Making a menu driven program, errors - c

Beginner to C and doing an assignment for a course. Fixed what I think needed to be fixed, but my menu will only go to part A, but not B, C, or D. It quits fine as well. No errors, wondering what is wrong with my code.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define PAUSE system("pause")
#define CLS system("cls")
#define FLUSH flush()
// Prototype Functions Here
void highestNumber(int, int, int);
void lowestNumber(int, int, int);
void displayAverage(int, int, int);
void displayMenu();
void flush();
char getUserChoice();
main() {
char userSelection;
int number1 = 0, number2 = 0, number3 = 0;
do {
userSelection = getUserChoice(); // Gets/DisplaysMenu
switch (userSelection) {
case 'A': // Enter a number
printf("Enter a number 1: ");
scanf("%i", &number1);
printf("Enter a number 2: ");
scanf("%i", &number2);
printf("Enter a number 3: ");
scanf("%i", &number3);
break;
case 'B': // Display Highest Number Entered
printf("In Case B");
highestNumber;
break;
case 'C': // Display Lowest Number entered
printf("In Case C");
lowestNumber;
break;
case 'D': // Display Average of Numbers entered
printf("In Case D");
displayAverage;
break;
case 'Q': // Quit the program
printf("You have quit the program\n");
PAUSE;
break;
default: // Invalid Selection
printf("Invalid selection...try again!\n");
PAUSE;
break;
} // end switch
} while (userSelection != 'Q');
PAUSE;
} // end of main
//==============
void highestNumber(int number1, int number2, int number3) {
if (number1 > number2 && number1 > number3) {
printf("The highest number is: %i", number1);
}
else if (number2 > number1 && number2 > number3) {
printf("The highest number is: %i", number2);
}
else if (number3 > number2 && number3 > number1) {
printf("The highest number is: %i", number3);
}
} //end highest number
void lowestNumber(int number1, int number2, int number3) {
if (number1 < number2 && number1 < number3) {
printf("The lowest number is: %i", number1);
}
else if (number2 < number1 && number2 < number3) {
printf("The lowest number is: %i", number2);
}
else if (number3 < number2 && number3 < number1) {
printf("The lowest number is: %i", number3);
}
} // end lowest number
void displayAverage(int number1, int number2, int number3) {
int average = (number1 + number2 + number3) / 3;
printf("The average of the three numbers you entered is: %i", average);
} // display average
void displayMenu() {
CLS;
printf("\n===============================\n");
printf("========== MAIN MENU ==========\n");
printf("===============================\n");
printf("A. Enter a number\n");
printf("B. Display Highest Number entered\n");
printf("C. Display Lowest Number entered\n");
printf("D. Display Average of Numbers entered\n");
printf("Q. Quit the program\n");
printf("Enter your choice: ");
} // end displayMenu
void flush() {
while (getchar() != '\n');
} // end flush
char getUserChoice() {
char result;
displayMenu();
scanf("%c", &result); FLUSH;
result = toupper(result);
return result;
} // end getUserChoice

