computer tutorial 


C PROGRAMMING CHAPTER 4

C Programming Tutorial - Chapter 4

Decision making

========================
Things covered in Chapter 4
The if statement
The else statement
The else if statement
The switch statement
========================

Chapters 1, 2 and 3 can be found at:
http://tazforum.thetazzone.com/viewtopic.php?t=6453
http://tazforum.thetazzone.com/viewtopic.php?t=6454
http://tazforum.thetazzone.com/viewtopic.php?t=6455
respectively.

Decision Making
By now, you know what variables are, how to get input from the user and how to
use that input in order to generate output. So, today we'll be discussing
decision making. Decision making is one of the most important parts of
programming. You've seen programs that take input from the user, and depending
on what that input is, vary the output. The simplest example of this is a
program that asks the user a yes/no question and does something accordingly.
Here's a program that does just that:

Code:


/*if1.c A program that uses an if...else construct to make a decision. */ #include <stdio.h>
void main()
{
    char prompt;
    printf("Do you want to continue? (y/n):");
    prompt = getchar(); //note that the single quotes around 'y' and the == sign
    if(prompt == 'y')
    {
          printf("\nYou picked yes. : ) \n");
    }
    else
    {
          printf("You picked no. : ( \n");
    }
}


Save it as if1.c . Compile. Fix errors. Run.

The if statement
All that's new in this program is the if{...} else {.....} thing. The both if
and else are C language keywords which means that they don't require any
external files for the compiler to understand them (As opposed to printf(),
scanf() and getchar() all of which require that you include stdio.h into your
program). The if keyword has a very simple format. All you have to do is:

Code:

if(somevariable == somedata)
{
do something
}



The else statement
The else keyword works in a similar way except that it has no condition to
evaluate. All that you have to do is:

Code:

else
{
do something
}




The else keyword must have an if statement immediately before it i.e. the else
statement must be the next statement after the ending brace ( } ) of the if
statement. Otherwise you get an "else without if" or "mismatched else" error.
Note: For an else statement an if is compulsory, but an else isn't compulsory
for an if statement. So you can have an if without an else but not an else
without an if.
The else if statement
Now, take a look at the next program:

Code:

/*if2a.c A program that uses an if...else if...else construct to make a decision. */
#include <stdio.h>
void main()
{
    char prompt;
    printf("Do you want to continue? (y/n): ");
    prompt = getchar();
    if(prompt == 'y')
    {
        printf("\nYou picked yes. : ) \n");
    }
    else if(prompt == 'n')
    {
        printf("You picked no. : ( \n");
    }
    else
    {
         printf("Invalid Decision.\n");
         printf("Run program again.\n");
    }
}



Save this as if2a.c . Compile. Fix errors. Run.
This program is pretty much the same as the first example except for the else if thing. else if is what you use when you need to make more than two decisions. It goes like this:

Code:

if(somevariable == somedata)
{
//do task 1
}

else if(somevariable == somedata)
{
//do take 2
}

else if(somevariable == somedata)
{
//do task 3
}

else
{
//do task 4
}



Take a look at the following example.

Helps illustrate the point better.

Code:


/*if2b.c A program that uses an if...else if...else construct to make a decision. */
#include <stdio.h>
void main()
{
    char prompt;
    printf("Do you want to continue? (y/n): ");
    prompt = getchar();
    if(prompt == 'y')
        printf("\nYou picked yes. : ) \n");
    else if(prompt == 'n')
         printf("You picked no. : ( \n");
    else
    {
         printf("Invalid Decision.\n");
         printf("Run program again.\n");
    }
}



This program is similar to if2a.c except that we have left out the braces on the if and else if statements. This is perfectly legal in C as long as the code to be exectuted if the condition is met resides on only one line. The else statement had more than one line after it so we had to use braces.

Note that, while code will compile fine without the braces, be careful when doing this. If in doubt, use braces. It leaves less room for mistakes and doesn't take too much additional time.

The switch statement

When you have to make multiple decisions,using else if repeatedly becomes a pain. Besides it leads to very messy code.
That's why we have the switch-case construct which is shown in the following program.
Code:


/*switch1.c A program that uses the switch case construct to make multiple decisions*/
#include <stdio.h>
void main()
{
    char choice;
    printf("Welcome to the cgkanchi eatery.\n What would you like to eat?\n");
    printf("Item\t\t\tWhat to type"\n);
    printf("Hamburger\t\th\n");
    printf("Hot Dog\t\t\td\n");
    printf("Sandwich\t\ts\n");
    choice = getchar();
    switch(choice)
    {
        case 'h': printf("One hamburger coming up!\n");
        printf("That'll be $0.5 please\n");
        break;
        case 'd':
        printf("One hot dog coming up!\n");
        printf("That'll be $0.75 please\n");
        break;
        case 's':
        printf("One sandwich coming up!\n");
        printf("That'll be $1.00 please\n");
        break;
        default: printf("I'm sorry sir, but we don't have that item on our menu\n");
        printf("Try the place down the road.\n");
        break;
     }
}


The format of the switch-case construct is:

Code:

switch(variable)
{
case 1:
//do task one
break;

case 2:
//do task 2
break;

case 3:
//do task 2
break;

default:
//do the default task
break;
}



Note that after case something you have a colon and not a semicolon.
The program encounters the switch statement and checks the variable specified inside the parantheses. Then it goes on to the first case. It checks the value of the expression after the case to see if it's equal to the variable. If so, it executes the statements within the case. If not, it continues to the next case and so on until it finds a match. If nothing matches, it looks for a default statement. If it finds it, it proceeds to execute whatever statements are contained within it.
If it doesn't find a default, it just exits the structure without any action.

The break statement stops any code below it in the switch statement from being exectuted. So if case 1 is true then the program will execute the code for case 1 and then jump to the next statement after the switch statement. The other cases will be ignored. If you leave out the break statements you can have multiple cases for a single selection which can be useful but it is easier to make errors.

Also note that there is a break statement after the last (default) case.
Although this is not necessary for your program to compile it is considered good programming practice.
That's all for this chapter.

Exercises to keep you from getting too bored waiting for chapter 5:

Write a program that takes in a character and tells you the number that the alphabet corresponds to. (eg A is 1, B is 2 and so on)
Hint: Use switch-case.
Modify the program to say something like "invalid input" when you type in something other than an alphabet.
Hint: Use default.

Cheers,
cgkanchi

Note:Special thanks to smirc for helping with the editing of this chapter.



 

Original Tutorial by cgkanchi for TheTAZZone-TAZForum

Originally posted on April 19th, 2007 here

Do not use, republish, in whole or in part, without the consent of the Author. TheTAZZone policy is that Authors retain the rights to the work they submit and/or post...we do not sell, publish, transmit, or have the right to give permission for such...TheTAZZone merely retains the right to use, retain, and publish submitted work within it's Network.