codescracker


c++

C++ if if-else if-else-if switch Statements



« Previous Tutorial Next Tutorial »


The selection (if, if-else, if-else-if, and switch) statements allows to choose the set-of-instructions for execution depending upon an expression's truth value. C++ provides following two types of selection statements:

In addition, in certain circumstances ? operator can be used as an alternative to if statement. The selection statements are also called conditional statements or decision statements (as already discussed in the previous tutorial). We will learn about selection statements of C++ in detail, divided into these parts:

C++ if Statement

An if statement tests a particular condition; if the condition evaluates to true, a course-of-action is followed i.e., a statement or set-of-statements is executed. Otherwise (if the condition evaluates to false), the course-of-action is ignored. Here is the syntax or general form of the if statement:

if(expression)
{
	statement(s);
}

Here, statement may be a single statement or a block of statements, or nothing (in case of empty statement). The expression must be enclosed in parentheses. If the expression evaluates to true i.e., a nonzero value, the statement is executed, otherwise ignored. For example, the following code fragment :

if(ch == ' ')
{
	spaces++;
}

Checks whether the character variable ch stores a space or not; if it does, the number of spaces are incremented by 1. Consider another example illustrating the use of if statement :

char ch;
cin >> ch;
if(ch == ' ')
{
	cout << "You entered a space" << "\n" ;
}
if(ch >= '0' && ch <= '9')
{
	cout << "You entered a digit" << "\n";
}

The above example reads a character. If the character input is a space, if flashes a message specifying it. If the character input is a digit, it flashes a message specifying it. Let's take an example demonstrating the if statement of C++ practically.

/* C++ Selection Statements - C++ if Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	char ch;
	cout<<"Enter a character: ";
	cin>>ch;
	if(ch>='0' && ch<='9')
	{
		cout<<"You entered a digit.";
	}
	getch();
}

Here is the sample run of the above C++ program:

c++ selection statements

Let's take another example, also demonstrating the if statement of C++

/* C++ Selection Statements - C++ if Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int num;
	cout<<"Enter a number: ";
	cin>>num;
	if(num%2==0)
	{
		cout<<"You entered an even number";
	}
	getch();
}

Here is the sample run of this C++ program:

c++ if statement

Following example programs also illustrates the syntax and working of the if statement :

/* C++ Selection Statements - C++ if Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int x, y, z, max;
	cout<<"Enter any three numbers: ";
	cin>>x>>y>>z;
	max = x;
	if(y>max)
	{
		max = y;
	}
	if(z>max)
	{
		max = z;
	}
	cout<<"\n"<<"The largest of "<<x<<", "<<y<<" and "<<z<<" is "<<max;
	getch();
}

When the above C++ program is compile and executed, it will produce the following output. This is the output, if 3rd number is biggest.

if statement c++

Here is another output, if 2nd number is biggest.

c++ if

Now, here is the last output, if 1st number is biggest:

c++ if statement program

C++ if-else Statement

The examples of if statement, you have seen so far allow you to execute a set of statements if a condition or expression evaluates to true. What if there is another course of action to be followed if the expression evaluates to false ?

There is another form of if that allows for this kind of either-or condition by providing an else clause. The syntax of the if-else statement is the following :

if(expression)
{
	statement 1;
}
else
{
	statement 2;
}

If the expression evaluates to true i.e., a nonzero value, the statement 1 is executed, otherwise, statement 2 is executed. The statement 1 and statement 2 can be a single statement, or a compound statement, or a null statement.

Note - Remember, in an if-else statement, only the code associated with if (i.e., statement 1) or the code associated with else (i.e., statement 2) executes, never both.

Let's take an example program, demonstrating the if-else statement of C++, practically.

/* C++ Selection Statements - C++ if-else Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int num;
	cout<<"Enter a number: ";
	cin>>num;
	if(num%2==0)
	{
		cout<<"You entered an even number";
	}
	else
	{
		cout<<"You entered an odd number";
	}
	getch();
}

Below are the two sample run of the above C++ program:

c++ if-else statement

c++ if else

Here is another program, also illustrating the use of if-else statement in a C++ program:

/* C++ Selection Statements - C++ if-else Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int x, y ;
	cout<<"Enter two numbers: ";
	cin>>x>>y;
	if(x>y)
	{
		cout<<x<<" is largest";
	}
	else
	{
		cout<<y<<" is largest";
	}
	getch();
}

When the above C++ program is compile and executed, it will produce the following output:

if-else statement c++

Important - Placement of semicolon is also important. In an if statement, DO NOT put semicolon in the line having test condition, such as

if (y > max) ; // DO NOT do this

Caution - If you put a semicolon after the test condition, the if statement ends there. The block or statements following are no more part of if in such cases. Now, let's discuss nested ifs statement in C++.

C++ Nested Ifs Statement

A nested if is an if that has another if in its if's body or in its else's body. The nested if can have one of the following three forms. Here is the first form:

if(expression 1)
{
	if(expression 2)
	{
		statement 1;
	}
	else
	{
		statement 2;
	}
}
else
{
	body-of-else;
}

This is the second form of nested ifs statement

if(expression 1)
{
	body-of-if;
	else
	{
		if(expression 2)
		{
			statement 1;
		}
		else
		{
			statement 2;
		}
	}
}

Now, this is the third form of nested ifs statement

if(expression 1)
{
	if(expression 2)
	{
		statement 1;
	}
	else
	{
		statement 2;
	}
}
else
{
	if(expression 3)
	{
		statement 3;
	}
	else
	{
		statement 4;
	}
}

In an if statement, either there can be if statement(s) in its body-of-if or in its body-of-else or in both. The inner ifs can themselves be nested ifs, but the inner if must terminate before an outer if. Following example programs illustrates the use of nested ifs

/* C++ Selection Statements - C++ nested ifs Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int num;
	cout<<"Enter a number: ";
	cin>>num;
	if(num>100)
	{
		if(num>500)
		{
			if(num>10000)
			{
				cout<<"Its too high..!!";
			}
			if(num<1000)
			{
				cout<<"Its medium..!!";
			}
		}
		if(num<=500)
		{
			cout<<"Its low..!!";
		}
	}
	if(num<=100)
	{
		cout<<"Its too low..!!";
	}
	getch();
}

Here are the sample runs of the above C++ program:

c++ if else if

c++ if else if program

C++ if-else-if Ladder

A common programming construct in C++ is the if-else-if ladder, which is often also called the if-else-if staircase because of its appearance. It takes the following general form :

if(expression)
{
	statement 1;
}
else if(expression 2)
{
	statement 2;
}
else if(expression 3)
{
	statement 3;
}
.
.
.
else
{
	statement N;
}

The expression are evaluated from the top downward. As soon as an expression evaluates to true, the statement associated with it is executed and the rest of the ladder is bypassed. If none of the expression are true, the final else gets executed. If the final else is missing, no action takes place if all the conditions are false. Following are some examples illustrates the use of if-else-if ladder in a C++ program:

/* C++ Selection Statements - C++ if-else-if Ladder */

