C++ The if statement and switch statement

In this C++ programming tutorial we take a look at the “if statement” and “switch statement”. Both are used to alter the flow of a program (if the specified test condition is true).

The if statement

The if statement can be used to test conditions so that we can alter the flow of a program. In other words: if a specific statement is true, execute some instructions. If not true, execute these instructions.

In the following example the user can input a number. The number is stored in the variable A. Now take a look at the “if statement”: if the number stored in the variable A is equal to ten, then “is equal” is printed on the screen. Simple, isn’t it. If the number is not equal to ten, then nothing is printed.

Take a look at the example:


	#include<iostream>
	using namespace std;

	int main()
	{
		int A;
		cin >> A;
		if ( A == 10 )
			cout << "is equal" << '\n';
		return 0;
	}

Now take another look at the “if statement”: look at the placement of the semi-colon. As you can see there is no semi-colon behind the “if statement”. If there is just one instruction (if the statement is true), you can place it after the “if statement” (with an indentation). Are multiple instructions necessary then you will have to use curly brackets, like so:


	if ( A == 10 )
	{
		cout << "Hello" << '\n';
		cout << "Hello" << '\n';
	}

Now we like to also print something if the “if statement” is not equal. We could do this by adding another “if statement” but there is an easier / better way. Which is using the so called “else statement” with the “if statement”.


	#include<iostream>
	using namespace std;

	int main()
	{
		int A;
		cin >> A;
		if ( A == 10 )
		{
			cout << "is equal" << '\n';
			cout << "closing program" << '\n';
		}
		else
		{
			cout << "not equal" << '\n';
			cout << "closing program" << '\n';
		}
		return 0;
	}

Note: Take a look at the placement of the curly brackets and how the indentations are placed. This is all done to make reading easier and to make less mistakes in large programs.

Nested if statements

If you use an “if statement” in an “if statement” it is called nesting. Nesting “if statements” can make a program very complex, but sometimes there is no other way. So use it wisely. Take a look at a nested “if statement” example below:


	#include<iostream>
	using namespace std;

	int main()
	{
		int a;
		cin >> a;
		if ( a <= 10 )
		{
			cout << "Below 10" << '\n';
		}
		else
		{
			if ( a < 60 )
			{
				cout << "Below 60" << '\n';
			}
		}
		return 0;
	}

Note: Again take a look at the placing of the curly brackets and the placing of the indentations.

So let’s walk through the example above: If the input is ten or below ten, “below 10” will be printed. If the input is above ten, the program will go into the “else statement”. In the “else statement” there is another “if statement” (this is nesting). This “if statement” checks the input again. If the input is below sixty, “below 60” will be printed.

Multiple condition testing

It is possible to test two or more conditions at once in an “if statement” with the use of the AND (&&) operator. Example:


if ( a > 10 && b > 20 &&  c < 10 )

If a is greater then ten and b is greater then twenty and c is smaller then ten, do something. So all three conditions must be true, before something happens. With the OR ( || ) operator you can test if one of two conditions are true.
Example:

	
      if ( a == 10 || b < 20 )

If a equals ten or b is smaller then twenty then do something. So if a or b is true, something happens.

The switch statement

The switch statement is almost the same as an “if statement”. The switch statement can have many conditions. You start the switch statement with a condition. If one of the variables equals the condition, the instructions are executed. It is also possible to add a default. If none of the variables equals the condition the default will be executed. See the example below:


	#include<iostream>
	using namespace std;

	int main()
	{
		char myinput;
		cin >> myinput;

		switch (myinput)
		{
			case 'a':
					cout << "Run program 1\n";
					break;
			case 'b':
				{
					cout << "Run program 2\n";
					cout << "Please Wait\n";
					break;
				}
			default:
					cout << "Invalid choice\n";
					break;
		}
		return 0;
	}

Note: break is used to exit the switch. See the next tutorial for more details.

That’s all for this tutorial.

We encourage you to make your own programs or to make changes in the example programs.
This is the only way you can learn programming C++. Make little programs, the more the better. Have fun!

This entry was posted in C++ Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 8 responses to “C++ The if statement and switch statement”

Why not let us know what you think by adding your own comment!

  1. rajaduraijaishva on July 31st, 2011:

    really superb.thanks foqt ur teaching

  2. anneka on December 8th, 2011:

    wow!!!!! very very very good

  3. King Nheilo on January 31st, 2012:

    Dont have any Combination of if and switch statement? i need it for my midterm examination. 🙂

  4. Chrys on February 20th, 2012:

    if ( a = 10 || b < 20 )

    I think this should be if ( a == 10 || b < 20 )

  5. admin on February 20th, 2012:

    @Chrys: Thanks, nice catch. Changed it!

  6. Ameer on April 16th, 2012:

    thanks a million, i’ve been sitting with my program for 3 hours and all i needed was

    if (num1 > num2 && num1 > num3)

  7. cwalls1014 on July 22nd, 2013:

    I’m trying to write an if statement that does something based on the inequality of two possible scenarios.

    if ( this stuff != this stuff )
    {
    do this stuff;
    }

    else if ( this stuff != this stuff )
    {
    do this stuff;
    }

    Any ideas on how to get his to work?

  8. Sanjay Shinde on October 5th, 2013:

    /*Create a simple ATM transaction using if_else, the main account balance is 5000.
    also test all condition on this program, like u cant withdraw less than 100 rs,
    u cant withdraw 110rs, and when one valid transaction complete it shows ur remaining balance */
    #include

    using namespace std;
    int main()
    {

    int a, b=5000,r; // here a= amount, b= main Balance, r= reminder condition
    cout<<"Enter the amount "<>a;
    r=a%100;

    if(a>=100 && r==0 && a<=b){
    cout<<"Please Collect the cash: "<<endl<<a<<endl<<endl;
    int rb = b – a;
    cout<<"Your Remaining account balance is :"<<endl<<rb<<endl;

    }//if block close
    else{
    cout<<"Incorrect or insufficient Amount entered "<<"\n\n";
    }//else block close
    cout<< "Thanx For Visiting "<<"\n\n\n\n\n";

    system("PAUSE");
    return 0;

    }// main close