Menu

Can a "switch" be in a loop?

2008-03-28
2012-09-26
  • George Kronz

    George Kronz - 2008-03-28

    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, 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:

    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 (&quot;cosine\n&quot;);
    break;
    
    default:
    printf (&quot;Illegal Character\n&quot;);
    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 . . .

     
    • Somelauw

      Somelauw - 2008-04-06

      Hasn't this forum something called indention? Is indention ignored or did you forget it? I'm new, so I don't know if this forum supports indention.

                  Test (some spaces before).
      

      For your problem:
      choice should be declared of type char or *char.

      For your while loop, you probably want to compare num1 to 1 which is done by num1 == 1.
      Easier ways to make looping infinite are:
      - while True
      - for(;;)

      Also, num1 isn't really a very descriptive name for a variable.
      And you can safely put switch or other control structures inside of other ones.

       
      • cpns

        cpns - 2008-04-06

        You mean "indentation".

        The text is rendered in plain HTML and HTML ignores leading and multiple whitespace.

        Considering the whole of Sourceforge is intended for collaborative code development, it is astonishing that its forums do not provide a means of posting formatted code, but that is the way it is. What Sourceforge does is not within the control of the Dev-C++ project (such as it is at present), nor the users of moderators.

        Generally if necessary I post code bodies into MSVC++ and do CTRL+K CTRL+F.

        >> choice should be declared of type char or *char.

        No. Check the documentation. http://www.cplusplus.com/reference/clibrary/cstdio/getchar.html . getchar() returns an int. It certainly should not be "char" because there is no such thing. If you meant "char", that would certainly be an error!

        >> For your while loop, you probably want to
        >> compare num1 to 1 which is done by num1 == 1.

        Yes, that was already explained. What are you adding to this discussion?

        >> Also, num1 isn't really a very
        >> descriptive name for a variable.

        Agreed, it is a really dumb name.

        Clifford

         
    • cpns

      cpns - 2008-03-29

      Replace

      while (num1=1)

      with

      while( num1 == 1 )

      For the question "Can a "switch" be in a loop?" the answer is yes, or course. But if you really want to see funky code involving a switch and a loop, where the switch is neither wholly in nor out of the loop, Google or Wikipedia "Duff's Device" ;-)

      Clifford

       
    • George Menoutis

      George Menoutis - 2008-04-04

      I don't understand. This while() is just supposed to be a never-ending one, right? Like while(1)? What is the difference of == or =?
      a)num1=1 : num1<-1 1 is true
      b)num1==1: int num1=1; num1==1 is true
      Since he has not replied, though, i suppose it worked...
      Couldn't find any other mistakes anyway

       
      • cpns

        cpns - 2008-04-06

        Weird. I could have swarn I'd replied to this earlier. Must have omitted to post. Doh!

        You make a good point. He said he "simplified the code", this often translates to "I changed the code, removing the actual problem while adding some new unrelated bugs". My bet is that the original code performed some modification to num1 within the loop. With = it would only terminate when num1 was zero, where he no doubt intended it to terminate when num1 was not 1.

        Clifford

         
        • cpns

          cpns - 2008-04-06

          ... "sworn" even.

           

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.