2.4. Another C++ Program: Adding Integers

Our next program obtains two integers typed by a user at the keyboard, computes the sum of these values and outputs the result using std::cout. Figure 2.5 shows the program and sample inputs and outputs. In the sample execution, we highlight the user’s input in bold. The program begins execution with function main (line 6). The left brace (line 7) begins main’s body and the corresponding right brace (line 22) ends it.


 1   // Fig. 2.5: fig02_05.cpp
 2   // Addition program that displays the sum of two integers.
 3   #include <iostream> // allows program to perform input and output
 4
 5   // function main begins program execution
 6   int main()
 7   {
 8      // variable declarations
 9      int number1 = 0; // first integer to add (initialized to 0)  
10      int number2 = 0; // second integer to add (initialized to 0) 
11      int sum = 0; // sum of number1 and number2 (initialized to 0)
12
13      std::cout << "Enter first integer: "; // prompt user for data
14      std::cin >> number1; // read first integer from user into number1
15
16      std::cout << "Enter second integer: "; // prompt user for data
17      std::cin >> number2; // read second integer from user into number2
18
19      sum = number1 + number2; // add the numbers; store result in sum
20
21      std::cout << "Sum is " << sum << std::endl; // display sum; end line
22   } // end function main


Enter first integer: 45
Enter second integer: 72
Sum is 117


Fig. 2.5. Addition program that displays the sum of two integers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.62