C for loop, How do I continuously prompt the user? - c

I am learning about loops such as for and while loops, so I decided to put myself to the test and write a program which you can see the code for below. The program gives the user a range of options to enter an option, but the problem I have is that i want to be able to continuously ask the user to "Enter a command" after an operation has completed.
For example, if I entered 1, the necessary code would be executed but then the whole program just ends. How can I enhance this program so it continuously asks the user to enter new commands until the user forcibly exits by entering 0?
#include <stdio.h>
int main()
{
int n;
int credit = 0;
int YN;
printf("Welcome to Cash booking software Version 2.145\n");
printf("--------------------------------------------------------\n");
printf("Use the following options:\n");
printf("0 -- Exit\n");
printf("1 -- Display Credit\n");
printf("2 -- Change Credit\n");
printf("3 -- Remove Credit\n");
printf("\n");
for ( ; ; )
{
printf("Enter a command: ");
scanf("%d", &n);
if (n == 0)
{
return 0;
}
else if (n == 1)
{
printf("Your credit is £%d", credit);
}
else if (n == 2)
{
printf("Enter a new credit value: \n");
scanf("%d", &credit);
printf("Your new credit value is %d", credit);
}
else if (n == 3)
{
printf("Are you sure you want to remove your Credit value? (Y=1/N=2)");
scanf("%d", &YN);
if (YN == 1)
{
credit = 0;
}
else
;
}
return 0;
}
}

