Thread: Can a "switch" be inside a loop?

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    4

    Can a "switch" be inside a loop?

    I am trying to write a simple program for calculating sines and cosines, which should continue until “q” is entered to quit. I assume that using a “switch” statement would be the easiest method, so that each “case” can test the input to decide whether to calculate sine or cosine, with the “default” being used to print “Illegal Character” if “c” or “s” is not entered. The switch works fine while it is by itself, but when I put it into a loop (so that I can repeat the calculations) the loop (I used a “while” loop in this example, but I’ve had the same results with other types of loop also) seems to run through twice after each input. On the second pass through, it also seems to execute the “default” case within the switch and prints “Illegal Character”. I can’t seem to follow along with the program’s flow to see why it is going through the loop twice with only one input. Am I doing something wrong (most likely)? Is it unacceptable to put a “switch” within a loop? Is there a better way to perform this simple operation (I also tried it with a “goto”, but got the same results)? I am ok until I have to get the program to repeat, that’s when the trouble starts.

    I have simplified the program below (so that I could easily test other options) so that it just prints “sine”, “cosine”, or “Illegal Character” when you input “s”, “c”, or any other (except “q”), and it will exit with “q”.

    Any help would be greatly appreciated. I am using DEV-C++ v4.9.9.2 (but I get the same results with MS Visual Studio), with XP pro. I am programming in C, not C++, if that makes a difference. Please be gentle, the last language I learned was fortran.....

    Code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <ctype.h>
    
    int main(void)
    {
    	
    int num1=1, choice;
    
    while (num1=1)
    {
    
    printf ("enter 's' for sine, 'c' for cosine, or 'q' to quit:\n");
    
    choice=getchar();
    
    if (choice=='q')
    {
    return 0;
    }
    
    switch (choice)
    {
    	case ('s'):
    	printf ("sine\n");
    	break;
    
    	case ('c'):
    	printf ("cosine\n");
    	break;
    
    	default:
    	printf ("Illegal Character\n");
    	break;
    
    }
    
    }
    system("PAUSE");
    return 0;
    }
    COMPILE LOG:
    Compiler: Default compiler
    Building Makefile: "C:\Dev-Cpp\Makefile.win"
    Executing make...
    make.exe -f "C:\Dev-Cpp\Makefile.win" all
    gcc.exe -c looptest.c -o looptest.o -I"C:/Dev-Cpp/include"
    gcc.exe looptest.o -o "Project10.exe" -L"C:/Dev-Cpp/lib"
    Execution terminated
    Compilation successful


    This is the output I get (with input of “s” then “c” then “q”):

    enter 's' for sine, 'c' for cosine, or 'q' to quit:
    s
    sine
    enter 's' for sine, 'c' for cosine, or 'q' to quit:
    Illegal Character
    enter 's' for sine, 'c' for cosine, or 'q' to quit:
    c
    cosine
    enter 's' for sine, 'c' for cosine, or 'q' to quit:
    Illegal Character
    enter 's' for sine, 'c' for cosine, or 'q' to quit:
    q
    Press any key to continue . . .

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Speaks for itself: http://faq.cprogramming.com/cgi-bin/...&id=1043284392

    Also, try to indent your code

    Code:
    while (num1=1)
    You mean, while(num1 == 1) ?

    Why don't you just run the loop while choice != 'q'? ie,
    Code:
    while((choice = getchar()) != 'q')
    {
    Last edited by zacs7; 03-28-2008 at 04:46 PM.

  3. #3
    Registered User
    Join Date
    Mar 2008
    Posts
    4
    Sorry for the poor formatting, I have been cutting/pasting all kinds of things just trying to get it to stop going through the loop twice (if that is what it is actually doing.

    I think you are right, it should actually be "while (num1 == 1), but it seems to run with only one "=". I will definitely correct that, thanks for catching it.

    As for the "while" loop, how would I get the program to ask (request it on screen) each time for an input for the variable "choice" if the loop starts after the initial choice? Or do you mean to replace the "if (choice=='q')" with the new "while" statement?

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Replacing the if with the "new" while statement, as in "put the new condition inside the while where it is right now", yes.

    A single equal is "acceptable" as far as the compiler is concerned. It just doesn't do the same thing as you want - it assigns "num" to 1, then checks if it's zero, if not, the loop continues. Since 1 is never 0, it will continue forever.

    Also bear in mind when you type "q" followed by enter as a response to some input, the enter also goes into the "input buffer", so next time round, getchar() is called, it gets a newline ('\n'), so every "input" is actually two characters, one letter, and one enter.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    Mar 2008
    Posts
    4
    If I replace the old "if" with the new "while", would it exit the program? Or would it continue to loop within the outer "while"?

    The only reason I have the outer "while" loop (or any other loop) is because it is the only way I could figure out to get the program to keep repeating itself (until "q" is entered.

    I didn't know that "q" followed by "enter" would count as two inputs, but that would definitely explain why it is going through the loop twice-correctly the first time, and printing "Illegal Character" the second (from the second input of "enter"). Thanks for explaining that, it was driving me crazy! Now if only I can fix it...

    Is there any way to stop the program from seeing the "enter" as a second input? Or, is there another way to get an input other than the "getchar()"?

  6. #6
    Registered User
    Join Date
    Mar 2008
    Posts
    4
    Thanks very much Mats! After you explained what was happening with the getchar(), I was able to find another thread with a similar problem. They simply advised inserting another getchar(); after the first (choice=getchar() in my case) which would "absorb" the carriage return. I tried it, and it works fine now!

    Thanks very much for everyone's help!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 12-01-2008, 10:09 AM
  2. For Loop inside While Loop
    By mesmer in forum C Programming
    Replies: 1
    Last Post: 11-29-2008, 12:29 PM
  3. syntax question
    By cyph1e in forum C Programming
    Replies: 19
    Last Post: 03-31-2006, 12:59 AM
  4. loop and compiling inside a code
    By MtJ in forum C Programming
    Replies: 3
    Last Post: 03-05-2006, 12:50 PM
  5. when a while loop will stop ?
    By blue_gene in forum C Programming
    Replies: 13
    Last Post: 04-20-2004, 03:45 PM