logo codesdope

Decide if or else


Till now, you have just seen how to take input and print anything on the screen. Now, your real coding part will begin.

Many times, we need to first see the conditions and accordingly make a decision. For example, if it is raining, we will take an umbrella otherwise not. Similarly, if a number is divisible by 2, it is even, otherwise, it is odd.

if and else C++

We take such type of decisions in C++ also by using if...else.

if statement


Again take the example of raining. If it is raining, a person will take an umbrella.

In C++, such type of decisions are taken using if statement. Let's first have a look at its syntax.

if(condition)
{
    statements
}

If the condition written within the brackets of if statement is true, then the statements written in the body of the if statement (i.e. within the curly braces '{ }') get executed.

Let's see an example of if statement.

#include <iostream>
int main()
{
	using namespace std;
	
	int a, b;
	a = 45;
	b = 45;
	if(a == b)
	{
		cout << "a is equal to b" << endl;
	}
	return 0;
}
Output
a is equal to b

Here the condition a == b is true and thus the statement in the body of the if statement got executed and "a is equal to b" got printed.
Note that { } represents the body of if. Whatever is written inside these curly braces is part of if.

So, the condition of if statement is checked and if found true, the statement(s) in its body are executed.

if...else statement


Now, consider that a chocolate costs 10 rupees and a candy costs 5 rupees. So, if you have at least 10 rupees, you can buy a chocolate, otherwise you have to buy a candy.

In the world of programming, this is done by using if...else statement. Let'see how.

if(condition)
    statement 1
else
    statement 2

If the condition is true, statement 1 will be executed. Otherwise, statement 2 gets executed.

Now, let's see the same example which we saw above, but this time using if...else statement.

#include <iostream>
int main()
{
	using namespace std;
	
	int a, b;
	a = 45;
	b = 47;
	if(a == b)
	{
		cout << "a is equal to b" << endl;
	}
	else
	{
		cout << "a is not equal to b" << endl;
	}
	return 0;
}
Output
a is not equal to b

In the above example, the value of 'a' is not equal to that of 'b'. Since the expression ( a == b ) is false, therefore the statement in the body of else i.e., 'cout << "a is not equal to b" << endl;' gets executed.

Consider one more example.

#include <iostream>
int main()
{
	using namespace std;
	int n;
	cout << "Enter number" << endl;
	cin >> n;
	if(n%2 == 0)
		cout << "Number is even" << endl;
	else
		cout << "Number is odd" << endl;
	return 0;
}
Output
Enter number
5
Number is odd

For a number to be even, it must be divisible by 2. This means that it should give a remainder 0 if divided by 2.
We entered 5 here and the value of n%2 i.e. 5%2 is 1. So, the statement in the body of else gets executed and Number is odd is printed on the screen.

To execute only one statement in if or else (as in previous example), you can skip curly brackets { }. If you want to execute multiple statements in if, then enclose the statements within curly brackets { }.
#include <iostream>
int main()
{
	using namespace std;
	int age;
	cout << "Enter your age" << endl;
	cin >> age;
	if(age >= 18)
	{
		cout << "You are 18+" << endl;
		cout << "Eligible to vote" << endl;
	}
	else
	{
		cout << "You are not yet 18" << endl;
		cout << "Not eligible to vote" << endl;
	}
	return 0;
}
Output
Enter your age
20
You are 18+
Eligible to vote

In this example, since the user entered the age as 20, which is greater than 18, so the condition age >= 18 became true. Therefore, the statements in the body of if got executed. If the user enters the age less than 18, then the condition 'age >= 18' will become false and the statements in the body of else statement will be executed.


Nested if/else statements

We can also use if or else inside another if or else if statements.

To understand this, let's see an example to print whether a number is the greatest or not by using one if inside another if.

#include <iostream>
int main()
{
	using namespace std;
	int x = 4, y = 3, z = 5;
	if(z > x)
	{
		if(z > y)
		{
			cout << "z is the greatest number" << endl;
		}
	}
	return 0;
}
Output
z is the greatest number

In the above example, the first expression i.e., (x>y) is true. So, the statements enclosed within the curly brackets {} of the first if condition will be executed.
Within the curly brackets, the first statement i.e., if(x>z) will be executed first.
Since this condition is true, the statement cout << "z is the greatest number" << endl; within the curly brackets of this if condition will be executed.