the following code should perform as you want.
Caveat: there may be some details that you would like to modify such as uncommenting the calls to getchar()
The following code has a number of constraints built it, like must enter the 3 numbers before trying to do any operations on those numbers.
The following code does not use non-portable calls to the shell.
the data is kept locally in the main() function and passed to each of the sub functions that need it.
Notice the function that changes the data is passed pointers to the data so the sub function can change that data.
useless macros were eliminated
the function: flush() was renamed for clarity as to what it does
appropriate error checking added
commented out unneeded if() statements
expanded flushStdin() to allow for either EOF or '\n'
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// Prototype Functions Here
void enterNumber (int*, int*, int*); // pass address so function can update
void highestNumber (int, int, int);
void lowestNumber (int, int, int);
void displayAverage(int, int, int);
void displayMenu ( void ); // corrected prototypes
void flushStdin ( void );
char getUserChoice ( void );
int main( void ) // only two valid signatures for main()
// this is one of them
{
char userSelection;
int number1; // added local data variables
int number2;
int number3;
int gotSelections = 0; // so cannot try to work with uninitialized data
do
{
userSelection = getUserChoice(); // Gets/DisplaysMenu
switch (userSelection)
{
case '1': // Enter a number
enterNumber( &number1, &number2, &number3 ); // pass expected parameters
gotSelections = 1;
break;
case '2': // Display Highest Number Entered
if( gotSelections )
{ // then data initialized
highestNumber( number1, number2, number3 ); // pass expected parameters
}
else
{ // else tried to pass unitialized data
printf( "must enter numbers before gathering Statistics\n" );
}
break;
case '3': // Display Lowest Number entered
if( gotSelections )
{ // then data initialized
lowestNumber( number1, number2, number3 ); // pass expected parameters
}
else
{ // else tried to pass unitialized data
printf( "must enter numbers before gathering Statistics\n" );
}
break;
case '4': // Display Average of Numbers entered
if( gotSelections )
{ // then data initialized
displayAverage( number1, number2, number3 );
}
else
{ // else tried to pass unitialized data
printf( "must enter numbers before gathering Statistics\n" );
}
break;
case 'Q': // Quit the program
printf("You have quit the program\n");
//system( "pause" );
break;
default: // Invalid Selection
printf("Invalid selection...try again!\n");
//system( "pause" );
break;
} // end switch
flushStdin();
//getchar();
} while (userSelection != 'Q');
//system( "pause" );
//flushStdin();
getchar();
} // end of main
void enterNumber(int * pNumber1, int *pNumber2, int *pNumber3)
{
printf("Enter a number 1:\n ");
if( 1 != scanf("%i", pNumber1) )
{
fprintf( stderr, "scanf for number1 failed" );
flushStdin();
getchar();
exit( EXIT_FAILURE );
}
printf("Enter a number 2:\n ");
if( 1 != scanf("%i", pNumber2) )
{
fprintf( stderr, "scanf failed for number2" );
flushStdin();
getchar();
exit( EXIT_FAILURE );
}
printf("Enter a number 3:\n ");
if( 1 != scanf("%i", pNumber3) )
{
fprintf( stderr, "scanf for number3 failed" );
flushStdin();
getchar();
exit( EXIT_FAILURE );
}
} //end enter number
void highestNumber(int number1, int number2, int number3)
{
if (number1 > number2 && number1 > number3)
{
printf("The highest number is: %i\n", number1);
}
else if (number2 > number1 && number2 > number3)
{
printf("The highest number is: %i\n", number2);
}
else //if (number3 > number2 && number3 > number1)
{
printf("The highest number is: %i\n", number3);
}
} //end highest number
void lowestNumber(int number1, int number2, int number3)
{
if (number1 < number2 && number1 < number3)
{
printf("The lowest number is: %i\n", number1);
}
else if (number2 < number1 && number2 < number3)
{
printf("The lowest number is: %i\n", number2);
}
else //if (number3 < number2 && number3 < number1)
{
printf("The lowest number is: %i\n", number3);
}
} // end lowest number
void displayAverage(int number1, int number2, int number3)
{
int average = (number1 + number2 + number3) / 3;
printf("The average of the three numbers you entered is: %i\n", average);
} // display average
void displayMenu()
{
//system( "cls" );
puts( "\033[H \033[J"); // \033 is octal value for 'escape'
printf("\n===============================\n");
printf("========== MAIN MENU ==========\n");
printf("===============================\n");
printf("1. Enter a number\n");
printf("2. Display Highest Number entered\n");
printf("3. Display Lowest Number entered\n");
printf("4. Display Average of Numbers entered\n");
printf("Q. Quit the program\n");
printf("Enter your choice: ");
} // end displayMenu
void flushStdin()
{
int ch;
while ( (ch = getchar()) != EOF && '\n' != ch );
} // end flush
char getUserChoice()
{
char result;
displayMenu();
if( 1 != scanf(" %c", &result) )
{
fprintf( stderr, "scanf for menu entry failed" );
flushStdin();
getchar();
exit( EXIT_FAILURE );
}
flushStdin();
//getchar();
result = (char)toupper((int)result);
return result;
} // end getUserChoice

Related

Should I include both fflush(stdin) and a space in scanf() or will only one of them suffice? [duplicate]

