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;
}
Related
Im writing a code that evolves the computer and I entering numbers and added them together to see who wins.
There are three problems:
Problem 1: When I try to recall the 'main()' function the 'game()' wont appear.
Problem 2: I can't seem to run the code forever until user decides to stop.
Problem 3: The point system isn't accurate enough.
Any help would be grateful.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int human_fingers;
int comp_fingers;
int menu_choice;
int answer;
int count = 1;
int point1 = 0, point2 = 0;
int total;
void intro() {
printf("Welcome to Morra - Odds and Even!\n\n");
printf("The rules of the game are pretty simple\n");
printf("You and the computer will pick a side each round\n");
printf("You must enter a number and the total sum will determine the winner!\n\n");
}
void example() {
printf("You picked even, by default the computer will be odd this round\n");
printf("You entered 3 and the computer entered 5\n");
printf("3 + 5 = 8, so you win because you choose even!\n");
}
void game() {
while(count < 7)
{
count = count + 1;
printf("Enter a number to choose a side:\n");
printf("Even [1] / Odd [2]\n");
scanf("%d", &menu_choice);
while((menu_choice<1) || (menu_choice>2)){
printf("Invalid entry, please Enter 1-2: ");
scanf("%d",&menu_choice);}
if(menu_choice == 1)
{
printf("The computer will be odd this turn\n");
printf("\nPlease enter an number (1-10)\n");
scanf("%d", &human_fingers);
while((human_fingers<1) || (human_fingers>10)){
printf("Invalid entry, please enter 1-10:");
scanf("%d",&human_fingers);}
printf("Computer is choosing a number....\n");
srand(time(NULL));
comp_fingers = rand() % 10 + 1;
printf("You: %d\n", human_fingers);
printf("Computer: %d\n", comp_fingers);
int result;
result = human_fingers + comp_fingers;
printf("Total is %d\n", result);
total = result % 2;
if(total == 0)
{
printf("This turn goes to You!\n\n");
printf("You: %d\n", point1 + 1);
printf("Computer: %d\n\n", point2 + 0 );
point1++;
}
else
{
printf("This turn goes to Computer!\n\n");
printf("You: %d\n", point1 + 0 );
printf("Computer: %d\n\n", point2 + 1);
point2++;
}
}
if(menu_choice == 2)
{
printf("The computer will be even this turn\n");
printf("\nPlease enter an number (1-10)\n");
scanf("%d", &human_fingers);
while((human_fingers<1) || (human_fingers>10)){
printf("Invalid entry, please enter 1-10:");
scanf("%d",&human_fingers);}
printf("Computer is choosing a number...\n");
srand(time(NULL));
comp_fingers = rand() % 10 + 1;
printf("You: %d\n", human_fingers);
printf("Computer: %d\n", comp_fingers);
int result;
result = human_fingers + comp_fingers;
printf("Total is %d\n", result);
total = result % 1;
if(total == 0)
{
printf("This turn goes to Computer!\n\n");
printf("You: %d\n", point1 + 0);
printf("Computer: %d\n\n", point2 + 1);
point1++;
}
else
{
printf("This turn goes to You!\n\n");
printf("You: %d\n", point1 + 1);
printf("Computer: %d\n\n", point2 + 0 );
point2++;
}
}
}
if(point1 > point2)
printf("You won, you beat the computer!\n");
else
printf("Unlucky the computer won!\n");
}
void end(){
printf("Game has ended!\n");
}
int main()
{
intro();
printf("Would you like an example to demostrate?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer == 1 )
{ example();
printf("\n\n");
game();
}
else
{ printf("\n\n");
game();
}
end();
printf("Would you like play another game?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer == 1)
{
main();
}
else {
printf("Thanks for playing MORRA - ODDS AND EVEN.");
}
return 0;
}
Why not:
int main()
{
for(;;) // Infinite loop. -- equivalent of while(1) if you prefer.
{
intro();
printf("Would you like an example to demostrate?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer == 1 )
{ example();
printf("\n\n");
game();
}
else
{ printf("\n\n");
game();
}
end();
printf("Would you like play another game?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer != 1)
{
printf("Thanks for playing MORRA - ODDS AND EVEN.");
break;
//^___ exit the infinite loop.
}
}
return 0;
}
Recalling the main you should definitely not, in almost any case. Just create loops if you want to repeat everything.
I was just building a simple calculator in C using CodeBlocks. After building and running it it went smoothly till the scanf() statement. After i put in 2 numbers for my program to scan and hit enter the program crashed and sent a message "C.exe has stopped working."Please help. Here is the code -
#include <stdio.h>
#include <stdlib.h>
int Calculator();
int main()
{
Calculator();
return 7;
}
int Calculator()
{
int num1;
int num2;
int operation;
printf("Hello. I am a calculator.\nChoose any operation you want to carry out- \n 1.Addition \n 2.Subtraction \n 3.Multiplication \n 4.Division \n");
scanf("%d", &operation);
switch (operation)
{
case 1:
printf("OK. You have chosen addition. \nEnter any 2 numbers to be added \n");
scanf("%d", num1);
scanf("%d", num2);
printf("%d + %d is = %d. \n Thank you. ", num1, num2, num1 + num2);
break;
case 2:
printf("OK. You have chosen subtraction. \nEnter any 2 numbers to be subtracted \n");
scanf("%d", num1);
scanf("%d", num2);
printf("%d - %d is = %d. \n Thank you. ", num1, num2, num1 - num2);
break;
case 3:
printf("OK. You have chosen multiplication. \nEnter any 2 numbers to be multiplied \n");
scanf("%d", num1);
scanf("%d", num2);
printf("%d x %d is = %d. \n Thank you. ", num1, num2, num1 * num2);
break;
case 4:
printf("OK. You have chosen division. \nEnter any 2 numbers to be divided \n");
scanf("%d", num1);
scanf("%d", num2);
printf("%d ÷ %d is = %d. \n Thank you. ", num1, num2, num1 / num2);
break;
default:
printf("\nHUH?\n\n");
break;
}
return 20;
}
Your scanf calls inside the switch are wrong. You need &.
Change:
scanf("%d", num1);
scanf("%d", num2);
to:
scanf("%d", &num1);
scanf("%d", &num2);
I suggest you to check the return of scanf.
Try to understand this:
#include <stdio.h>
#include <stdlib.h>
int Calculator( void );
int main( void )
{
Calculator();
}
int Calculator( void )
{
int num1;
int num2;
int operation;
printf("Hello. I am a calculator.\nChoose any operation you want to carry out- \n 1.Addition \n 2.Subtraction \n 3.Multiplication \n 4.Division \n");
if ( scanf("%d", &operation) != 1 ){
printf( "Error scanf() ==>> on Operation" );
exit( 1 );
}
switch (operation)
{
case 1:
printf("OK. You have chosen addition. \nEnter any 2 numbers to be added \n");
if ( scanf("%d", &num1) != 1 ){
printf( "Error scanf() ==>> switch - case 1 ==>> 1" );
exit( 1 );
}
if ( scanf("%d", &num2) != 1 ){
printf( "Error scanf() ==>> switch - case 1 ==>> 2" );
exit( 1 );
}
printf("%d + %d is = %d. \n Thank you. ", num1, num2, num1 + num2);
break;
case 2:
printf("OK. You have chosen subtraction. \nEnter any 2 numbers to be subtracted \n");
if ( scanf("%d", &num1) != 1 ){
printf( "Error scanf() ==>> switch - case 2 ==>> 1" );
exit( 1 );
}
if ( scanf("%d", &num2) != 1 ){
printf( "Error scanf() ==>> switch - case 2 ==>> 2" );
exit( 1 );
}
printf("%d - %d is = %d. \n Thank you. ", num1, num2, num1 - num2);
break;
case 3:
printf("OK. You have chosen multiplication. \nEnter any 2 numbers to be multiplied \n");
if ( scanf("%d", &num1) != 1 ){
printf( "Error scanf() ==>> switch - case 3 ==>> 1" );
exit( 1 );
}
if ( scanf("%d", &num2) != 1 ){
printf( "Error scanf() ==>> switch - case 3 ==>> 2" );
exit( 1 );
}
printf("%d x %d is = %d. \n Thank you. ", num1, num2, num1 * num2);
break;
case 4:
printf("OK. You have chosen division. \nEnter any 2 numbers to be divided \n");
if ( scanf("%d", &num1) != 1 ){
printf( "Error scanf() ==>> switch - case 4 ==>> 1" );
exit( 1 );
}
if ( scanf("%d", &num2) != 1 ){
printf( "Error scanf() ==>> switch - case 4 ==>> 2" );
exit( 1 );
}
printf("%d ÷ %d is = %d. \n Thank you. ", num1, num2, num1 / num2);
break;
default:
printf("\nHUH?\n\n");
break;
}
return 20;
}
You should reconsider your return statements from main and Calculator
You want to
scanf("%d", &num1);
scanf("%d", &num2);
at each instance.
Also, if you want to prevent other crashes, watch out for division by zero :)
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
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;
}
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
}