So, first we checked if 'x' is greater than 'y' or not. If it is, then we compared it with 'z'.

Isn't that simple?

Let's see the same example using if...else inside another if...else.

#include <iostream>
int main()
{
	using namespace std;
	int x = 4, y = 3, z = 5;
	if(x > y){
		if(x > z)
			cout << "x is the greatest integer";
		else
			cout << "x is not the greatest integer";
	}
	else
		cout << "x is not the greatest integer";
	return 0;
}
Output
x is not the greatest integer

Here the condition x > y is true. So the statements enclosed within the curly brackets { } of the first if condition will be executed. Within the curly brackets, the first line i.e. if( x > z ) will be executed first. Since this condition is false, the statement cout << "x is the greatest integer"; within the curly brackets of this if condition will not be executed. So, the statement of its corresponding else (i.e. the inner else) cout << "x is not the greatest integer"; will be executed.

We can also do the same thing using &&.

#include <iostream>
int main()
{
	using namespace std;
	int x = 4, y = 3, z = 5;
	if( (x > y) && (x > z))
		cout << "x is the greatest integer";
	else
		cout << "x is not the greatest integer";
	return 0;
}
Output
x is not the greatest integer

Here, the condition inside if will be true only if both (x > y) and (x > z) are true. If that is the case, then x will be the greatest number otherwise not.

else if statements


Many times we fall in situations when 'if' and 'else' are not sufficient. For example, if you have 5 rupees then you will buy a candy, or if you have 10 rupees, then a chocolate and if more than 100, then a cake. Thanks to C++, because it provides another tool 'else if' to get this done.

Consider this example to find the greatest among three numbers.

#include <iostream>
int main()
{
    using namespace std;
    int x = 4, y = 5, z = 1;;
    if ( (x > y) && (x > z) ){
        cout << "x is the greatest integer" << endl;
    }
    else if ( (y > x) && (y > z) ){
        cout << "y is the greatest integer" << endl;
    }
    else
        cout << "z is the greatest integer" << endl;
    return 0;
}
Output
y is the greatest integer

We can give condition in else if also. First, the condition of if will be checked. If it is false, then condition of else if will be checked, and if that is also false then else will be executed.

In the above example, we are given three numbers x, y and z and have to find the highest among them.
For that, first, we will compare the first number with the other two i.e., 'x' with both 'y' and 'z'. Now, if the condition (x>y && x>z) is true (if both are true, means x is the greatest ), then the statements enclosed within the curly brackets {} of the first if condition will be executed. If not so, then it will go to else if and check for (y>x && y>z). If this condition is true, then the corresponding statements will be executed, otherwise, it will go to else.

Let's see one more example.

#include <iostream>
int main()
{
    using namespace std;
    char grade = 'A';
    if( grade == 'A' ){
      cout << "Excellent !" << endl;
    }
    else if(grade == 'B'){
      cout << "Outstanding !" << endl;
    }
    else if(grade == 'C'){
      cout << "Good !" << endl;
    }
    else if(grade == 'D'){
      cout << "Can do better" << endl;
    }
    else if(grade == 'E'){
      cout << "Just passed" << endl;
    }
    else if(grade == 'F'){
      cout << "You failed" << endl;
    }
    else{
      cout << "Invalid grade" << endl;
    }
    return 0;
}
Output
Excellent !

First, the condition of if is checked. If it is true, then only the statements inside that 'if' are executed, otherwise it checks the condition inside else if. If it is true, then its body is executed, otherwise next else if is checked. If none of them are true then else is executed.

We can also solve the above example using switch..case, which makes the code much simpler.

Switch..case


Normally, if we have to choose one case among many choices, nested if-else is used. But if the number of choices is large, switch..case is a better option as it makes our code more neat and easier.

Let's have a look at its syntax.

switch(expression)
{
    case constant1:
        statement(s);
        break;
    case constant2:
        statement(s);
        break;
/* you can give any number of cases */
    default:
        statement(s);
}