#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	char ch;
	float a, b, result;
	cout<<"Enter any two number: ";
	cin>>a>>b;
	cout<<"\n"<<"Enter the operator(+, -, *, /) : ";
	cin>>ch;
	cout<<"\n";
	if(ch=='+')
		result=a+b;
	else
		if(ch=='-')
			result=a-b;
		else
			if(ch=='*')
				result=a*b;
			else
				if(ch=='/')
					result=a/b;
	cout<<"\n"<<"The calculated result is : "<<result<<"\n";
	getch();
}

Here are the two sample runs of the above C++ program:

c++ if-else-if ladder

if else if ladder

Here is the improved version of the above C++ program.

/* C++ Selection Statements - C++ if-else-if Ladder */

#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
	clrscr();
	char ch;
	float a, b, result;
	cout<<"Enter any two number: ";
	cin>>a>>b;
	cout<<"\n"<<"Enter the operator(+, -, *, /) : ";
	cin>>ch;
	cout<<"\n";
	if(ch=='+')
	{
		result=a+b;
	}
	else if(ch=='-')
	{
		result=a-b;
	}
	else if(ch=='*')
	{
		result=a*b;
	}
	else if(ch=='/')
	{
		result=a/b;
	}
	else
	{
		cout<<"Wrong Operator..!!.. exiting...press a key..";
		getch();
		exit(1);
	}
	cout<<"\n"<<"The calculated result is : "<<result<<"\n";
	getch();
}

When the above C++ program is compile and run, it will produce the following outputs:

c++ nested ifs statement

Here is another sample run of the above C++ program:

nested ifs c++

Here is one more sample run of the above C++ program:

if-else statement

Let's take another C++ program, for the complete understanding on the if-else-if ladder in C++. Before going to this program, let's see the following table to understand the ASCII code for different character. Because the upcoming program print whether a given character is an upper case or a lower case character or a digit or any other character. Use the ASCII codes for it. The ASCII codes are given here in the following table:

Characters ASCII Range
'0' - '9' 48 - 57
'A' - 'Z' 65 - 90
'a' - 'z' 97 - 122
Other Characters 0 - 255 excluding the above mentioned codes

Let's now look at the following program:

/* C++ Selection Statements - C++ if-else-if Ladder */

#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	char ch;
	cout<<"Enter a character: ";
	cin>>ch;
	if(ch >= 48 && ch <= 57)
	{
		cout<<"\nYou entered a digit";
	}
	else if(ch >= 65 && ch <= 90)
	{
		cout<<"\nYou entered an uppercase character";
	}
	else if(ch >= 97 && ch <=122)
	{
		cout<<"\nYou entered a lowercase character";
	}
	else
	{
		cout<<"\nYou entered a special character";
	}
	getch();
}

When the above program is compile and executed, it will produce the following output:

c++ if else if statement

if else if program

if else if example

The ? : (Alternative to if)

C++ has an operator that can be used as an alternative to if statement. You are familiar with this operator, the conditional operator ? : This operator can be used to replace if-else statements of the general form:

if(expression1)
{
	expression2;
}
else
{
	expression3;
}

The above form of if can be alternatively written using ? : as follows,

expression1 ? expression2 : expression3 ;

It works in the same way as the above given form of if does i.e., expression1 is evaluated, if it is true, expression2 gets executed (i.e., its value becomes the value of entire expression) otherwise expression3 gets executed (i.e., its value now becomes the value of the entire expression). For example, the following if statement :

int c;
if(a>b)
{
	c=a;
}
else
{
	c=b;
}

can be alternatively written as

int c = a > b ? a : b ;

See how simple and compact your code has become.

if Vs ? :

Here are some points differentiating the if statement and ? : (alternative to if) also called as conditional operator.

C++ switch Statement

C++ provides a multiple-branch selection statement known as switch. This selection statement successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed. The syntax of switch statement is as follows:

switch(expression)
{
	case constant1 : statement sequence 1;
			break;
	case constant2 : statement sequence 2;
			break;
	case constant3 : statement sequence 3;
			break;
	.
	.
	.
	case constant n-1 : statement sequence n-1;
			break;
	default : statement sequence n;
}

The expression is evaluated and its values are matched against the values of the constants specified in the case statements. When a match is found, the statement sequence associated with that case is executed until the break statement or the end of switch statement is reached. If a case statement does not include a break statement, then the control continues right on the next case statement(s) until either a break is encountered or end of switch is reached. This situation (i.e., missing break in case statement) is called fall through. The default statement gets executed when no match is found. The default statement is optional and, if it is missing , no action takes place if all matches fail.

The ANSI standard specifies that a switch can have upto 257 case statements, however, you must always limit the number of case statements to a smaller amount for the sake of efficiency.

Following example illustrates the use of switch statement. This program ask to the user to input number of week's day (1-7) and translate to its equivalent name of the day of the week (e.g., 1 to Sunday, 2 to Monday, ...., 7 to Saturday).

/* C++ Selection Statement - C++ switch Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int dow;
	cout<<"Enter number of week's day (1-7): ";
	cin>>dow;
	switch(dow)
	{
		case 1 : cout<<"\nSunday";
			break;
		case 2 : cout<<"\nMonday";
			break;
		case 3 : cout<<"\nTuesday";
			break;
		case 4 : cout<<"\nWednesday";
			break;
		case 5 : cout<<"\nThursday";
			break;
		case 6 : cout<<"\nFriday";
			break;
		case 7 : cout<<"\nSaturday";
			break;
		default : cout<<"\nWrong number of day";
			break;
	}
	getch();
}

When the above program is compile and executed, it will produce the following output:

c++ switch case

Here is another sample output of the above C++ program:

c++ switch statement

switch Vs if-else

The switch and if-else both are selection statements and they both let you select an alternative out of given many alternatives by testing an expression. However, there are some differences in their operations. These are given below:

C++ Nested-Switch

Like if statements, a switch can also be nested. There can be a switch as part of the statement sequence of another switch. For example, the following code fragment is perfectly all right in C++

switch(a)
{
  case 1 : switch(b)
		    {
			 case 0 : cout << "Divide by zero-Error !!" ;
					  	break;
			  case 1 : res = a/b ;
			}
			break;
  case 2 :
	   :
}

Some important Things to know about switch

There are some important things that you must know about the switch statement :

Tip - A switch statement is more efficient than nested if-else statement.

Tip - Always put a break statement after the last case statement in a switch.

More Examples

Here are some more C++ programs listed, that you may like:


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test