Printing Output
Printing output to screen is achieved using readymade library functions. One suchfunction is printf( ).
General Form of printf() is as follow: -
printf ( "<format string>", <list of variables> );
<format string> can contain,
%f for printing real values
%d for printing integer values
%c for printing character values
In addition to format specifiers like %f, %d and %c the format string may also contain any other characters. These characters are printed as they are when the printf( ) is executed.
Examples
The output of the last two statement would look like this...
Rate of Interest = 6.5
Principal 1000
Simple Interest = Rs. 1300
Simple Interest = Rs. 1300
What is ‘\n’ doing in this statement? It is called newline and it takes the cursor to the next line. Therefore, you get the output split over two lines. ‘\n’ is one of the several Escape Sequences available in C which we will cover in the subsequent chapters.
Receiving Input: -
In the program discussed above we have assigned value to principal, rate and duration. Every time we run the program we would get the same value for simple interest.
If we want to calculate simple interest for some other set of values then we are required to make the relevant changes in the program, and again compile and execute it. Thus this program is not generalised and will not work for any set of values.
To make the program general the program itself should ask the user to supply the values of principal, rate of interest and duration (no of years)through the keyboard during execution.
This can be achieved using a function called scanf( ). This function is a counter-part of the printf( ) function. printf( ) outputs the values to the screen whereas scanf( ) receives them from the keyboard.
Example
The first printf( ) outputs the message ‘Enter values of principal, rate, duration on the screen. Here we have not used any expression in printf( ) which means that using expressions in printf( ) is optional.
Note that the ampersand (&) before the variables in the scanf( ) function is a must. & is an ‘Address of’ operator’. It gives the location number used by the variable in memory. When we say &a, we are telling scanf( ) at which memory location should it store the value supplied by the user from the keyboard.
We will cover AddressOf operation in detail in subsequent chapters.
Note that a blank, a tab or a new line separates the values supplied to scanf( ).
Example The three values separated by blank
1000 6.5 2
Ex.: The three values separated by tab.
1000 6.5 2
Ex.: The three values separated by newline.
1000
6.5
2
Output:-
Principal =1000 Rate of Interest = 6.5 Duration = 2
Simple interest = Rs. 130
In above example int, float are all data types which we will cover in detail in subsequent chapters.