About  Contact

Let us Practice some C++ Programs

Choose proper data type:
While writing C++ programs, one thing remember you must choose proper data type, otherwise the result may not be accurate. For example if in the program you are doing any division operation then there is very much chance that result is in fraction, but if your data type of the variable to store the result is "int" then the fractional part will be lost. Therefore the data type must be of float. Now let us practice programs.

Q2. Write a program to accept three numbers then find their average.
Q3. Write a program to accept principal, rate of interest and time then find the simple interest
Q4. Write a program to accept marks obtained in five different subjects out of 100 then find total and percentage of marks.

#include <iostream.h>
void main(){
    int a, b, c;
    float d;
    cout<<"Enter the first No:";
    cout<<"Enter the second No:";
    cout<<"Enter the third No:";
Note:Notice that the data type of result variable here variable "d" is float. Another point to be noticed that the sum is divided by 3.0 this means that the sum would be converted into float data type by the compiler itself then it would be divided by 3.0, so if the result has got any fractional part it will be stored in "d". If the sum is divided by 3 then, first the result would be generated in integer then it would be converted in float as the left hand side of the assignment operator is of type float; so the result would be only integral part of a real number ( or a zero at the fractional part of the answer.)
Another point to be noted that students often do mistake in writing the line d=(a+b+c)/3.0; they write it as d=a+b+c/3.0 here the answer becomes wrong because only the value of "c" is divided by 3 and is added with the sum of "a" and "b". This line can be broken down into two line as below-
Take another int variable "k"

#include <iostream.h>
void main(){
    float p, r, t,si;
    cout<<"Enter Principal:";
    cout<<"Enter Rate of Interest:";
    cout<<"Enter Time in years:";

#include <iostream.h>
void main(){
    float phy, chem, eng, math, cs, total, percent;
    cout<<"Enter marks of english:";
    cout<<"Enter marks of physics:";
    cout<<"Enter marks of chemistry:";
    cout<<"Enter marks of maths:";
    cout<<"Enter marks of computer sc:";
    total=eng + phy + chem + math + cs;
    percent = total/500*100;
Note: In the program-4 the line "percent=total/500*100" we have written 500 still the result is correct because here all data type are float. In this program "\n" is used to display Total and Percentage in two different lines we can use "endl" instead of "\n", endl is used without quotes. Write and run the programs and see the outputs.