Adding two numbers
Here we'll perform a program of adding two numbers and display it's result. The complete program is shown below.
1 /* Program addition of two numbers
3 Written by a programmer
2 */
3
4 main()
5 {
6 int number ;
7 float amount ;
8
9 number= 10 ;
10
11 amount= 25.90 + 35.25 ;
12 printf("%d\n", number) ;
13 printf("%5.2f", amount) ;
14 }
This program after execution will produce an output:
10
61.15
The first two lines of the program are comment lines. It is a good practice to use a comment line at the beginning of the program to give information such as the name of the program, date, etc.
In lines 5 and 6, the words number and amount are variable names that are used to store numeric data(integer and real). In C language, all variables should be declared to tell the compiler what the variable names are and what type of data they hold.
The declaration of variable happens like this:
int number ;
float amount ;
It tells the compiler that the number is an integer and the amount is a floating point number. A declaration statement must appear at the beginning of the function. All declaration statements end with a semicolon (;).
*Remember int and float are called keywords and can't be used as variable names.
Data is stored in a variable by assigning a data value to it. In line 8, an integer value of 10 is assigned to the integer variable number. In line 10, the result of the addition of two real numbers is assigned to the floating point variable amount.
number= 10 ;
amount= 25.90 + 35.25 ;
In the next line, there is a print statement containing two arguments. The first one is "%d" which 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.
printf("%d\n" , number) ;
The last line statement of the program
printf("%5.2f", amount) ;
It prints out the value of the amount in floating point format, The formate specification is "%5.2f" which tells the compiler that the output must be in floating point with five places all and two places to the right of the decimal point.
*Note, Remember some important things that you will use most of the time. That is:
1. "%d" is used for printing integer values.
2. "%f" is used for printing real values.
there are other formats that will discussed later.
----------------------------------------------------------------------------------------------------------------------------
Explore our website for valuable C programming resources and enhance your coding skills today!.
Learn C programming language from basic to advanced here (Click here or on the image)
Stay Strong, keep learning, and keep growing.