next up previous
Next: Nested ifs Up: If Statement Previous: Blocks of Code

else Statement

The else statement never appears in a program with out an if statement. The else statement provides an alternative for false condition. This section introduces the else statement by showing you the if-else combination, its format can be


\begin{emph}
if(condition) statement;\ else statement;\end{emph}

or when you have blocks as:

\begin{emph}
if(condition)\ \{\ sequence of statements \  
\}\ else\ \{\  one or sequence of statement(s)\  \}\  \end{emph}

Example

/* In this example you will see a demo of using the if-else combined statements and a new header file. The header file used in this example is stdlib.h which stands for standered library. A predefined function that is capable of generating a random integer number the function used for this purpose is rand() */

#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";
cout << "Correct guess was $\backslash$t" << hope << endl;
}
return 0;
}



Yousef Haik
2/23/1998