In switch...case, the value of the expression enclosed in the brackets ( ) following switch is checked. If the value of the expression matches the value of the constant in case, the statement(s) corresponding to that case will be executed.

If the expression does not match any of the constant values, then the statements corresponding to default are executed.

Now, let's see the above example using switch..case.

#include <iostream>
int main(){
	using namespace std;
	char grade = 'B';
  	switch ( grade )
  	{
		case 'A':
      		cout << " Excellent ! " << endl;
    		 break ;
    	case 'B':
    		 cout << " Outstanding ! " << endl;
      		break ;
    	case 'C':
      		cout << " Good ! " << endl;
      		break ;
    	case 'D':
      		cout << " Can do better " << endl;
      		break ;
    	case 'E':
      		cout << " Just passed " << endl;
      		break ;
    	case 'F':
      		cout << " You failed " << endl;
      		break ;
    	default :
      		cout << " Invalid grade " << endl;
  	}
	return 0;
}
Output
Outstanding !

In this example, the value of grade is B. Since the value of the constants of the first case is not 'B', so case 'B' will be executed and 'Outstanding !' will be printed. Then break statement will terminate the switch without checking the rest of the cases. This is how it works.

No need to write break in default case because it automatically terminates once default statements are executed.

Now let's see what happens when we don't add break after the cases.

#include <iostream>
int main(){
	using namespace std;
	char grade = 'B';
  	switch ( grade )
  	{
    	case 'A':
      		cout << " Excellent ! " << endl;
    	case 'B':
      		cout << " Outstanding ! " << endl;
    	case 'C':
      		cout << " Good ! " << endl;
    	case 'D':
      		cout << " Can do better " << endl;
    	case 'E':
      		cout << " Just passed " << endl;
    	case 'F':
      		cout << " You failed " << endl;
    	default :
      		cout << " Invalid grade " << endl;;
  	}
	return 0;
}
Output
Outstanding !
Good !
Can do better
Just passed
You failed
Invalid grade

In the above example, the value of grade is 'B', so the control jumped to case 'B'. Since there is no break statement after any case, so all the statements after case 'B' will also be executed.

If you want to execute only that case whose constant value equals the value of the expression of switch statement, then use break statement.
Always enclose character values within ' '.

Let's see another example where the value of the expression is an integer.

#include <iostream>
int main(){
    using namespace std;
    int i = 2 ;
    switch ( i )
    {
    	case   1:
        	cout << "Number is 1" << endl;
         	break ;
      	case   2:
         	cout << "Number is 2" << endl;
         	break ;
      	default :
         	cout << "Number is greater than 2" << endl;
    }
	return 0;
}
Output
Number is 2

Another form of if else


We can also judge the condition using the ternary operator. The ternary operator checks whether a given condition is true and then evaluates the expressions accordingly. It works as follows.

condition ? expression1 : expression2;

If the condition is true, then expression1 gets evaluated, otherwise expression2 gets evaluated.

#include <iostream>
int main(){
	using namespace std;
	int age;
	cout << "Enter age" << endl;
	cin >> age;
	(age > 18) ? cout << "eligible to vote" : cout << "not eligible to vote";
	return 0;
}
Output
Enter age
5
not eligible to vote

Here, if the condition (age > 18) is true, then expression1 i.e., cout << "eligible to vote" will get evaluated, otherwise, expression2 i.e., cout << "not eligible to vote" will get evaluated. Since the value of age that we entered (10) is less than 18, therefore expression2 got evaluated and "not eligible to vote" got printed.

Let's see another example in which we want to find the greater among two numbers.

#include <iostream>
int main(){
	using namespace std;
	int num1 = 4, num2 = 5, num;
	num = (num2 > num1) ? num2 : num1;
	cout << "The greater number is " << num << endl;
	return 0;
}
Output
The greater number is 5.

In this example, if the condition (num2 > num1) is true, then num2 i.e., 5 will get assigned to num, otherwise, num1 i.e., 4 will get assigned to num. In our case, the values of num1 and num2 are 4 and 5 respectively. Thus, the condition 'num2 > num1' is true and the value of num2 i.e., 5 got assigned to num and so 5 got printed.

Knowledge is of no value unless you put it into practice.
-Anton Chekhov

Share what you know
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.