C Programming Tutorial - Chapter 4
Results 1 to 6 of 6

Thread: C Programming Tutorial - Chapter 4

  1. #1
    Antionline Herpetologist
    Join Date
    Aug 2001
    Posts
    1,165

    C Programming Tutorial - 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://www.antionline.com/showthread...hreadid=137499
    http://www.antionline.com/showthread...hreadid=140166
    http://antionline.com/showthread.php?s=&threadid=221501
    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:

    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:

    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:

    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 your 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, it is considered
    poor programming style to do this. Always use braces. It leaves less room for
    mistakes.

    The switch statement
    Using switch-case to make decisions 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:

    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. 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 more easy 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 practise.
    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.
    Buy the Snakes of India book, support research and education (sorry the website has been discontinued)
    My blog: http://biology000.blogspot.com

  2. #2
    Nice Job

  3. #3
    Member
    Join Date
    Mar 2002
    Posts
    88
    Thanks So Much For ALL of Your Tutorials i Hope That By The Time C++ Is Second
    Nature To Me It Doesnt Become Obsolete Like Python And Pascal Then Again Im
    Wonderin Why Its On(Python)My XP Machine

  4. #4
    Member
    Join Date
    Feb 2003
    Posts
    49
    This is a very good tutorial!!! I am a new member here, and I have never done ANY programming in my life. This tutorial is GREAT!!

  5. #5
    Member
    Join Date
    Oct 2002
    Posts
    37
    Well put together man, just wish I could give you some greenies. Oh well, how about a chapter 5 :P (appologize if there is one, its not on the index)

    *side note* i am starting to love vi
    The only limit a person has, is the limit they give themselves.
    Cogito ergo sum. - Descartes

  6. #6
    Junior Member
    Join Date
    Nov 2003
    Posts
    4
    You could just have them type the whole word like hamburger with &lt;string.h&gt; and if(strcmp(choice,"Hamburger")==0) , but maybe this is a little to recondite for this specific tutorial...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •