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:
COMPILE LOG: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; }
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 . . .