Learn C - Running your first c program

C is a programming languages. So what better way is there to learn the language, than programming in it. Let us plunge into the water. Let us write our C program.


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

This program just prints hello world on the screen. Let us see it in action. You need to type the program, compile it and then execute it.
   Are you using Windows system? Then you need either turbo-c IDE or you can use Visual C++ IDE from Microsoft . You can download. You can download VC++ from http://www.softpedia.com/get/Programming/Other-Programming-Files/Microsoft-Visual-C-Toolkit.shtml.
 You are using Linux System
  1. If you are using unix/linux os, then gcc compiler comes along. You have to type your program using some text editor. gedit is a good editor in Linux similar to notepad. Type your program using editor. Now save your program firstprogram.c Note that the file name must have extension .c
  2. compile your program. Go to the command prompt. And type the command
        gcc yourdirectory/firstprogram.c
    Replace yourdirectory with complete directory name where your c program is stored.
  3. If there are any mistakes in the program, you will see these errors with their line numbers. If there are no errors, you just see the command prompt.
  4. Verify that you have a file called a.out by giving ls command.
  5. Execute the program by giving the command
            ./a.out
    You will see
$./a.out
Hello world
$
     
     Now we are ready to analyse the program.
    1. First line #include<stdio.h> tells the compiler to include the header file. Header files will have declarations of library functions. All your programs must include the stdio.h file
    2. Second line int main() is used to define the main function. Functions are parts of c program which do some actions and return an answer. main is a special function because it is where the program execution begins. So every program must have a main function
    3. Third line is just a curly bracket. Every function must be enclosed in a pair of braces or curly brackets.
    4. Fourth line calls the library function printf(print formatted) to print a message on the display. The message to be displayed is in quotes. \n is a special character which displays a return.
    5. Fifth line return 0; is used because very program must return a 0 if it is successful. And as this 0 is an integer, you use int main()- read as main is a function which returns an integer.
    6. Also note that every c statement ends with a ;

Comments

Popular Posts