This question already has answers here:
Using fflush(stdin)
(7 answers)
Closed 4 years ago.
My calculator app hasn't been working properly after a user inputs a number. So I added fflush(stdin) and a space after the %d in scanf(). My question is should I only include both fflush(stdin) and a space after %c or will only one of the options suffice? I'm working on a Macbook, so I'm concerned that if I leave one out it won't work on other operating systems.
#include <stdio.h>
#include <stdlib.h>
//PROTOTYPE
int operationSwitch(); //Function to calculate total of operand1 and operand2.
int menu(); //Function for main menu.
int iResume(); //Function to continue the program or not.
char iOperation = '\0'; //choices (1-7)
float operand1 = 0; //number 1
float operand2 = 0; //number 2
float operandTotal = 0; //total
int testPrime, counter, prime = 0;
char cContinue = '\0';
char symbol = '\0';
int main(){
menu();
return 0;
}
int menu (){
do {
printf("\nPlease choose an operation: ");
printf("\n(1) Addition\n ");
printf("\n(2) Subtraction\n ");
printf("\n(3) Multiplication\n ");
printf("\n(4) Division\n ");
printf("\n(5) Modulus (integers only)\n ");
printf("\n(6) Test if Prime (integers only)\n ");
printf("\n(7) Exit\n ");
printf("\nChoose (1-7):\t");
fflush(stdin);
scanf(" %c", &iOperation);
} while (iOperation < 49 || iOperation > 55 );
if (iOperation != 54 && iOperation != 55){ //ASCII 55 == 7)
printf("\nEnter number 1:\t");
fflush(stdin);
scanf(" %f", &operand1);
printf("\nEnter number 2:\t");
fflush(stdin);
scanf(" %f", &operand2);
}
operationSwitch();
/*** RESULTS ***/
if ( symbol == '/' && operand2 == 0) {
printf("\n\t-----| Answer: %.2f / %.2f = Undefined |-----\n", operand1,operand2);
} else if (iOperation != 54) {
printf("\n\t-----| Answer: %.2f %c %.2f = %.2f |-----\n", operand1, symbol, operand2, operandTotal);
}
iResume();
return 0;
} //End Menu
/*********************************
SWITCH FUNCTION
*********************************/
int operationSwitch() {
switch (iOperation) {
case 49://1 Addition Ascii 49 == 1 43 == +
operandTotal = operand1 + operand2;
symbol = '+';
break;
case 50: //2 Substraction
operandTotal = operand1 - operand2;
symbol = '-';
break;
case 51: //3 Multiplication
operandTotal = operand1 * operand2;
symbol = '*';
break;
case 52: //4 Division
operandTotal = operand1 / operand2;
symbol = '/';
break;
case 53: //5 Modulus
operandTotal = (int)operand1 % (int)operand2;
symbol = '%';
break;
case 54: //6
prime = 1;
printf("\nEnter number to be tested for prime: ");
fflush(stdin);
scanf(" %d", &testPrime);
for(counter = 2; counter <= (testPrime/2); counter++ )
{
if(testPrime % counter == 0)
{
prime = 0;
break;
}
}
if (prime == 1) {
printf("\n\t| %d is a prime number. |\n", testPrime);
}
else {
printf("\n\t| %d is not a prime number. |\n", testPrime);
printf("\n\t| %d * %d = %d \n", testPrime/counter, counter , testPrime);
}
break;
case 55:
printf("\nGood Bye\n");
exit(0);
break;
default:
printf("\nYou entered: %c - Please try again ", iOperation );
break;
} //End Switch iOperation
return 0;
} //End Switch Function
/*********************************
RESUME FUNCTION
*********************************/
int iResume() {
printf("\nWould you like to try again?\nPress \'Y\' to go to menu,\nor any key to quit?\t");
fflush(stdin);
scanf(" %c", &cContinue);
if (cContinue == 'y' || cContinue == 'Y'){
menu();
} else {
printf("Good Bye!\n" );
}
return 0;
}
fflush(stdin) is undefiined behavior.
int fflush(FILE *ostream);
ostream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes
any unwritten data for that stream to be delivered to the host
environment to be written to the file; otherwise, the behavior is
undefined.

scanf from the buffer is not working properly

