Page 41 - Modular_V1.1_Flipbook
P. 41
Let us take an example given below:
void main()
{
int age;
cout<<”Enter you age: “;
cin>>age;
if (age < 18)
{
cout << “You are eligible to vote.”;
}
cout<<”Outside the if statement”;
}
In the preceding code, if the value in age of less than 18, the statement written inside the if
statement is executed. Otherwise, C++ skips the entire block and continues with the program.
Program1: To take a number from the user as input and print the cube of it. Show a message
“Too Large Number”, if user enters a number greater than 20.
#include<iostream.h>
#include<conio.h>
void main()
{
int n, cu;
cout<<”Enter a number less than 21: “;
cin >> n;
if (n <= 20)
{
cu = n * n * n;
cout<<”The cube of “<< n << “ is: “ << cu; Output 1:
} Enter a number less than 21: 20
if (n > 20) The cube of 20 is: 8000
{ Output 2:
cout<<”Too Large Number”; Enter a number less than 21: 25
} Too Large Number
getch();
}
THE IF…ELSE STATEMENT
The if…else statement checks for a condition. If the condition evaluates to True, the statement(s)
in the if block is executed, otherwise the statements in the else block is executed.
Conditional Statements 39

