Basic C Program

Enough of basics, we will quickly move into programming. I will start with a very simple program and start explaining to you on how to write a C Program and compile it using Dev CPP. Whatever may be the compiler, the steps will be almost similar. Have a look at the following program. It simply displays "Welcome to http://c-thebasics.blogspot.com".

Code
#include<stdio.h>
main()
{
printf("Welcome to http://c-thebasics.blogspot.com");
}
As I have already described in this post, there are many inbuilt functions and they are grouped to form library files. These files can be included in the program and the functions in those library can be used. The first statement includes the standard input/output library. Extension of the file .h stands for Header file, it contains the definition (let us see what they are later) for input/output functions. This is called a Pre-processor directive (Processed before compilation phase)

main() - Is a user defined function. Every program starts execution from this point. The opening brace { and closing brace } tells the compiler where the function starts and ends.

printf - As I have said, it is a inbuilt function. Its job is to display whatever is given as input to it. Here the input is a string (group of characters).

Now what to do with this piece of code ? Open your C compiler, and open a new source file in it. Type the above code and save it as Welcome.c , where .c is the file extension.

If you are using Dev C++, go to Build -> Compile & Run (F9).
If you are using TurboC, go to Run -> Run (Ctrl + F9)

Ok, but what happened ? Nothing seemed to come up? Yes, because the output window has already came and closed in Dev C++. In TurboC, Press Alt+F5, to get to the outscreen.

In DevC++, the window has already closed. So we need a little work around to see the output.

Code
#include<stdio.h>
main()
{
printf("Welcome to http://c-thebasics.blogspot.com");
getch();
}
So what have we added extra ? getch(); What it does ? It is again a inbuilt function, and it is used for accepting a Single Character from our Keyboard, so until we press any key, the cursor stays there, Hence we will see the output. So usually I used to put this getch(); as the last line in a program.

Did you note something ? we have a semi colon at the end of every statement. This is how we tell the compiler that its an end of a line/statement.

Another point to be noted here is that, the above program still runs fine in Dev C++, without errors even if the stdio.h header file is not included. Possible reason is that, it is automatically included by DevC++ compiler when compiling & executing the program. In TurboC, it will show error.

0 comments:

Post a Comment

 
Template designed using TrixTG