#include <stdio.h>
int main()
{
char cha;
int m=0;
int f=0;
int tot;
while(cha=='m'||cha=='M'||cha=='F'||cha=='f')
{
printf("What is your gender?(m or f):\n");
scanf(" %c",&cha);
switch (cha)
{
case 'm':
case 'M':
printf("\nYou are a male");
++m;
printf("\nPress a to total up");
break;
case 'f':
case 'F':
printf("\nYou are a female");
++f;
printf("\nPress a to total up");
break;
case 'a':
tot=m+f;
printf("\nThe number of male is %d and the number of female is %d",m,f);
printf("\nThe total of male and female is:%d",tot);
break;
}
}
return 0;
}
So i just meddle around with my code trying to put up a program that can sum up the amount of m and f inputted in the program and end up with no output at all.The program just terminated without showing any output.I try to put semicolon at the end of while expression but the while loop end up doesnt even functioning.What's wrong with my code?
you don't give cha a value.
so it doesn't enter the while.
i think this edition is better. and also error handling is so important.
#include <stdio.h>
int main()
{
char cha;
int m=0;
int f=0;
int tot;
bool end = false;
while(end==false)
{
printf("What is your gender?(m or f):\n");
scanf(" %c",&cha);
switch (cha)
{
case 'm':
case 'M':
printf("\nYou are a male");
++m;
printf("\nPress a to total up");
break;
case 'f':
case 'F':
printf("\nYou are a female");
++f;
printf("\nPress a to total up");
break;
case 'a':
tot=m+f;
end = true;
printf("\nThe number of male is %d and the number of female is %d",m,f);
printf("\nThe total of male and female is:%d",tot);
break;
default:
printf("\nEnter valid sex.");
}
}
return 0;
This loop expression:
while(cha=='m'||cha=='M'||cha=='F'||cha=='f')
is evaluated before cha is given a value by the call to scanf(). So basically you get random behavior since cha is not initialized when that line is first reached. There's a very low chance that it holds any of the valid characters, to the loop exits immediately.
Also, please note that scanf() can fail; you should always check its return value.
while condition never gets true
never gets true you should modify this to work according to you although i have modified your code you can have a look of it.
`#include <stdio.h>
int main()
{
char cha;
int m=0;
int f=0;
int tot;
while(cha!='a')
{
printf("What is your gender?(m or f):\n");
scanf(" %c",&cha);
switch (cha)
{
case 'm':
case 'M':
printf("\nYou are a male");
++m;
printf("\nPress a to total up");
break;
case 'f':
case 'F':
printf("\nYou are a female");
++f;
printf("\nPress a to total up");
break;
case 'a':
tot=m+f;
printf("\nThe number of male is %d and the number of female is %d",m,f);
printf("\nThe total of male and female is:%d",tot);
break;
}
}
return 0;
`}
Hi your while loop is never satisfied as cha was never initialized before the while loop. As per your requirement it should be do while loop instead of a while loop. Modify your code like below:-
int main()
{
char cha;
int m=0;
int f=0;
int tot;
do
{
printf("What is your gender?(m or f):\n");
scanf(" %c",&cha);
switch (cha)
{
case 'm':
case 'M':
printf("\nYou are a male");
++m;
printf("\nPress a to total up");
break;
case 'f':
case 'F':
printf("\nYou are a female");
++f;
printf("\nPress a to total up");
break;
case 'a':
tot=m+f;
printf("\nThe number of male is %d and the number of female is %d",m,f);
printf("\nThe total of male and female is:%d",tot);
break;
}
} while(cha=='m'||cha=='M'||cha=='F'||cha=='f');
return 0;
}
Related
I'm fairly new to the C language. Here my question is that the switch case in the function getDiscount(int ch, float total) only reads the default case and execute the code. I can't identify any errors as it runs correctly, but is generating a wrong answer. Here's my complete code. Does my scanf statements take their ASCII values and execute? I just have no idea.
#include<stdio.h>
float getTotalPrice(char type, int qty);
float getDiscount(char mode, float total);
void getGift(float total);
int main(void)
{
int quantity;
float total;
char garment, method;
printf("\nAvailable Garment Types:\n");
printf("Garment Type\tPrice\\u\n");
printf("T-Shirt - 't'\tRs. 1500.00\n");
printf("Frock - 'f'\tRs.3500.00\n");
printf("Skirts - 's'\tRs.2000.00\n");
printf("\nEnter Your Choice: ");
scanf("%c", &garment);
printf("Enter the quantity: ");
scanf("%d", &quantity);
printf("\nAvailable payment methods are:\n");
printf("Cash - 'c'\nCredit Card - 'd'\nOther - 'o'\n");
printf("\nEnter Your Payment Method: ");
scanf("%c", &method);
total = getTotalPrice(garment,quantity);
total = getDiscount(method,total);
getGift(total);
return 0;
}
float getTotalPrice(char type, int qty)
{
float total=0;
switch(type)
{
case 't':
case 'T':
total = 1500*qty;
break;
case 'f':
case 'F':
total = 3500*qty;
break;
case 's':
case 'S':
total = 2000*qty;
break;
default:
printf("\nError: Enter a valid choice\n");
break;
}
return total;
}
float getDiscount(char mode, float total)
{
switch(mode)
{
case 'c':
case 'C':
total = (total - (total*15/100));
break;
case 'd':
case 'D':
total = (total - (total*10/100));
break;
case 'o':
case 'O':
total = (total - (total*5/100));
break;
default:
printf("\nError: Enter a valid payment method\n");
break;
}
return total;
}
void getGift(float total)
{
float gift;
if(total >= 10000)
{
gift = 3000;
}
else if((total >= 5000)&&(total <= 9999))
{
gift = 2000;
}
else if((total < 4999)&&(total > 1))
{
gift = 1000;
}
else
{
printf("\nError: Invalid inputs\n");
}
printf("\nTotal Price = Rs. %.f\n", total);
printf("\nYour gift voucher value = Rs. %.f\n", gift);
}
add whitespace in your scanf here scanf("%c", &method); so it will become scanf(" %c", &method);
why is this happeneing? you always enter the getdiscount function with the enter of the previous scanf() and that's ruining your input, the whitespace before the %c will ignore that enter and thus let you choose the correct char - c, d,d or o
From the book "Programming in C"
Write a program that takes an integer keyed in from the terminal and extracts and displays each digit of the integer in English. So, if the user types in 932, the program should display
nine three two
Remember to display “zero” if the user types in just a 0.
Its been hours and its still cant be solved.. Do anyone know how to? This is the code so far
#include <stdio.h>
int right_digit,number;
int main ()
{
scanf("%i",&number);
right_digit = number % 10;
switch (right_digit)
{
case '0':
printf("0");
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:
break;
}
number = number / 10;
return 0;
}
The first problem here is, you're (wrongly) trying to use the character representation of the integer numbers. In your code, right_digit is supposed to represent an integer digit, not a character literal.
You must not to use the ''s, just write
case 0:
...
case 1:
and so on.
Just to add a bit on your mistake, it was considering the corresponding integer values of the character literal '0', '1' and so on. For ASCII, they are equivalent to
case 48:
case 49:
.
.
which is not what you intended.
That said,
You need to put the modulo calculation and switch-case inside a loop and carry out the conversion for all the digits of the input integer.
You need to start printing from the beginning (MSB), currently , you're printing from LSB. (Hint: Start printing the result of the modulo operation)
printf("0"); should be printf("Zero ");, as per the requirement.
/*USING SWITCH CASE ...ALSO YOU CAN USE '0' and negative numbers */
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int rem,num,sum=0,rem1,num1,add;
printf("enter the number:\n");
scanf("%i",&num);
if(num<0)
{
printf("minus ");
num=-num;
}
if(num==0)
{
printf("zero");
}
while(num!=0)
{
rem=num%10;
num=num/10;
sum=sum*10 +rem;
}
/*printf("%i\n",sum);*/
while(sum!=0)
{
rem1=sum%10;
sum=sum/10;
switch(rem1)
{
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:
printf("invalid no");
}
}
return 0;
}
Hope this program will help you to understand the logic and I am also posting the solution for same problem using switch case....
/* Write a program that takes an integer keyed in from
* the terminal and extracts and displays each digit of the
* integer in English. So, if the user types in 932, the
* program should display >>> nine three two <<<.
* (Remember to display “zero” if the user types in
* just a 0.)
*/
/*USING IF-ELSE IF*/
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int rem,num,sum=0,rem1;
printf("enter the number:\n");
scanf("%i",&num);
if(num<0)
{
printf("minus ");
num=-num;
}
if(num==0)
{
printf("zero");
}
while(num!=0)
{
rem=num%10;
num=num/10;
sum=sum*10 +rem;
}
/*printf("%i\n",sum);*/
while(sum!=0)
{
rem1=sum%10;
sum=sum/10;
if(rem1==0)
{
printf("zero ");
}
else if(rem1==1)
{
printf("one ");
}
else if(rem1==2)
{
printf("two ");
}
else if(rem1==3)
{
printf("three ");
}
else if(rem1==4)
{
printf("four ");
}
else if(rem1==5)
{
printf("five ");
}
else if(rem1==6)
{
printf("six ");
}
else if(rem1==7)
{
printf("seven ");
}
else if(rem1==8)
{
printf("eight ");
}
else if(rem1==9)
{
printf("nine ");
}
else
{
printf("invalid no");
}
}
return 0;
}
I'm making this program using switch statements that will assign letter grades based on if the user enters numbers 0 - 10. If the user enters a number that is not 0-10, the program outputs an error message and has the user re-enter. However, if the user enters a character the program will loop at the default case. I want it to output the error message from the default case once, and have them re-enter if they enter a character. I'm not sure as to why it loops the default case when a character is entered though.
#include <stdio.h>
int main()
{
int grade;
int r;
while((r = scanf("%i", &grade)) != EOF)
{
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
break;
case 8:
printf("Your grade is a B\n");
break;
case 7:
printf("Your grade is a C\n");
break;
case 6:
printf("Your grade is a D\n");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
break;
default:
printf("Invalid score, please re-enter\n");
}
}
return 0;
}
Try something like:
#include <stdio.h>
int main()
{
int grade;
int r=0;
while(r != 1)
{
scanf("%i", &grade);
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
r=1
break;
case 8:
printf("Your grade is a B\n");
r=1
break;
case 7:
printf("Your grade is a C\n");
r=1
break;
case 6:
printf("Your grade is a D\n");
r=1
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
r=1
break;
default:
printf("Invalid score, please re-enter\n");
break;
}
}
return 0;
}
This will clear the input buffer on an invalid input and allow a retry.
#include <stdio.h>
int main()
{
int grade;
int r;
while((r = scanf("%i", &grade)) != EOF)
{
if ( r != 1) {//r == 1 is successful input of integer
grade = -1;//reset grade on invalid input
}
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
break;
case 8:
printf("Your grade is a B\n");
break;
case 7:
printf("Your grade is a C\n");
break;
case 6:
printf("Your grade is a D\n");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
break;
default:
printf("Invalid score, please re-enter\n");
while ( getchar() != '\n');//clear input buffer
}
}
return 0;
}
The reason your code always loops is because there is no way to exit out of your while other than to kill the program. Remember that break only breaks out of the inner-most switch or loop.
The cleanest way to break out of multiple levels is to use a flag. One way to do what you want is like this:
bool valid_grade = false;
while(!valid_grade && (r = scanf("%i", &grade)) != EOF)
{
valid_grade = true;
switch(grade)
{
case 10:
// unchanged from your code
default:
valid_grade = false;
printf("Invalid score, please re-enter\n");
}
}
Hi i am trying to calculate total price for 6 different items and 3 of them must be selected. by using C i tried use switch statement but unfortunately i stuck after 2 selection.
Thank you
#include<stdio.h>
int main()
{
char ch;
int total=0;
printf("Which cou will you choose:\n");
printf("a) cpu 1 \n");
printf("b) cpu 2 \n");
scanf("%c", &ch);
switch (ch)
{
case 'a':
printf("The price is 110 \n");
total+=110;
break;
case 'b':
printf("The price is 140\n");
total+=140;
break;
default:
printf("Invalid choice.Switching to next question\n");
}
printf("Which ram will you choose:\n");
printf("q) ram 1 \n");
printf("w) ram 2 \n");
scanf("%c", &ch);
switch (ch)
{
case 'q':
printf("The price is 10 \n");
break;
case 'w':
printf("The price is 14\n");
printf("Please Wait\n");
break;
default:
printf("Invalid choice\n");
break;
}
printf("Which hdd will you choose:\n");
printf("x) hdd 1 \n");
printf("y) hdd 2 \n");
scanf("%c", &ch);
switch (ch)
{
case 'x':
printf("The price is 65 \n");
break;
case 'y':
printf("The price is 75\n");
printf("Please Wait\n");
break;
default:
printf("Invalid choice\n");
break;
}
printf("That'll cost %d",total);
return 0;
}
after i add everything once i start program it works only for first switch statement
You need a variable total to add up the total cost. Your code will look like this:
#include<stdio.h>
int main()
{
char ch;
int total=0;
printf("Which option will you choose:\n");
printf("a) cpu 1 \n");
printf("b) cpu 2 \n");
scanf("%c", &ch);
switch (cpu)
{
case 'a':
printf("The price is 110 \n");
total+=110;
break;
case 'b':
printf("The price is 140\n");
total+=140;
break;
default:
printf("Invalid choice.Switching to next question\n");
}
//ask next question.
//get input
//use a switch like the above one
//add total
//repeat this as many times you want
printf("That'll cost %d",total);
return 0;
}
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');