Continue loop not working correctly - c

I have two continue loops in the below program- each time when a user enters 'X' or 'x', the program is supposed to again ask the user for input, ie the program is supposed to keep working normally. However, in my program, on entering X/x, it terminates.
I would really appreciate any suggestions as to why this is happening!
#include<stdio.h>
int main(int argc, char const *argv[])
{
char card_name[3];
int count = 0;
while (card_name[0] != 'X')
{
printf("\n Enter the card name\n");
scanf("%2s", card_name);
int val = 0;
switch (card_name[0])
{
case 'K':
case 'Q':
case 'J': val = 10;
break;
case 'A': val = 11;
break;
case 'x':
case 'X':
printf("\n Game ended, thanks for playing!!!\n");
printf("\n New Game begins!!!\n");
continue;
default: val = atoi(card_name);
//break;
if ((val < 1) || (val > 10))
{
printf("\n Incorrect card name entered! Please try again!\n");
continue;
}
}
printf("\n The current card value is:%i\n", val);
//Card counting
if ((val > 2) && (val < 7))
{
count++;
printf("\n The count has gone up\n");
}
else if (val == 10)
{
count--;
printf("\n The count has gone down\n");
}
printf("\n The current card count is %i\n", count );
}
/* code */
return 0;
}

If you enter an uppercase X, your continue goes back to the loop condition;
while(card_name[0]!='X')
...where the value is X and it promptly exits.

Change:
case 'x':
case 'X':
printf("\n Game ended, thanks for playing!!!\n");
printf("\n New Game begins!!!\n");
continue;
to:
case 'x':
case 'X':
printf("\n Game ended, thanks for playing!!!\n");
printf("\n New Game begins!!!\n");
*card_name = '\0';
continue;

Related

When the main() function is called back the program is terminated. Is there a way I can fix this?

I have to write a c program to manage the reservations. When I call back the main function the program gets terminated without continuing. How can I fix this error? ( I haven't written the whole program)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int i, j, day, x;
char session[10];
int array[2][5] = {{0,0,1,0,1},{1,1,0,0,0}};
char response,ans,choice;
printf("**************** WELCOME TO NAT RESERVATION SYSTEM ****************");
printf("\n\nCHOOSE WHAT TO DO");
printf("\n\n\t\tA.\t\tBOOK THE THEATER");
printf("\n\t\tB.\t\tCHECK RESERRVATIONS");
printf("\n\t\tC.\t\tREMOVE RESERVATIONS");
printf("\n\t\tD.\t\tCALCULATE INCOME");
printf("\n\t\tE.\t\tEXIT");
printf("\n\nYOUR RESPONSE\t\t: ");
scanf("%c",&response);
switch (response){
case 'A': printf("\n\nBOOK THE THEATER"); break;
case 'B': printf("\n\nCHECK RESERRVATIONS"); break;
case 'C': printf("\n\nREMOVE RESERVATIONS"); break;
case 'D': printf("\n\nCALCULATE INCOME"); break;
case 'E': printf("\n\nEXIT"); break;
}
if (response == 'A'){
printf("\n\nCHOOSE A DAY : ");
scanf("%d",&day);
j = day -1;
printf("YOUR SESSION : ");
scanf("%c",session);
fgets(session,10,stdin);
if(strcmp(session,"MORNING")){
i = 0;
}else if(strcmp(session,"AFTERNOON")){
i = 1;
}else{
printf("PLEASE ENTER MORNING OR AFTERNOON");
}
if(array[i][j] == 0){
printf("\n\nTHE SESSION IS AVAILABLE.\nDO YOU WANT TO CONFIRM THE BOOKING?(Y/N) : ");
scanf("%c",&ans);
I want to direct the program to print the main menu. So I called back the main() function here.
if(ans == 'Y' || ans == 'y'){
array[i][j] = 1;
printf("\nYOUR BOOKING WAS SUCCESSFUL!\n\n");
main();
}
}else if(array[i][j] == 1){
printf("\n\nTHE SESSION IS NOT AVAILABLE.");
printf("DO YOU WANT TO TRY ANOTHER SESSION?(Y/N): ");
scanf("%c",&ans);
if(ans == 'Y' || ans == 'y'){
main();
}else if(ans == 'N' || ans == 'n'){
printf("THANK YOU! HAVE A NICE DAY!");
exit(0);
}
}
}
}
I tried to use a while loop. I don't know what to put inside the brackets. Please help me. I'm new to C programming as I learned most of them online.
while(1){
printf("**************** WELCOME TO NAT RESERVATION SYSTEM ****************");
printf("\n\nCHOOSE WHAT TO DO");
printf("\n\n\t\tA.\t\tBOOK THE THEATER");
printf("\n\t\tB.\t\tCHECK RESERRVATIONS");
printf("\n\t\tC.\t\tREMOVE RESERVATIONS");
printf("\n\t\tD.\t\tCALCULATE INCOME");
printf("\n\t\tE.\t\tEXIT");
printf("\n\nYOUR RESPONSE\t\t: ");
scanf("%c",&response);
switch (response){
case 'A': printf("\n\nBOOK THE THEATER"); break;
case 'B': printf("\n\nCHECK RESERRVATIONS"); break;
case 'C': printf("\n\nREMOVE RESERVATIONS"); break;
case 'D': printf("\n\nCALCULATE INCOME"); break;
case 'E': printf("\n\nEXIT"); break;
}
if (response == 'A'){
printf("\n\nCHOOSE A DAY : ");
scanf("%d",&day);
j = day -1;
printf("YOUR SESSION : ");
scanf("%c",session);
fgets(session,10,stdin);
if(strcmp(session,"MORNING")){
i = 0;
}else if(strcmp(session,"AFTERNOON")){
i = 1;
}else{
printf("PLEASE ENTER MORNING OR AFTERNOON");
}
if(array[i][j] == 0){
printf("\n\nTHE SESSION IS AVAILABLE.\nDO YOU WANT TO CONFIRM THE BOOKING?(Y/N) : ");
scanf("%c",&ans);
if(ans == 'Y' || ans == 'y'){
array[i][j] = 1;
printf("\nYOUR BOOKING WAS SUCCESSFUL!\n\n");
continue;
main();
}
}
if(array[i][j] == 1){
printf("\n\nTHE SESSION IS NOT AVAILABLE.");
printf("DO YOU WANT TO TRY ANOTHER SESSION?(Y/N): ");
scanf("%c",&ans);
if(ans == 'Y' || ans == 'y'){
continue;
main();
}else if(ans == 'N' || ans == 'n'){
printf("THANK YOU! HAVE A NICE DAY!");
exit(0);
}
}
}
Your original program without while and continue seems to work fine if you use scanf with the format string " %c", that is insert a blank space before the percentage sign. This makes the program skip leading white space. Without the leading space in the format string the newline characters in the input will not be skipped over.
NOTE: It is also better to print a newline at the end of a string. If I choose B, for instance, the program output does not end with a newline so on a non-Windows machine the command prompt (in my case a dollar sign) is displayed on the same line as the output:
CHECK RESERRVATIONS$

Problem with Rock Scissor Paper program in C

I have a problem with my program. I want it to execute a loop that makes the result of the game and increments the score. But for some reason it doesn't make the exiting loop or shows the correct score. Below is the code. What the problem could there be.?
Is the there something wrong with the function calls. I want to execute ask the player if he wants to continue and in the case he wants to play to shwo the new score.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void game_exit(void);
void game_playing(void);
void game_choice_menu();
int algorithm(int *player_choice, int *computer_choice);
int main()
{
system("clear");
printf("\n|==============================|\n| ROCK-SCISSORS-PAPER |\n|==============================|\n");
printf("\n1.Start Playing!\n2.Exit!\n\nWhat you wanna do: (pick 1 or 2): ");
int input;
scanf("%d",&input);
switch (input)
{ case 1:
game_playing();
game_exit();
break;
case 2:
game_exit();
break;
default:
printf("WRONG INPUT!! TRY AGAIN!!!");
game_exit();
break;
}
}
void game_choice_menu(void)
{
static int player,computer;
player =0;
computer = 0;
system("clear");
printf("PLAYER : %d COMPUTER: %d \n", player, computer);
printf("===============================");
printf("\nRock, Scissors or Paper? (1 for Rock, 2 for Scissors and 3 for Paper) ");
int answer;
do{
scanf("%d",&answer);} while (answer<=1 && answer>=3);
int computer_choice = rand()% 3;
int result;
result = algorithm(&answer,&computer_choice);
if (result==0) {
player++;
//system("pause 3");
printf("\n YOU WON!!!\n");}
else {
//system("pause 3");
printf("\n YOU LOSE!!!\n");
computer++;}
}
int algorithm(int *player_choice, int *computer_choice)
{
if ( *player_choice < *computer_choice)
{
if ( (*computer_choice - *player_choice)==2)
return 1;
else if ((*computer_choice - *player_choice)==1)
return 0;
}
else if (*player_choice > *computer_choice)
{
if ((*player_choice - *computer_choice)==2)
return 1;
if ((*player_choice - *computer_choice)==1)
return 0;
}
}
void game_playing(void)
{
for (;;)
{
game_choice_menu();
//printf("\n Want to play again? (Y for yes, N for no)");
//char reply;
//scanf("%c",&reply);
//if (reply == 'y' || reply == 'Y')
// continue;
//else if (reply == 'n' || reply == 'N')
// break;
}
}
void game_exit(void)
{
system("clear");
printf("THANK YOU FOR PLAYING!!!");
printf("\n");
}

Repeat the Program Prompt

The current problem is with the Evaluate another interval (Y/N)? prompt. Let's say I run the program 4 times; in order to end it, it requires me to type N 4 times.
int main() {
int trap, test;
double low, hi;
char repeat, c;
//Gather End Points
do {
printf("Enter endpoints of interval to be integrated (low hi): ");
test = scanf("%lf %lf", &low, &hi);
if (test != 2) {
printf("Error: Improperly formatted input\n");
while((c = getchar()) != '\n' && c != EOF); //Discard extra characters
} else
if (low > hi)
printf("Error: low must be < hi\n");
} while ((test != 2 || low > hi));
//Gather amount of triangles
do {
printf("Enter number of trapezoids to be used: ");
test = scanf("%d", &trap);
if (test != 1) {
printf("Error: Improperly formated input\n");
while((c = getchar()) != '\n' && c != EOF); //Discard extra characters
} else
if (trap < 1)
printf("Error: numT must be >= 1\n");
} while ((trap < 1 || test != 1));
//Output integrate
printf("Using %d trapezoids, integral between %lf and %lf is %lf",
trap, low, hi, integrate(low, hi, trap));
//Prompt user for another time
while (1) {
printf("\nEvaluate another interval (Y/N)? ");
scanf(" %c", &repeat);
switch (repeat) {
case 'Y':
main();
case 'y':
main();
case 'N':
return 0;
case 'n':
return 0;
default:
printf("Error: must enter Y or N");
}
}
return 0;
}
I expect it so that no matter what run of the program I'm on it will close when I type one N.
There are many ways to achieve what you want but calling main recursively is not a good idea.
A pretty simple way to change your program is to add an additional while(1) level. Something like:
int main(void)
{
char repeat;
while(1){ // Outer while to keep the program running
printf("running program\n");
// Put your program here
printf("program done\n");
repeat = '?';
while(repeat != 'y' && repeat != 'Y'){ // Repeat until input is 'Y' or 'y'
printf("\nEvaluate another interval (Y/N)? ");
scanf(" %c", &repeat);
switch (repeat){
case 'Y':
case 'y':
break;
case 'N':
case 'n':
return 0; // Stop if input is 'n' or 'N'
default:
printf("Error: must enter Y or N");
}
}
}
return 0; // This will never be reached
}
Another way (a simpler way, IMO) is to put the code where you ask the user into a function that you call from main. Like:
int continueProg()
{
char repeat = '?';
while(1){
printf("\nEvaluate another interval (Y/N)? ");
scanf(" %c", &repeat);
switch (repeat){
case 'Y':
case 'y':
return 1;;
case 'N':
case 'n':
return 0;
default:
printf("Error: must enter Y or N");
}
}
}
int main(void)
{
do {
printf("running program\n");
// Put your program here
printf("program done\n");
} while(continueProg());
return 0;
}
BTW: Take a look at getchar instead of using scanf
There are multiple problems in your program:
You test the return value of scanf() when reading the user's answer to the prompts, and you clear the pending input correctly, but you do not handle the potential end of file, leading to endless loops.
c must be defined as int to accommodate for all values returned by getchar(): 256 values of type unsigned char and the special value EOF.
You can main() recursively to repeat the program's action requiring multiple N answers. You should instead add an outer loop and exit from it upon a N answer or an end of file condition.
Here is a modified version:
#include <stdio.h>
double integrate(double low, double hi, int trap) {
...
}
int flush_line(void) {
// Consume the pending input and return `'\n`` or `EOF`
int c;
while ((c = getchar()) != EOF && c != '\n')
continue;
return c;
}
int main() {
// Main program loop
for (;;) {
int trap, test;
double low, hi;
char repeat;
//Gather End Points
for (;;) {
printf("Enter endpoints of interval to be integrated (low hi): ");
test = scanf("%lf %lf", &low, &hi);
if (test == EOF)
return 1;
if (test != 2) {
printf("Error: Improperly formatted input\n");
if (flush_line() == EOF)
return 1;
continue; // ask again
}
if (low > hi) {
printf("Error: low must be < hi\n");
continue;
}
break; // input is valid
}
//Gather amount of triangles
for (;;) {
printf("Enter number of trapezoids to be used: ");
test = scanf("%d", &trap);
if (test == EOF)
return 1;
if (test != 1) {
printf("Error: Improperly formated input\n");
if (flush_line() == EOF)
return 1;
continue;
}
if (trap < 1) {
printf("Error: numT must be >= 1\n");
continue;
}
break;
}
//Output integrate
printf("Using %d trapezoids, integral between %lf and %lf is %lf\n",
trap, low, hi, integrate(low, hi, trap));
//Prompt user for another time
for (;;) {
printf("\nEvaluate another interval (Y/N)? ");
if (scanf(" %c", &repeat) != 1)
return 1; // unexpected end of file
switch (repeat) {
case 'Y':
case 'y':
break;
case 'N':
case 'n':
return 0;
default:
printf("Error: must enter Y or N\n");
if (flush_line() == EOF)
return 1;
continue;
}
break;
}
}
}

How to turn integers into string in c programming? (eg. 0 => zero)

How to turn integers into string in c programming? (eg. 0 => zero)
Code Example:
https://onlinegdb.com/BygYM1L9V
#include <stdio.h>
#include <stdbool.h>
int main(int argc, const char * argv[]) {
int input, number, right_digit;
bool isNegative = false;
printf("Insert a number:\n ");
scanf("%d", &input);
// if keyed-in number is negative, make it positive, but remember it was negative
if ( input < 0 ) {
input = input;
isNegative = true;
}
if (isNegative == true){
printf("negative ");
}
number = 0;
// reversing the digits of input and store in number
while ( input ) {
// adds the last digit of input to value from right
number = 10 * number + input % 10;
input /= 10;
}
do {
right_digit = number % 10;
switch (right_digit) {
case 0:
printf("zero ");
break;
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
}
number = number / 10;
} while (number != 0 );
printf("\n");
return 0;
}
Expected result for entering 1230 is one two three zero.
However, this code provides 123 and omits the 0. How do I turn integers into strings?
However, is there a better way of doing it? Is there any other method? C coders, please help
I'd drop the switch for a look-up table. Regarding numbers having to be parsed with % operator "backwards" from ls digit and up, simply store them digit by digit in a separate temporary array to easily re-order them.
void stringify (unsigned int n)
{
const char* LOOKUP_TABLE [10] =
{
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
};
if(n == 0)
{
puts(LOOKUP_TABLE[0]);
return ;
}
int numbers[10]={0}; // assuming UINT_MAX = 4.29 billion = 10 digits
for(int i=0; i<10; i++)
{
numbers[10-i-1] = n%10;
n/=10;
}
bool remove_zeroes = true;
for(int i=0; i<10; i++)
{
if(!remove_zeroes || numbers[i]!=0)
{
remove_zeroes = false;
printf("%s ", LOOKUP_TABLE[numbers[i]]);
}
}
}
Out of your problem a typo in your code : input = input; must be input = -input;
It is easier to work on the number as a string, example :
#include <stdio.h>
int main() {
printf("Insert a number:\n ");
char s[32];
if (fscanf(stdin, "%31s", s) != 1) {
return -1;
}
char * p = s;
if (*p == '-') {
printf("negative ");
p += 1;
}
for (;;) {
switch (*p++) {
case 0:
case '\n':
if ((*s == '-') && (p == (s+2))) {
puts("missing number");
return -1;
}
putchar('\n');
return 0;
case '0':
printf("zero ");
break;
case '1':
printf("one ");
break;
case '2':
printf("two ");
break;
case '3':
printf("three ");
break;
case '4':
printf("four ");
break;
case '5':
printf("five ");
break;
case '6':
printf("six ");
break;
case '7':
printf("seven ");
break;
case '8':
printf("eight ");
break;
case '9':
printf("nine ");
break;
default:
puts(" invalid number");
return -1;
}
}
}
Compilation and executions :
/tmp % gcc -pedantic -Wall -Wextra n.c
vxl15036 /tmp % ./a.out
Insert a number:
0
zero
vxl15036 /tmp % ./a.out
Insert a number:
-1
negative one
vxl15036 /tmp % ./a.out
Insert a number:
12305
one two three zero five
vxl15036 /tmp % ./a.out
Insert a number:
007
zero zero seven
vxl15036 /tmp % ./a.out
Insert a number:
-
negative missing number
vxl15036 /tmp % ./a.out
Insert a number:
a
invalid number
As you see the number is rewritten as it was enter, 0 at left are not removed and -0 is negative zero
It can be fun to write one thousand two hundred thirty four for 1234 ;-)
I made a small change to your program so that it loops through once before to get the number of digits, and then loops through count times for the switch statement.
#include <stdio.h>
#include <stdbool.h>
int main(int argc, const char * argv[]) {
int input, number, right_digit;
bool isNegative = false;
printf("Insert a number:\n ");
scanf("%d", &input);
// if keyed-in number is negative, make it positive, but remember it was negative
if ( input < 0 ) {
input = -input;
isNegative = true;
}
if (isNegative == true){
printf("negative ");
}
int count = 0;
int n = input;
//count the digits
while(n != 0)
{
n /= 10;
++count;
}
number = 0;
// reversing the digits of input and store in number
while ( input ) {
// adds the last digit of input to value from right
number = 10 * number + input % 10;
input /= 10;
}
for(int i = 0; i < count; i++) {
right_digit = number % 10;
switch (right_digit) {
case 0:
printf("zero ");
break;
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
}
number = number / 10;
}
printf("\n");
return 0;
}
I think you use similar logic as this example integrated into your loop, but when you reverse the number the 0's get treated like leading 0's and are ignored. I didn't make any changes to the inside of the loop so that may need to be cleaned up.
test input:
12345000
output:
one two three four five zero zero zero

C programming do while with switch case program

I have been able to do switch case program but I want program to run again and again until a user selects to quit.
I basically wants program to run again and again using do while loop...
switch(I)
{
case 1:
printf("67");
break;
case 2:
printf("45");
break;
default:
printf("default");
}
Use a do...while loop like this:
int I = 1; //Initialize to some non-zero number to prevent UB
printf("Enter 0 to quit \n");
do{
if (scanf("%d",&I) != 1) //If invalid data such as characters are inputted
{
scanf("%*[^\n]");
scanf("%*c"); //Clear the stdin
}
} while(I!=0); //Loop until `I` is not 0
This piece of code will loop until the user enters 0. You can change this code according to your needs. If you want your switch in this, copy your posted code after the scanf.
The loop will run until you enter -1 as input.
#include<stdio.h>
int main()
{
int I;
do
{
puts("Enter -1 to quit");
printf("Enter your choice: ");
scanf("%d",&I);
switch(I)
{
case 1:
printf("67\n");
break;
case 2:
printf("45\n");
break;
case -1:
puts("Bye");
break;
default:
printf("default\n");
}
}while(I != -1);
return 0;
}
this program runs untill user gives input 0 or a negative number...
#include<stdio.h>
int main()
{
int I;
do
{
scanf("%d",&I);
switch(I)
{
case 1:
printf("67");
break;
case 2:
printf("45");
break;
default:
printf("default");
}
}
while(I>0);
return 0;
}
Simple Use of Do-While Loop.
Choice is the variable in which user's choice will be stored, whether he wants to print the statement again or not.
int choice;
do{
printf("\nHello World!"); //This is the task of the program (Replace it with your task)
printf("\nDo You Want to Print it again ? 1 Yes/0 No: ");
scanf("%d",&choice);
}while(choice==1); //Loop will exit when choice gets value other than 1
// here switch will run until A is not equal to S
int N;
char A;
do{
cin>>N;
N = N%7;
cout<<endl;
cin>>A;
switch(N)
{
case 1: cout<<"Monday"<<endl; break;
case 2: cout<<"Tuesday"<<endl; break;
case 3: cout<<"Wednesday"<<endl; break;
case 4: cout<<"Thursday"<<endl; break;
case 5: cout<<"Friday"<<endl; break;
case 6: cout<<"Saturaday"<<endl; break;
case 0: cout<<"Sunday"<<endl; break;
default: cout<<"Invalid Input"; }}
while(A!='S');

Resources