As other users explained return 0; inside of the loop is what is causing the problem and moving it out would solve it, But since you're learning about loops I think this is a great example to teach you something.
Usually you should only use a for loop when you have some parameter that defines de number of times the loop will be executed. The fact that you just used for( ; ; ) is a huge red flag for ther is a betther way to do this.
For example the proper way to write an infinite loop in c is while(1){//code in the loop}. So you could change your for loop with this and it will work fine (relocating return 0; in the correct location).
But since in this code you dont really want an infinite loop (usually they're a bad idea), but you want the loop to run until is pressed 0, the best solution is to use a do{} while(); loop where inside of do you check if either 1, 2 or 3 is pressed and perform their functionality, and then in the while condition you check if 0 has been pressed, and only in that case the program exits.
This is how the code would look like:
do{
printf("Enter a command: ");
scanf("%d", &n);
if (n == 1){
printf("Your credit is £%d\n", credit); // \n added
}
else if (n == 2){
printf("Enter a new credit value: \n");
scanf("%d", &credit);
printf("Your new credit value is %d\n", credit); // \n added
}
else if (n == 3){
printf("Are you sure you want to remove your Credit value? (Y=1/N=2):");
scanf("%d", &YN);
if (YN == 1){
credit = 0;
}
}
} while(n != 0);
return 0;
Also note that I added \n in some printf() commands for better visualization.

use continue statement at the end of each condition , and you can use break statement instead of return 0, so the code will be :
if (n == 0)
{
break;
}
else if (n == 1)
{
printf("Your credit is £%d ", credit);
continue;
}
else if (n == 2)
{
printf("Enter a new credit value: \n");
scanf("%d", &credit);
printf("Your new credit value is %d ", credit);
continue;
}
else if (n == 3)
{
printf("Are you sure you want to remove your Credit value? (Y=1/N=2) : ");
scanf("%d", &YN);
if (YN == 1)
{
credit = 0;
continue;
}
else {
continue;
}

Related

How can I modify program to set array range from 0 to 100 in program below

I need the code below to recognize if the grades entered is below 1 or greater than 100. If it is not within the parameters, I want to let the user know and allow them to enter another grade without exiting the program or losing grades they have already entered. I don't want the program to quit until the user enters q and I want to ensure all of the valid grades entered print at that time. I have tried numerous methods and am not getting the right results. I think I probably need some other else if statement, but I haven't been able to find the right one to work. Any information you can share to get me on the right track would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection in Parenthesis******\n Add grades(a)\n Quit(q) \n");
scanf("%c",&choice);
if(choice == 'a' || 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
printf("Grades are:\n");
for(i=0; i<gCount; i++)
{
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
You can do a while loop to verify the user input. With a while you'll be able to force the user to enter the right grade.
if(choice == 'A' || choice == 'a'){
printf("Enter grade:");
scanf("%d", &grades);
getchar();
while(grade < 1 || grade > 100){
printf("You entered a wrong number\n");
printf("Enter a grade between 1 and 100: ");
scanf("%d", &grades);
getchar();
}
gradeArray[gCount] = grades;
}
your solution is almost aligned with what you had in mind. Here is how you can do it differently.
#include <stdio.h>
int main()
{
char choice;
int arraySize = 100; //change this to any number you wish
int gradeScore = 0;
int gradeArray[arraySize];
int gCount = 0;
int showCount = 0;
while(choice != 'q')
{
//to ask for user's input every time
printf("What do you want to do? Enter\n");
printf("'a' to add grades\n");
printf("'q' to quit\n");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
//your implementation should check for user input before proceeding
if(choice != 'a')
{
//in this condition, 'q' is technically an incorrect input but your design states that 'q' is for quitting
//thus, do not alert the user here if 'q' is entered
if(choice != 'q')
{
//a condition to warn the user for incorrect input
printf("Incorrect input. Please enter only 'a' or 'q'\n");
}
}
else if(choice == 'a')
{
printf("Enter grade: \n");
scanf(" %d", &gradeScore);
//to check for user input if the grades entered are less than 1 or more than 100
if(gradeScore < 1 || gradeScore >100)
{
//print a warning message
printf("The grade you entered is invalid. Please enter a grade from 1 - 100\n");
}
//for all correct inputs, store them in an array
else
{
printf("Grade entered\n");
gradeArray[gCount] = gradeScore;
gCount++;
}
}
}
//prints grade when 'q' is entered
if(choice == 'q')
{
printf("Grades are: \n");
for(showCount = 0; showCount < gCount ; showCount++)
{
printf("%d\n", gradeArray[showCount]);
}
}
}
To sum up the important parts, be sure to check for the user grade input to be in range of 1 - 100. Store the grade in the array if it is within range and be sure to increase the array counter, otherwise it will always store it in gradeArray[0] for the subsequent grades. Hope this helps
Use a do-while loop to keep the program looping back to get another choice unless a valid choice has been entered. Use fgetc to read a single character - fewer problems. Only print grades if at least one grade has been entered.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection******\n Add grades(a)\n Quit(q) \n");
do
{
choice = fgetc(stdin);
if(choice == 'a' || choice == 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
else if(choice != 'q')
printf("Invalid choice - try again\n");
} while (choice != 'a' && choice != 'A' && choice != 'q');
if(choice == 'q') //if the user choice is q, then exit the loop
break;
}
if(gCount > 0)
{
printf("Grades are:\n");
for(i=0; i<gCount; i++)
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}

Vending Machine - Logic Error

// My issue is a rather specific one, the code compiles "Insert Coins" "Coin
//not accepted " indefinitely and doesn't allow input at all. I've tried this
//program with "While" only loops and "do" loops and it always compiles
//indefinitely without allowing input.I'm trying to figure out where my logic
//error is and possibly a simpler solution if possible. Thanks.
#include <stdio.h>
int main(void){
int money, drink_selection, coins;
money = 0;
do{ //ISSUE HERE??
do{ //OR HERE??
printf("Insert Coins: "); //REPEATS THIS
scanf("%d" ,&coins); //DOESNT ALLOW THIS
if(coins == 0 || coins == 5 || coins == 10 || coins == 25)
{
money +=coins;
}
else {
printf("Coin not accepted \n");//REPEATS INDEFINITELY
}
}while(coins != 0); // looping here?
printf("Please select from the following menu: 1 - Coffee or 2 - Tea ) \n");
printf("Enter your choice: \n");
scanf("%d", &drink_selection);
switch(drink_selection){
case 1:
printf("You have selected coffee as your choice. \n");
money-=25;
if (money >=0){
printf("Please take your coffee. \n");
}
break;
case 2:
money-=15;
if (money >= 0){
printf("Tea dispensing \n");
}
break;
default:
printf("Ivalid input");
break;
}
if (money > 0){
printf("Your change is %d cents ", &coins);
}
else if (money < 0){
printf("Insufficient amount, your change is: %d", &coins);
}
}while(money == 0); //POSSIBLY ISSUE IS HERE?
return 0;
}

How to make the program restart if I press a certain button

I've recently written this "guess the number" program. My problem is that I want the program to restart when I press "y" after the "Play again" question comes. Any ideas? :)
srand( time(NULL) );
int secretNumber = rand()%100 + 1;
int guess = 0;
int counter = 0;
printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");
while(1)
{
counter++;
scanf("%d", &guess);
if (guess == secretNumber)
{
printf("It took you %d tries\n", counter);
printf("Play again (y/n)?\n");
break;
}
if (guess < secretNumber)
{
printf("Too low!\n");
}
if (guess > secretNumber)
{
printf("Too high!\n");
}
Put the entire code snippet you have inside another while(1) statement:
srand(time(NULL));
while(1)
{
int secretNumber = rand()%100 + 1;
int guess = 0;
int counter = 0;
printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");
while(1)
{
//code for guessing number
}
printf("Play again? ");
if (getchar() != 'y')
{
break;
}
}
This
printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");
needs to be inside your loop, unless you only want to give them one guess.
The easiest way to do what you want is to create a new secret number when they guess right, and bail out of your loop if they answer "No" to "do you want to play again?"
You can use another variable. like below.
char userinput = 'y';
while(input == 'y')
{
//your logic here
//And at the end use one scanf
printf("Play again (y/n)?\n");
scanf("%c", &userinput);
}
You need to add one new variable, In above case it's userinput.
use a while loop, with a loop variable of type bool say dec initially True. Put your code and initialize all the variables inside the loop, so that they can have a local scope and gets destroyed each time the loop is complete. Ask user for the dec variable if it presses "y" set it to True else set it to False. so that the loop may be skipped this time
code may be like :
char cha;
bool dec=True;
while(dec){
srand( time(NULL) );
int secretNumber = rand()%100 + 1;
int guess = 0;
int counter = 0;
printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");
while(1)
{
//code for guessing number
}
printf("Play again? ");
scanf("%c",&cha);
if (char== 'y')
bool=True;
else bool=False;
}

Random number game C

The game works fine my first time through, although; the second time it only gives you two lives... I have tried to change the number of lives but still can't figure out what I'm doing wrong.
// C_program_random_number_game
#include<stdio.h>
#include<time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int num1,x = 0;
char game, cont, replay;
printf("Would you like to play a game? : ");
scanf("%c",&game);
if (game == 'y' || game == 'Y')
{
printf("\nThe rules are simple. You have have 5 tries to guess the computers number. \n \n If you succeed you win the game, if you dont you lose the game. Good luck!");
do
{
int r = rand()%5 +1;
printf("\n\nEnter a number between 1 and 5 : ");
scanf("\n%d",&num1);
x++;
if(num1 > 0 && num1 < 5)
{
do
{
if(num1 < r)
{
printf("\nClose! try a little higher... : ");
x++;
}
else if (num1 > r)
{
printf("\nClose! try a little lower...: ");
x++;
}
scanf("%d",&num1);
}while(num1!=r && x <3);
if(num1 == r)
{
printf("\nWinner! >> you entered %d and the computer generated %d! \n",num1, r);
}
else if(num1 != r)
{
printf("\nBetter luck next time!");
}
printf("\n\nWould you like to play again? (y or n) : ");
scanf("\n%c",&replay);
}
else
{
printf("Sorry! Try again : ");
scanf("%d",&num1);
}
}while(replay == 'y'|| replay == 'Y');
}
else if (game == 'n' || game == 'N')
{
printf("Okay, maybe next time! ");
}
else
{
printf("Sorry, invalid data! ");
}
return 0;
}
There are all kinds of issues with you code (most of them are minor in terms of programming). Most of the errors are typos in what you want done via this question and what you printf().
As is, this code will random between 1-25, accept an input of any valid int, see if you matched it, and only give you 5 tries. (I didn't add error checking to enforce that the input is between 1-25. That should probably be added.)
I commented my code below with all my changes and went by that you had in the printf()s.
Note: See my comments above for explanations of my changes since I already pointed them out. I also formatted it so its a little more easy to read.
Note2: I did this quickly using an online compiler. If you find anything wrong with this or not working as you'd like, just comment below and I'll address it.
// C_program_random_number_game
#include<stdio.h>
#include<time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int num1,x = 0;
char game, cont, replay;
printf("Would you like to play a game? : ");
scanf("%c",&game);
if (game == 'y' || game == 'Y')
{
printf("\nThe rules are simple. You have have 5 tries to guess the computers number. \n \n If you succeed you win the game, if you dont you lose the game. Good luck!");
do
{
int r = rand()%25 +1;
printf("\n\nEnter a number between 1 and 25 : ");
scanf("%d",&num1);
do
{
printf("r = %d\n", r);
if(num1 < r)
{
printf("\nClose! try a little higher... : ");
x++; //Increment x if wrong guess
}
else if (num1 > r)
{
printf("\nClose! try a little lower...: ");
x++; //Increment x if wrong guess
}
scanf("%d",&num1);
}while(num1!=r && x < 5); //If x is 5 or more, they ran out of guesses (also, you want an && not an ||)
if(num1 == r) //Only print "winner" if they won!
{
printf("\nWinner! >> you entered %d and the computer generated %d! \n",num1, r);
}
printf("\nWould you like to play again? (y or n) : ");
scanf("\n%c",&replay);
}while(replay == 'y'|| replay == 'Y');
}
printf("Thanks for playing! ");
if (game == 'n' || game == 'N')
{
printf("Okay, maybe next time! ");
}
return 0;
}
There are a combination of two problems. The first is that you're not breaking out of the "for" loop when the number matches. Therefore the match is only checked on every third guess.
The second problem is in this logic check:
}while(num1!=r || x <= 3);
We see that this turns into "true" if the for loop is broken out of early.

Monty hall show simulation unexpected results

#include <stdio.h>
#include <time.h>
int main (void)
{
int pickedDoor, remainingDoor, hostDoor, winningDoor, option, games = 0, wins = 0;
float frequency = 0;
srand (time(NULL));
while (1)
{
printf ("Pick one of the three doors infront of you, which do you want?\n");
scanf ("%d", &pickedDoor);
if (pickedDoor > 3 || pickedDoor <= 0)
{
break;
}
winningDoor = rand() % 3 + 1;
do
{
hostDoor = rand() % 3 + 1;
} while (hostDoor == pickedDoor || hostDoor == winningDoor);
do
{
remainingDoor = rand() % 3+1;
} while (remainingDoor == pickedDoor || remainingDoor == hostDoor);
printf ("The door the host picked is %d\n", hostDoor);
do
{
printf("Do you want to switch doors? Please enter in the door you want:\n", hostdoor);
scanf("%d", &option);
if (option > 3 || option <= 0)
{return 0;}
}while (option == hostDoor);
if (option == winningDoor)
{
printf("You Won!\n");
wins++;
}
else
{
printf("YOU LOSE!\n");
}
games++;
}
frequency = ((float) wins / games) *100;
printf ("The number of games that you won is %d\n", wins);
printf ("The frequency of winning is %.0f%%\n", frequency);
return 0;
}
Hi, this is my version of the monty hall game show, im getting unexpected results though.
sometimes when I enter in a door for my option it just brings me back to the "pick one of the three doors infront of you" statement, when it should tell me if i have won or lost.
I think this is because the "option" door is equal to the "hostDoor.
I thought having "option != hostDoor" would fix it but it does not.
If i am correct in that assumption how can I fix it? If not why is it not working and how can I fix it?
To simulate correctly, OP needs to show the host door.
do {
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
if (option > 3 || option <= 0 ) {
return 0;
}
} while (option == hostDoor);
// instead of
#if 0
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
if (option > 3 || option <= 0 ) { return 0; }
#endif
To deal with OP " it should tell me if i have won or lost." problem, change
else if (option == remainingDoor)
to
else
Your scanf("%d", &option) is OK. I prefer the fgets()/sscanf() combo and its alway useful to check the result of scanf() family, but that is not your issue here.
Its because of these:
scanf ("%d", &pickedDoor);// reads \n after the last input
scanf("%d", &option); // reads \n after the last input
**option != hostDoor; // completely useless .. get rid of it**
I would suggest putting a getchar() after each scanf to get rid of the \n character
so something like this:
#include <stdio.h>
#include <time.h>
int main (void)
{
int pickedDoor, remainingDoor, hostDoor, winningDoor, option, games = 0, wins = 0;
char collect; //variable to collect any extra input like \n
float frequency = 0;
srand (time(NULL));
while (1)
{
printf ("Pick one of the three doors infront of you, which do you want?\n");
scanf ("%d", &pickedDoor);
collect = getchar(); // get rid of the \n from the input stream
printf("collect = %c\n",collect);
if(collect!='\n'){ // is it actually a \n or did you take in something else
putchar(collect); // if it isn't \n put it back
}
if (pickedDoor > 3 || pickedDoor <= 0)
{
break;
}
winningDoor = rand() % 3 + 1;
do
{
hostDoor = rand() % 3 + 1;
} while (hostDoor == pickedDoor || hostDoor == winningDoor);
do
{
remainingDoor = rand() % 3+1;
} while (remainingDoor == pickedDoor || remainingDoor == hostDoor);
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
collect = getchar(); // get rid of the \n from the input stream
printf("collect = %c\n",collect);
if(collect!='\n'){ // is it actually a \n or did you take in something else
putchar(collect); // if it isn't \n put it back
}
if (option > 3 || option <= 0 )
{
return 0;
}
if (option == winningDoor)
{
printf("You Won!\n");
wins++;
}
else if (option == remainingDoor)
{
printf("YOU LOSE!\n");
}
games++;
}
frequency = ((float) wins / games) *100;
printf ("The number of games that you won is %d\n", wins);
printf ("The frequency of winning is %.0f%%\n", frequency);
return 0;
}
Another more efficient way would be to use fgets or to have error checks on scanf() itself
srand and rand belongs to stdlib header file
#include<stdlib.h> // include this header file
option != hostDoor; // this statement does not do anything
and your else if (option == remainingDoor) should be else { printf("you lose");}

Resources