Write Your First Program in C

Program is set of instructions for a computer to execute. The first Program every website teaches is to print "Hello World !", We will be looking in to printing the "Hello World !".

To start coding open the favorite editor vi / notepad and write the below program and save it as hello.c

#include <stdio.h>                                     //line1
int main() {                                                //line2
    printf("%s \n", "Hello World !");           //line3
}                                                                 //line4

The above Hello World program hello.c is a set of instruction for the C compiler. 

Line1 Instructs the compiler to include the header file stdio.h. 

Line2 Instructs the compiler to start the execution from the main() function, also int that is start of the main() function is the return value of main() function, and open flower braces indicates the start of the main() function.

Line3 Instructs the Compiler to print the string type %s followed by new line "/n" and the string is "Hello World !". Every statement in C program should end with semicolon but this rule does not apply for function definition, while loop, for loop and if statements

Line4 Instructs the closing brace is end of the main() function and also the end of the program.

Compile and Run the object file

[root@linux01 ~]#
[root@linux01 ~]# gcc hello.c -o hello
[root@linux01 ~]# echo $?
0
[root@linux01 ~]#
[root@linux01 ~]# ./hello
Hello World !
[root@linux01 ~]#
[root@linux01 ~]# 

In order to compile the C program we need to first compile the program and remove any syntax errors and compile time errors to do this we execute "gcc hello.c -o hello" and generate the new object file hello. As we see echo $? return code is zero there are no syntax errors or compile time errors detected by C Compiler.

Execute the object file ./hello will get the result "Hello World !" onto the standard output.

Executing the C Program with out using main function

#include<stdio.h>                                     //line1
#define here main                                     //line2

int here() {                                                 //line3
    printf("%s \n", "Hello World !");           //line4
}                                                                 //line5

In the above Hello World program we see a difference line2 and line3. #define is a directive that will replace the contents of here with main during the compile time. So after the compilation is done the line3 will become int main() { instead of int here() {. So execution will be as same as printing Hello World !.

 



 



Post a Comment

0 Comments