Saturday, February 28, 2009

Basic Structure of a C Program

To ensure easy understanding of this language, a lot of examples will be given to make sure you understand better.

A basic program that displays the message "Hello World!"is as below


#include< stdio.h>
int main()
{
printf("Hello World!\n");
return 0;
}


We shall look each of the statements one at a time.

#include <>stdio.h<>
This line tells the program to include stdio.h library functions into the program, so that input and output functions can be used.This is a preprocessor directive, which always starts with a hash, #. This does not affect the program in anyway, it is just to enable the compiler to recognize input and output functions.

int main()
Every program needs to start at a certain point. Therefore, he compiler will always start the program from the main function. The 2 curly braces that can be found in the beginning of the main function and the end of the program indicates the functions that are inclusive in the main function. All functions, statements , expressions and code are to be entered inbetween those 2 curly braces.

printf("Hello World!\n");
This line tells the program to produce the message "Hello World!". The printf() function is an output function where it displays messages and other stuff. We will talk about that later.

return 0;
Each function, such as int main() returns a value back to the function, which indicates that all the statements and code before the return 0; statement are successfully executed. This can be marked as an end point, in this case, your program.


Note: The program can also be coded as below:


#include< stdio.h>
int main(){printf("Hello World!\n");return 0;}

Notice that I have omitted the new lines in the code above. This means that the C language does not take spacing and new lines into consideration, we just add them to make your program look structured and tidy.

No comments: