next up previous
Next: The if-else-if Ladder Up: If Statement Previous: else Statement

Nested ifs

a nested if is an if statement that is the target of another if or else. Nested ifs are very common in programming. The main thing to remember about the nested if in C++ is that an else statement is always refers to the nearest if statement within the same block. The nested if may appear in a a program as

if(condition 1) (outside block) { //beginning of (condition 1 block)
if(condition 2) statement 1;
if(condition 3) statement 2;
else statement 3; // this else is for condition 3 (nearest if in the block)
} //end of condition 1 block
else statement 4;// this else is for condition 1 (outside block)

The final else is not associated with if(condition 2) even though it is the closet if without an else, because it is not in the same block. Rather, the final else is associated with if(condition 1). C++ allows at least 256 levels of nesting. In practice you will never need to nest if that many times.

Example

/* This program uses the nested if and modify the previous example*/

#include <iostream.h>
#include <stdlib.h>

main ( )
{
int hope; // number generated by computer randomly
int guess;// number guessed by user
hope=rand(); // assign a random number to hope
cout << "Guess an integer number";
cin >> guess;
if(guess==hope)
{
cout << "Congratulation you are a winner $\backslash$n";
cout << "You have guessed correctly $\backslash$n";
}
else
{
cout << "Sorry, your guess is wrong";
if(guess>hope) cout<<"Your guess is too high $\backslash$n";
else cout <<"Your guess is too low $\backslash$n";
}
return 0;
}


next up previous
Next: The if-else-if Ladder Up: If Statement Previous: else Statement
Yousef Haik
2/23/1998