Thursday, 15 March 2012

C Programming - Sample - 2 - Adding Two Numbers


ADDING TWO NUMBERS

Consider another program, which performs addition on two numbers and displays the result. The complete program is shown :

 

This program when executed will produce the following output:

100
106.10

The first two lines of the program are comment lines. It is a good practice to use comment lines in the beginning to give information such as name of the program, author, date, etc. Comment characters are also used in other lines to indicate line numbers.
The words number and amount are variable names that are used to store numeric data. The numeric data may be either in integer form or in real form. In C, all variables should be declared to tell the compiler what the variable names are and what type of data they hold. The variables must be declared before they are used. In lines 5 and 6, the declarations

int number; fl 
oat amount ;

tell the compiler that number is an integer (int is the abbreviation for integer) and amount is a floating (float) point number. Declaration statements must appear at the beginning of the functions as shown in Fig. All declaration statements end with a semicolon .

The words such as int and float are called the keywords and cannot be used as variable names. 

Data is stored in a variable by assigning a data value to it. This is done in lines 8 and 10. In line- 8. an integer value 100 is assigned to the integer variable number and in line-10, the result of addi¬tion of two real numbers 30.75 and 75.35 is assigned to the floating point variable amount. The statements
number = 100;
amount = 30.75 + 75.35;
are called the assignment statements. Every assignment statement must have a semicolon at the end. The next statement is an output statement that prints the value of number. The print statement
printf ("%d \ n", number);
contains two arguments. The first argument "%d" tells the compiler that the value of the second argument number should be printed as a decimal integer. Note that these arguments are separated by a comma. The newline character \n causes the next output to appear on a new line. The last statement of the program
printf("%5.2f", amount);

prints out the value of amount in floating point format. The format specification %5.2f tells the compiler that the output must be infloating point, with five places in all and two places to the right of the decimal point.


No comments:

Post a Comment