C Tutorial – The if and switch statement

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

Boolean Operators

Before we can take a look at test conditions we have to know what Boolean operators are. They are called Boolean operators because they give you either true or false when you use them to test a condition. The greater than sign “>”
for instance is a Boolean operator. In the table below you see all the Boolean operators:

== Equal
! Not
!= Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
&& And
|| Or

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 this instruction. If not true, execute this instruction. So lets take a look at an example:


	#include<stdio.h>

	int main()
	{

		int mynumber;

		scanf("%d",&mynumber);
		if ( mynumber == 10 )
			printf("Is equal\n");
		return 0;
	}

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

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 ( mynumber == 10)
	{
		printf("is equal\n");
		printf("closing program\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<stdio.h>

	int main()
	{
		int mynumber;
		scanf("%d",&mynumber);

		if ( mynumber == 10 )
		{
			printf("Is equal\n");
			printf("Closing program\n");
		}
		else
		{
			printf("Not equal\n");
			printf("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<stdio.h>

	int main()
	{
		int grade;

		scanf("%d",&grade);
		if ( grade <= 10 )
		{
			printf("YOU DID NOT STUDY.\n");
			printf("YOU FAILED ! \n");
		}
		else
		{
			if ( grade < 60 ) 			{ 				printf("You failed \n"); 				printf("Study harder\n"); 			} 			else 			{ 				if ( grade >= 60 )
					printf("YOU PASSED ! \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 grade is equal or below ten, you did not study. If the grade 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 grade again. If the grade is below sixty, you must study harder. In the “else statement” from this “if statement” there is another “if statement”. It checks whether the grade is above or equal to sixty. If it is, you passed the test.

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 variable equals the condition, the instructions are executed. It is also possible to add a default. If none of the variable equals the condition the default will be executed. See the
example below:


      #include<stdio.h>

	int main()

	{
		char myinput;

		printf("Which option will you choose:\n");
		printf("a) Program 1 \n");
		printf("b) Program 2 \n");
		scanf("%c", &myinput);

		switch (myinput)
		{
			case 'a':
			 		printf("Run program 1\n");
			 		break;
			case 'b':
				{
			 		printf("Run program 2\n");
					printf("Please Wait\n");
					break;
				}
			default:
					printf("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 25 responses to “C Tutorial – The if and switch statement”

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

  1. Vipandeep on December 8th, 2010:

    Can we have If statement in Switch case?

  2. admin on December 9th, 2010:

    Sure you can, for example:

    #include<stdio.h>

    int main()
    {
    char myinput;
    int i=5;
    printf("Which option will you choose:\n");
    printf("a) Program 1 \n");
    printf("b) Program 2 \n");
    scanf("%c", &myinput);

    switch (myinput)
    {
    case 'a':
    printf("Run program 1\n");
    if( i == 5) {
    printf("OK\n");
    }
    break;
    case 'b':
    {
    printf("Run program 2\n");
    printf("Please Wait\n");
    break;
    }
    default:
    printf("Invalid choice\n");
    break;
    }
    return 0;
    }

  3. yankpascal on July 5th, 2011:

    i like it

  4. venkatrao on July 21st, 2011:

    excellent

  5. reshma on August 14th, 2011:

    y didnt you use curly braces in case a…you have just opened only for b?

  6. admin on August 14th, 2011:

    @reshma: you are right. Using curly braces in a case statement is a matter of coding style, because most compilers allow different variations. In this case the b statement has multiple printf statements and a has not. Therefore b has curly braces and a has not. Just as you can do with the if statement, where you use curly braces if there is more than one statement that needs to be run if the if statement is valid.

    You can try it yourself, make little programs and see what is allowed by the compiler. But whatever style you choose (no curly braces, only with multiple statements you use curly braces or always curly braces) try to be consistent, especially if you work with different people on the same code!

  7. Omar on September 30th, 2011:

    is it possivle to use multiple conditions in switch ..cases! ??
    eg if (i7)
    how we do this in switch ??

  8. Sean on December 30th, 2011:

    when using if or else if, can i initialize something instead of printing? (probably a dumb question, but meh)

    e.g.
    if (number == 1)
    int identifier = “value1”;
    else if (number == 2)
    int identifier = “value2”;

  9. Emma Cummin on February 16th, 2012:

    Hi there,

    I have tried to write a similar program, but for some reason whatever number I enter results in the default “Invalid choice” being displayed. Can anyone please shed any light on why this may be?

    Thanks,
    Emma

    CODE:

    #include

    int main()

    {
    int mynumber;

    printf (“Please choose a digit between 0 and 9 …\n”);
    scanf (“%d”, &mynumber);

    switch (mynumber)
    {
    case ‘0’:
    printf (“That’s extremely boring.\n”);
    break;
    case ‘1’:
    case ‘9’:
    printf (“You chose a perfect square.\n”);
    break;
    case ‘2’:
    printf (“You chose the smallest prime number.\n”);
    break;
    case ‘3’:
    case ‘5’:
    case ‘7’:
    printf (“You chose a prime number.\n”);
    break;
    case ‘4’:
    case ‘6’:
    case ‘8’:
    printf (“You chose an even number.\n”);
    break;
    default:
    printf (“Invalid choice.\n”);
    }

    return 0;

    }

  10. Emma Cummin on February 16th, 2012:

    PS. The start actually reads #include<stdio.h>. Apologies.

  11. admin on February 16th, 2012:

    @Emma: you should remove the ‘ ‘ characters in your example (for instance ‘0’ should become 0). Below you’ll find a source example that should work. Also you better use scanf_s, if have put it in the example. Good luck!

    #include<stdio.h>

    int main() {

    int mynumber;

    printf(“Please choose a digit between 0 and 9 …\n”);
    //
    //scanf (“%d”, &mynumber);
    //Better use scanf_s, prevents buffer overloading
    scanf_s(“%d”, &mynumber, 1);

    switch (mynumber) {
    case 0:
    printf (“That’s extremely boring.\n”);
    break;
    case 1:
    case 9:
    printf (“You chose a perfect square.\n”);
    break;
    case 2:
    printf (“You chose the smallest prime number.\n”);
    break;
    case 3:
    case 5:
    case 7:
    printf (“You chose a prime number.\n”);
    break;
    case 4:
    case 6:
    case 8:
    printf (“You chose an even number.\n”);
    break;
    default:
    printf (“Invalid choice.\n”);
    }
    return 0;
    }

  12. Eug on March 7th, 2012:

    i got a part of programming of a c language for my microcontroller. i know it’s a bit different. ignore some part of my programming. i wanna ask if i can use switch statement for the if/else statement part? and also is it faster and use less space (space is crucial for my application)?
    //========== ==========include========== ==========//
    #include ;
    __CONFIG ( 0x3F32 );

    //========== ==========define========== ==========//

    #define servo4 RB4 // define servo motors
    #define servo3 RB5
    #define servo2 RB6
    #define servo1 RB7

    #define vdown RD2 // define buttons
    #define vup RD3
    #define right RD4
    #define left RD5
    #define down RD6
    #define up RD7

    //========== ==========global variable========== ==========//

    unsigned int m1;
    unsigned int m2;
    unsigned int m3;
    unsigned int m4;
    unsigned int counter;
    unsigned int p=12; // pull
    unsigned int r=17; // release
    unsigned int c=0; // center (no pulse to servo motor)

    //========== ==========main function========== ==========//

    void main(void)
    {
    while (1)
    {
    if(up==0 && down==1 && left==1 && right==1 && vup==1 && vdown==1) //up
    {
    GIE=1;
    m1=p;
    m2=p;
    m3=r;
    m4=r;
    continue;
    }
    else if(up==1 && down==0 && left==1 && right==1 && vup==1 && vdown==1) //down
    {
    GIE=1;
    m1=r;
    m2=r;
    m3=p;
    m4=p;
    continue;
    }
    else if(up==1 && down==1 && left==0 && right==1 && vup==1 && vdown==1) //left
    {
    GIE=1;
    m1=r;
    m2=p;
    m3=p;
    m4=r;
    continue;
    }
    else if(up==1 && down==1 && left==1 && right==0 && vup==1 && vdown==1) //right
    {
    GIE=1;
    m1=p;
    m2=r;
    m3=r;
    m4=p;
    continue;
    }
    else if(up==1 && down==1 && left==1 && right==1 && vup==0 && vdown==1) //vertical up
    {
    GIE=1;
    m1=p;
    m2=p;
    m3=p;
    m4=p;
    continue;
    }
    else if(up==1 && down==1 && left==1 && right==1 && vup==1 && vdown==0) //vertical down
    {
    GIE=1;
    m1=r;
    m2=r;
    m3=r;
    m4=r;
    continue;
    }
    GIE=0;
    }

    }

  13. FMMK on November 14th, 2012:

    Here is an example of a simple “multiple choice” program I made for those who are interested. It might clarify some of your questions:

    CODE:

    #include

    int main ()
    {

    char userInput;

    printf(“Which is the largest object?\n”);

    scanf(“%c”, &userInput);
    //Switch is kind of like the if statement:
    switch (userInput)
    {

    case ‘a’:
    {
    printf(“Incorrect!\n”);
    break;
    }
    case ‘b’:
    {
    printf(“Incorrect!\n”);
    break;
    }
    case ‘c’:
    {
    printf(“Incorrect!\n”);
    break;
    }
    case ‘d’:
    {
    printf(“Correct\n”);
    break;
    }
    default:
    printf(“a)A Truck\n”);
    printf(“b)A Peanut\n”);
    printf(“c)An Elephant\n”);
    printf(“d)The moon\n”);
    break;
    }

    return 0;
    }

  14. FMMK on November 16th, 2012:

    IGNORE THE CODE ABOVE ^ (It has errors)

    Here is another “Multiple Choice” example that should work:

    CODE:

    #include

    int main ()
    {

    char MyInput;

    printf(“What is 2 + 2?\n a)1\n b)2\n c)3\n d)4\n Answer:”);

    scanf(“%c”, &MyInput);

    stdin;

    switch (MyInput)

    {
    {
    case ‘a’:
    printf(“Incorrect\n”);

    }

    break;
    {
    case ‘b’:
    printf(“Incorrect\n”);

    }
    break;

    case ‘c’:
    { printf(“Incorrect”);

    }
    break;

    case ‘d’:
    { printf(“Correct!\n”);
    if (MyInput == ‘d’)
    {
    printf(“You are AWSOME!!!\n”);
    }

    }
    break;
    default:
    printf(“Not a valid choice”);

    }

    return 0;

    }

  15. FMMK on November 16th, 2012:

    Make sure this is there: ( #include) — I don’t know why it doesn’t get printed out on this site. Strange.

  16. Mohamed F. on February 23rd, 2013:

    Hi, Nice Tutorial, one of the best i have seen till now 🙂

    PS : The Nested If Example, there is a hidden part of the code that wasn’t displayed correctly in the page “far on the right side” ,you should check it.

    Regards,

  17. Adam on April 10th, 2013:

    How does the program know which case it is using?

  18. Zeefan on May 27th, 2013:

    @Adam
    The ‘a’ after the word case, the one which is in single quotes is the keyword the computer will look for. If you type in a and enter, it will execute case a.
    What I would like to know is if I can make it so, that different words can execute the same case, for example if I want the word “pie” to execute one of the cases, and I also want it so, if I typed in “Pie” instead (upper case P) it still executes the case. I thought it would be something like:
    case (‘pie’ || ‘Pie’):
    But it seems I was wrong…

  19. ProfRubik on July 26th, 2013:

    hey guys im having a problem…..

    what am i going to input if i want my program to Continue if the first statement is true then close if the second statement is true????

  20. Matt F on August 12th, 2013:

    Basically ive been working on a switch case within a switch case.
    List of stuff
    1,2,3 are the options
    IF/when you select 1/2/3 it adds a correct variable to character data and does a print.
    Do you want to keep this selection?
    y/n
    if no, starts over and lets you pick again. If you pick y, it breaks and starts the next piece of code. How would I go about that?

  21. Pamela on August 31st, 2013:

    Mode of Payment:

    A/a – Cash no additional
    B/b – installment plus 5%
    C/c – Credit card plus 2%

    how can i program this using switch statement please help me? Thank.

  22. K.Revathy on October 11th, 2013:

    now i completely understand about the switch stmt and if stmt .such a easier explanation to understand.Thanksss alottt……….!!!!!

  23. lwanga joseph on October 17th, 2013:

    can i use operators in c switch statements?

  24. JOSEPH on October 24th, 2013:

    Keep up the spirit of educating the world.
    U make the future of future programmers.

  25. john paul on April 11th, 2014:

    Please help me at line 25 printf wont show

    #include
    #include

    int main()

    {
    char choice;
    int num=10;
    printf(“Welcome to My Video Rental”);
    printf(“What do you want to do? \n\n”);
    printf(“a. Rent a Movie\n”);
    printf(“b. Return a Movie\n\n”);
    printf(“Enter choice: \n\n”);

    choice = getch();

    switch(choice)
    {
    case ‘a’:

    printf(“want movie do you like to rent?\n” );
    printf(“1.don jon\n”);
    printf(“2.battleship\n”);
    printf(“3.wolf of wall street\n”);
    printf(“4.insidious\n”);
    printf(“5.perks of being a wall flower\n”);
    if( num < 5 ){
    printf("thank you for renting our movies!"); <——(line 25)
    }
    break;

    case 'b' :
    printf("thank you for returning our movie videos\n" );
    break;

    default:
    {
    printf("Error! Choice not found.");
    }

    getch();

    }
    }