Learn C programming - Addition of two numbers

Tuesday, February 16, 2010

Let us study a simple C program to add two numbers , input from keyboard and print the sum.


#include <stdio.h>
#include <conio.h>

void main ( )
{ int a, b, sum;
clrscr( );
printf ("Enter two integer numbers");
scanf ("%d%d,&a,&b);
sum=a+b;
printf("\n The sum of two numbers is %d\n",sum);
getch( );
}

The first two lines with #include are called pre processor directives which loads two function libraries in memory. Because of which we can use functions like clrscr, printf , scanf in our program.

Third line is main function , which is must in any C program. void means the function will not return any value. If we do not write void , we have to add one line return (0) at the end of the program. Because in C every function must return a value.

Fourth line is declaration of variables a,b and 'sum' as integers. In C we must declare type of the variable before we can use it .

Fifth line is clear screen function which clears the previous screen i.e. any previous output on the screen is cleared .

Printf in sixth line displays message on screen to enter two numbers

Scanf in seventh line accepts two numbers from keyboard and assign these to variables a , b

The eighth line adds two variables a and b and assigns it value to variable 'sum'

Ninth line prints the value of sum on screen . The printf statement here uses format specifier %d here , we will study about this later.

The getch in tenth line holds the output screen till we press a key.

From the above program we can say that a general program in C will have

#include lines to include necessary library functions

void main ( )

Declaration and initialization of the variables required in the program

Data input statements

Processing or logic statements generating desired output

Statement to display output.

Please note that the all C keywords in program has to be in lower case because C is case sensitive language and any capital letter for commands/keywords gives error.

0 comments: