Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating Expressions and Statements 87

4


LISTING4.6 A Complex, Nested ifStatement


1: // Listing 4.6 - a complex nested
2: // if statement
3: #include <iostream>
4: int main()
5: {
6: // Ask for two numbers
7: // Assign the numbers to bigNumber and littleNumber
8: // If bigNumber is bigger than littleNumber,
9: // see if they are evenly divisible
10: // If they are, see if they are the same number
11:
12: using namespace std;
13:
14: int firstNumber, secondNumber;
15: cout << “Enter two numbers.\nFirst: “;
16: cin >> firstNumber;
17: cout << “\nSecond: “;
18: cin >> secondNumber;
19: cout << “\n\n”;
20:
21: if (firstNumber >= secondNumber)
22: {
23: if ( (firstNumber % secondNumber) == 0) // evenly divisible?
24: {
25: if (firstNumber == secondNumber)
26: cout << “They are the same!\n”;
27: else
28: cout << “They are evenly divisible!\n”;
29: }
30: else
31: cout << “They are not evenly divisible!\n”;
32: }
33: else
34: cout << “Hey! The second one is larger!\n”;
35: return 0;
36: }

Enter two numbers.
First: 10

Second: 2
They are evenly divisible!
Two numbers are prompted for one at a time, and then compared. The first if
statement, on line 21, checks to ensure that the first number is greater than or
equal to the second. If not, the elseclause on line 33 is executed.

OUTPUT


ANALYSIS
Free download pdf