Thursday, 31 August 2017

Simple Numeric i/o in C++

This example reads in three numbers of users and the number and average them and then print out the sum and average.


  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. float a,b,c,sum=0.0, average=0.0 ;
  6. int n=3 ;
  7. cout << " Then type the three numbers \n" ;
  8. cin >> a >> b >> c ;
  9. sum = a + b + c ;
  10. average = sum / n ;
  11. cout << " And the numbers were " ;
  12. cout << a << " " << b << " " << c << " \n" ;
  13. cout << " The sum is " << sum << " \n" ;
  14. cout << " The average number is " << average << "\n" ;
  15. return(0) ;
  16. system("pause");
  17. }
The first line #include <iostream> makes available cin and cout so that we can
interact with the program.
The next line makes available the standard namespace.
The next line is the start of the program.
The { indicates the start of the declaration and executable part of the program.
The next two lines declare the variables we will be using within the program and their
types. In this example we will be working with numeric data, and thus we have a, b,
c, sum and average to be of real type, or float in C++ terminology. n is of type integer
or int in C++ terminology.
The semicolon ; is the statement separator.
Note that we also provide initial values for sum, average and n within the declarations. The
= symbol is an assignment operator.
cout << " Then type the three numbers \n" prompts the user for input. Note the
use again of \n to provide a newline.
cin >> a >> b >> c reads three numbers from the input stream. Spaces are valid
separators. Note the use of multiple >> symbols to break up the input stream, not a comma
as in other languages.
sum = a + b + cadds the values of a, b and c together and assigns the result to sum.
average = sum / n calculates the sum divided by n and assigns the result to average.
cout << " And the numbers were  " prints out a text message.
cout << a << " " << b << " " << c << " \n" echos the numbers back to the user. 
Note that we use multiple << symbols to break up the output stream, not a comma as in other languages.
cout << " The sum is " << sum << " \n" prints out the sum.
cout << " The average number is " << average << "\n" prints out the average.
return(0) ends the program and returns the value 0 to the operating system level.
system("pause"); use to hold the screen.
} is the end of the program.
We have the conventional use of + and / in arithmetic expressions.

0 comments:

Post a Comment

Tech UOG