I will use this small part of code in my assignment but there are some problems. When I don't use fflush(stdin) it doesn't scan the basetype. But when I use fflush(stdin) it scans the basetype but the scanf inside the while loop doesn't continue to take the characters from the buffer. For example when I enter 2A... Please help.
#include <stdio.h>
#include <math.h>
int main() {
int operation, basetype, number1;
char num1;
printf("Please enter the number of the operation you would like to perform:");
printf("\n1. Bitwise OR\n2. Bitwise NOT\n3. Bitwise COMPARE\n4. Exit");
scanf("%d", &operation);
if (operation == 1) {
printf("You chose Bitwise OR operation.");
printf("\nPlease enter the first number:");
scanf(" %c", &num1);
fflush(stdin);
printf("\nPlease specify the base(10/16):");
scanf("%d", &basetype);
if (basetype == 10) {
while (num1 != 10) {
number1 = num1 - '0';
if (number1 >= 1 && number1 <= 9) {
printf("ok");
} else
printf("not ok");
scanf("%c", &num1);
}
}
}
return 0;
}
fflush(stdin); has undefined behavior, do not use it to attempt to flush the standard input buffer. You could instead write:
{ int c; while ((c = getchar()) != EOF && c != '\n') continue; }
You should also decide whether you read a number in num1 or a digit. "%c" is for reading a single character, "%d" to read a number in decimal format.
There is a scanf format tailored for your needs: %i converts a number encoded in a user specified base, 8, 10 or 16 depending on the initial characters, just like the C source code syntax for integer literals.
Here is a simplified program that can deal with hexadecimal input entered with a 0x prefix, such as 0x40 for 64:
#include <stdio.h>
#include <math.h>
int main(void) {
int operation, number1, number2, result;
printf("Please enter the number of the operation you would like to perform:\n"
"1. Bitwise OR\n"
"2. Bitwise NOT\n"
"3. Bitwise COMPARE\n"
"4. Exit\n");
if (scanf("%i", &operation) != 1)
return 1;
if (operation == 1) {
printf("You chose Bitwise OR operation.\n");
printf("Please enter the first number: ");
if (scanf("%i", &number1) != 1)
return 1;
printf("Please enter the second number: ");
if (scanf("%i", &number2) != 1)
return 1;
result = number1 | number2;
printf("%d (0x%x) | %d (0x%x) = %d (0x%x)\n",
number1, number1, number2, number2, result, result);
}
return 0;
}
the following proposed code:
cleanly compiles
contains embedded comments about problems with the code
is organized to clearly show what each part of the code is doing
for Bitwise_OR operation clearly shows the code does nothing, especially not a bitwise OR operation
and now the proposed code:
#include <stdio.h> // scanf(), printf(), perror()
#include <stdlib.h> // exit(), EXIT_FAILURE
//#include<math.h>
enum
{
Bitwise_OR = 1,
Bitwise_NOT,
Bitwise_COMPARE,
Exit
};
int main( void )
{
char operation;
int basetype;
int number1;
char num1;
puts("Please enter the number of the operation you would like to perform:");
printf( "%s",
"1. Bitwise OR\n"
"2. Bitwise NOT\n"
"3. Bitwise COMPARE\n"
"4. Exit");
if( 1 != scanf(" %c",&operation) )
{
perror( "scanf for operation failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
switch( operation )
{
case Bitwise_OR: //<-- bitwise OR never performed
printf("You chose Bitwise OR operation.");
printf("\nPlease enter the first number:");
if( 1 != scanf(" %c",&num1) )
{
perror( "scanf for first number failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
//fflush(stdin);
printf("\nPlease specify the base(10/16):");
if( 1 != scanf("%d", &basetype) )
{
perror( "scanf for base failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
switch(basetype)
{
case 10:
while(num1 != 10) //<-- user entering 0x0A is extremely unlikely
{
number1=num1-'0'; //<-- what if num1 not '0'...'9'
if(number1>=1 && number1<=9)
{
printf("ok");
}
else
printf("not ok");
// either retry first digit or get second digit
scanf(" %c",&num1); //<-- leading space to consume 'white space'
}
break;
case 16:
break;
default:
puts( "base must be 10 or 16" );
break;
} // end switch()
break;
case Bitwise_NOT:
break;
case Bitwise_COMPARE:
break;
case Exit:
break;
default:
break;
} // end switch()
return 0;
} // end function: main

Check whether the second number is greater than or less than to first number

Im doing an testing program. There will be 2 inputs, first number and second number.Check the first number if it is greater than or less if the first number is less to second number. The user will input again the "Enter second number", i dont know how should I do the do while in there. thanks
This is my code:
#include<stdio.h>
int main()
{
int number1,number2,total;
printf("Enter first number");
scanf("%d",&number1);
printf("Enter second number");
scanf("%d",&number2);
if(number1 > number2)
{
total = number1 - number2;
printf("%d",total);
}
else
{
printf("Number 1 is less than to number 2");
}
return 0;
}
#include <stdio.h>
int main(void){
int number1, number2, total;
printf("Enter first number >");
scanf("%d", &number1);
while(1){
printf("Enter second number >");
int status = scanf("%d", &number2);//check return value of scanf
if(status == 1){// read integer but No check such as 3.5, 3?
if(number1 < number2)
printf("Number 1 is less than to number 2\n");
else
break;
} else if(status == 0){//can't read integer
printf("invalid input.\n");
scanf("%*[^\n]");scanf("%*c");//clear up to newline
} else {//if(status == EOF){//you want finish ;-)
puts("bye");
return -1;
}
}
total = number1 - number2;
printf("%d\n", total);
return 0;
}

If statement in while loop not working

For the past 3 days, I have been having program trying to fix this code. Can someone here please help. The program doesn't print the last statement if a negative number is imputed. If a negative number is imputed, instead of printing "Terminating the program...", it jumps to print "Enter the first number:" before quitting.
int main(void)
{
int choose, number1, number2, total_hold;
do
{
printf("\n");
printf("1: sum of two numbers \n");
printf("2: difference of two numbers\n");
printf("3: product of two numbers\n");
printf("<0:terminate the program\n");
printf("Select calculation:");
scanf("%d", &choose);
printf("Enter the first number:");
scanf("%d", &number1);
printf("Enter the second number:");
scanf("%d", &number2);
if (choose == 1)
{
total_hold = sumOfNumbers(number1, number2);
displayS(number1, number2, total_hold);
}
else if (choose == 2)
{
total_hold = differenceOfNumbers(number1, number2);
displayD(number1, number2, total_hold);
}
else if (choose == 3)
{
total_hold = MultiplicationOfNumbers(number1, number2);
displayM(number1, number2, total_hold);
}
else if (choose < 0)
{
printf("Terminating the program...");
break;
}
}
while (choose > 0);
return 0;
}
Place this:
if (choose < 0)
{
printf("Terminating the program...");
break;
}
Immediately after you scanf("%d", &choose).
In addition to that, you may as well change while (choose > 0) to while (1).
You are using a
do{
statement 1;
statement 2;
...
...
statement n;
}while(condition);
Hence in do-while loop all the statement are executed at-least once and then the condition is checked.
Better to use while loop instead of do-while
You're executing three scanf instructions before ANY if statement. If you want to check if choose variable is lower than 0 you can do it BEFORE the other two scanf calls like this
int main(void)
{
int choose, number1, number2, total_hold;
do
{
printf("\n");
printf("1: sum of two numbers \n");
printf("2: difference of two numbers\n");
printf("3: product of two numbers\n");
printf("<0:terminate the program\n");
printf("Select calculation:");
scanf("%d", &choose);
if (choose < 0)
{
printf("Terminating the program...");
break;
}
printf("Enter the first number:");
scanf("%d", &number1);
printf("Enter the second number:");
scanf("%d", &number2);
if (choose == 1)
{
total_hold = sumOfNumbers(number1, number2);
displayS(number1, number2, total_hold);
}
else if (choose == 2)
{
total_hold = differenceOfNumbers(number1, number2);
displayD(number1, number2, total_hold);
}
else if (choose == 3)
{
total_hold = MultiplicationOfNumbers(number1, number2);
displayM(number1, number2, total_hold);
}
}
while (choose > 0);
return 0;
}
Statements
printf("Enter the first number:");
scanf("%d", &number1);
printf("Enter the second number:");
scanf("%d", &number2);
are executed indpendently of the value entered in varaible choose because the last is tested after these statements.
The more correct design of the program could look like (without testing)
#include <stdio.h>
int main(void)
{
while ( 1 )
{
enum { Exit = 0, Addition = 1, Difference = 2, Multiplication = 3 };
unsigned int choose;
int number1, number2, total_hold;
printf( "\n" );
printf( "%d: sum of two numbers \n", Addition );
printf( "%d: difference of two numbers\n", Difference );
printf( "%d: product of two numbers\n", Multiplication );
printf( "%d: terminate the program\n", Exit );
printf( "Select calculation:" );
scanf( "%u", &choose );
if ( choose == Exit )
{
printf( "Terminating the program..." );
break;
}
if ( choose <= Multiplication )
{
printf( "Enter the first number:" );
scanf( "%d", &number1 );
printf( "Enter the second number:" );
scanf( "%d", &number2 );
}
switch ( choose )
{
case Addition: {
total_hold = sumOfNumbers(number1, number2);
displayS(number1, number2, total_hold);
break;
case Difference:
total_hold = differenceOfNumbers(number1, number2);
displayD(number1, number2, total_hold);
break;
case Multiplication:
total_hold = MultiplicationOfNumbers(number1, number2);
displayM(number1, number2, total_hold);
break;
default:
printf("Invalid selection. Try again.\n");
break;
}
}
return 0;
}

how to repeat a c program from the beginning and clean the screen and 1st input values?

i m new in programing.
i've written a simple program.
i want to repeat the program again and again and it can only exit when user wants to exit.
here is my program
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
int num1, num2, a, m, s, choice;
float d;
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Any Key To Exit");
getch();
return 0;
}
and here is the output
"Enter The First Number: 10
Enter The Second Number: 10
Enter Your Choice
For Addition Type A
For Multipication Type M
For Division Type D
For Substraction Type S : A
The Addition Of The Number Is= 20
Press Any Key To Exit"
I want a line before the line Press Any Key To Exit
"If You Want To Calculate Again Press Y
or
Press Any Key To Exit"
when press Y then the program should start from the beginning.
How can i do this???
wrap the code inside a do{} while() ?
char answer;
do{
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Y to continue. Press any Key To Exit");
scanf(" %c",&answer); // dont forget type &
}
while(answer == 'y' || answer == 'Y');
Declare a variable, let's say answer, which will store the user answer when you ask for "Press Y to continue. Press any Key To Exit". Check to see what value has that variable. If is 'y' or 'Y', the loop will repeat. If the user pressed other key, the loop is over.
You can also use recursion, which is often used in more functional oriented programming languages.
Pseudo-code:
myfunction = do
...
b <- somethingtodo
...
if b
then myfunction
else return ()
Relative to Jens's solution, it would look like:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main (void)
{
char choice;
int num1, num2, cont;
printf("Enter the first number: ");
scanf("%d", &num1);
getchar ();
printf("Enter the second number: ");
scanf("%d", &num2);
getchar ();
printf("A - addition\n");
printf("S - subtraction\n");
printf("M - multiplication\n");
printf("D - division\n");
printf("[ASMD]? ");
choice = (char)toupper(getchar());
getchar ();
printf("\n");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
printf("Continue [YN]? ");
cont = toupper(getchar());
getchar ();
if (cont == 'Y')
return main(); // the difference.
else if (cont == 'N')
return EXIT_SUCCESS;
}
}
I would move the calculation stuff in it's own function and then use while() in main.
I have tried to fix other problems as well (this solution only uses standard C functions).
#include <stdio.h> // puts, printf, fprintf, scanf, getchar, stderr, EOF
#include <stdlib.h> // exit, EXIT_SUCCESS, EXIT_FAILURE
#include <ctype.h> // toupper
char fail_on_eof (int c)
{
if (c == EOF)
exit (EXIT_FAILURE);
// In case of fail_on_eof (scanf (...)) the return value of this this
// function is not useful
// scanf () returns the number of chars read or EOF
// getchar () returns a char or EOF
return (char) c;
}
void skip_to_next_line (void)
{
char c;
do
{
c = fail_on_eof (getchar ());
} while (c != '\n');
}
char read_upcase_char_line (char* prompt)
{
char c;
printf ("%s ", prompt);
c = fail_on_eof (toupper (getchar ()));
skip_to_next_line ();
return c;
}
int read_num_line (char* prompt)
{
int num;
printf ("%s ", prompt);
fail_on_eof (scanf ("%d", &num));
skip_to_next_line ();
return num;
}
int calculate (void)
{
char choice;
int num1, num2, cont;
num1 = read_num_line ("Enter the first number:");
num2 = read_num_line ("Enter the second number:");
puts("A - addition");
puts("S - subtraction");
puts("M - multiplication");
puts("D - division");
choice = read_upcase_char_line ("[ASMD]?");
puts("");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
// Better use stderr for error messages
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
// Better use stderr for error messages
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
cont = read_upcase_char_line ("Continue [YN]?");
if (cont == 'Y')
return -1;
else if (cont == 'N')
return 0;
}
}
int main(void)
{
while (calculate ());
return EXIT_SUCCESS; // Use this constant to avoid platform specific issues with the return code
}

Resources