So my professor asked us to create a switch statement. We are allowed to use only the "SWITCH" statement to do the program. He wants us to input a number and then display it if it is on the number range and what briefcase number will be taken as shown below. Now... I know that for this type of program it is easier to use the IF statement. Doing Case 1: Case 2: Case 3...Case 30 will work but will take too much time due to the number range.
#include <stdio.h>
main()
{
int x;
char ch1;
printf("Enter a number: ");
scanf("%d",&x);
switch(x)
{
case 1://for the first case #1-30
case 30:
printf("The number you entered is >= 1 and <= 30");
printf("\nTake Briefcase Number 1");
break;
case 31://for the second case #31-59
case 59:
printf("The number you entered is >= 31 and <= 59");
printf("\nTake Briefcase Number 2");
break;
case 60://for the third case #60-89
case 89:
printf("The number you entered is >= 60 and <= 89");
printf("\nTake Briefcase Number 3");
break;
case 90://for the fourth case #90-100
case 100:
printf("The number you entered is >= 90 and <= 100");
printf("\nTake Briefcase Number 4");
break;
default:
printf("Not in the number range");
break;
}
getch();
}
My professor told us that there is a shorter way on how to do this but won't tell us how. The only way I can think of shortening it is by using IF but we are not allowed to. Any Ideas on how I can make this work out?
With GCC and Clang, you can use case ranges, like this:
switch (x){
case 1 ... 30:
printf ("The number you entered is >= 1 and <= 30\n");
break;
}
The only cross-compiler solution is to use case statements like this:
switch (x){
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
printf ("The number you entered is >= 1 and <= 6\n");
break;
}
Edit: Using something to the effect of switch (x / 10) is another good way of doing this. It may be simpler to use GCC case ranges when the ranges aren't differences of 10, but on the other hand your professor might not take a GCC extension as an answer.
If the ranges are consistent, then you can throw away some of the data:
switch (x / 10 )
{
case 0:
case 1:
case 2: // x is 0 - 29
break ;
// etc ...
}
Otherwise you'll have to do a little bit of hackery around the edges.
Try this ...
#include <stdio.h>
main()
{
int x;
char ch1;
printf("Enter a number: ");
scanf("%d",&x);
int y=ceil(x/30.0);
switch(y)
{
case 1:
printf("The number you entered is >= 1 and <= 30");
printf("\nTake Briefcase Number 1");
break;
case 2:
printf("The number you entered is >= 31 and <= 60");
printf("\nTake Briefcase Number 2");
break;
case 3:
printf("The number you entered is >= 61 and <= 90");
printf("\nTake Briefcase Number 3");
break;
case 4:
printf("The number you entered is >= 91 and <= 100");
printf("\nTake Briefcase Number 4");
break;
default:
printf("Not in the number range");
break;
}
getch();
}
Related
I am trying to make a calculator for resistor. So the input is a value in Ohms and the output will be the color band of the resistor.
But I've been stuck in this for a while, I'm not sure what is happening. No matter what, the code always go to the default situation.
char a, b, c;
int tolerancia,valor;
printf("enter resistance value: ");
scanf("%i", &valor);
c = valor % 10; // th
b = (valor % 100) / 10; // second digit
a = valor / 100; // first digit
switch (a) //colour band for first digit//
{
case '0':
printf("black ");
break;
case '1':
printf("brown ");
break;
case '2':
printf("red ");
break;
case '3':
printf("orange ");
break;
case '4':
printf("yellow ");
break;
case '5':
printf("green ");
break;
case '6':
printf("blue ");
break;
case '7':
printf("violet ");
break;
case '8':
printf("grey ");
break;
case '9':
printf("white ");
break;
default:
printf("unknown value ");
}
The switch case goes for 3 times (first digit, second digit and tolerance) and in every situation the output is "unknown value"
You're reading an int, but your switch is comparing the first digit of that int to various characters. Now, char is a numeric type, so this (kind of) works, but the value of '0' does not equal 0 and so on for all digit characters.
Thus you go straight to the default case.
More correctly:
switch (a) {
case 0:
printf("black ");
break;
// etc.
}
You could also simply have an array of strings and use the digit to index it. Making sure of course to validate that a is a valid index.
char *colors[] = {
"black", "brown", "red", "orange", "yellow",
"green", "blue", "violet", "grey", "white"
};
if (a >= 0 && a <= 9) {
printf("%s ", colors[a]);
}
else {
printf("unknown value ");
}
Here %i takes an integer value as integer value with decimal, hexadecimal or octal type. To enter a value in hexadecimal format – value should be provided by preceding “0x” and value in octal format.
But you are taking the Characters ... Instead of the case '1' :
We must write case 1: then it's given correctly.
So this is the code I'm working on. All is good except that I need to match the case with the counter so I can manage to display the desired output "you are in your tens / teens". I tried many different approaches but I couldn't get it right. However, I think the problem is within the condition. Any tips? Note: I'm just a beginner who just started programming in C this semester!
#include <stdio.h>
int main()
{
int YoB, CY, Age;
unsigned int counter = 0;
printf("Please enter your year of birth");
scanf_s("%d", &YoB);
printf("Please enter the current year");
scanf_s("%d", &CY);
Age = CY - YoB;
printf("Entered year of birth %d\n", YoB);
printf("Entered current year %d\n", CY);
printf("You are %d years old\n \n", Age);
if (Age > 18) {
puts("You are an adult\n");
if (Age < 18)
puts("You are a minor\n");
}
if(Age<=100){
while (++counter <= 10);
}
switch (counter) {
case 0:
puts("You are less than 10\n");
break;
case 1:
puts("you are in your tens / teens\n");
break;
case 2:
puts("You are in your twenties\n");
break;
case 3:
puts("You are in your thirties\n");
break;
case 4:
puts("You are in your fourties\n");
break;
case 5:
puts("You are in your fifties\n");
break;
case 6:
puts("You are in your sixties\n");
break;
case 7:
puts("You are in your seventies\n");
break;
case 8:
puts("You are in your eighties\n");
break;
case 9:
puts("You are in your nineties\n");
break;
case 10:
puts("You are a 100+!!\n");
break;
default:
puts("invalid age!");
break;
}
return 0;
}
Answer to your problem
You have a simple logic issue in your "counter-setter-loop" (I don't know how I should call this).
if(Age<=100){
while (++counter <= 10);
}
you're incrementing counter to 11 not 10. Suppose counter is 10, it'll iterate again, since the condition <= 10 is still true. As a result you'd need to change this part to:
if(Age<=100){
while (++counter < 10);
}
Code review
Anyway, when I saw your code, some code improvements went through my head. I hope that's fine for you, if not, you can skip this.
adding \n to printf (little UI improvement)
In my opinion it looks a little bit better, if you create a little prompt and create a new line for the input:
printf("Please enter your year of birth\n>> ");
scanf_s("%d", &YoB);
printf("Please enter the current year\n>> ");
scanf_s("%d", &CY);
Logic issue:
There's a logic issue in this part:
if (Age > 18) {
puts("You are an adult\n");
if (Age < 18)
puts("You are a minor\n");
}
Assuming Age is < 18. I think that you'd expect to have the output You are a minor. But this will never happen because in order to get to the if (Age < 18) condition, you'd need to enter the Age > 18 condition. So I think you mean it like that:
// Also keep in mind that Age can be "< 0" if the user used a "bad" input.
if (Age < 0) {
puts("You are not born yet.");
} else if (Age >= 18) {
puts("You are an adult\n");
} else {
puts("You are a minor\n");
}
Set counter a value instead of using a loop
You can change this part:
if (Age <= 100){
while (++counter <= 10);
}
to this:
if (Age <= 100) {
counter = 10;
}
although I don't really understand how you can enter the other case-arms since counter seems to be only 0 or 10 due to the condition above. I think you rather mean something like this:
if (Age <= 100) {
counter = Age / 10;
}
Also please use variable-names which start with a lowercase and not with a uppercase since uppercase Names are rather used for structs, enums or constants etc.
To sum it up, I'd do it as follows:
#include <stdio.h>
int main()
{
int birth_year, current_year, age;
unsigned int tenths = 0;
printf("Please enter your year of birth\n>> ");
scanf_s("%d", &birth_year);
printf("Please enter the current year\n>> ");
scanf_s("%d", ¤t_year);
age = current_year - birth_year;
printf("Entered year of birth %d\n", birth_year);
printf("Entered current year %d\n", current_year);
printf("You are %d years old\n \n", age);
if (age < 0) {
puts("You aren't born yet.");
} else if (age >= 18) {
puts("You are an adult.\n");
} else {
puts("You are a minor.\n");
}
if(age <= 100){
tenths = age % 10;
}
switch (tenths) {
case 0:
puts("You are less than 10\n");
break;
case 1:
puts("you are in your tens / teens\n");
break;
case 2:
puts("You are in your twenties\n");
break;
case 3:
puts("You are in your thirties\n");
break;
case 4:
puts("You are in your fourties\n");
break;
case 5:
puts("You are in your fifties\n");
break;
case 6:
puts("You are in your sixties\n");
break;
case 7:
puts("You are in your seventies\n");
break;
case 8:
puts("You are in your eighties\n");
break;
case 9:
puts("You are in your nineties\n");
break;
case 10:
puts("You are a 100+!!\n");
break;
default:
puts("invalid age!");
break;
}
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");
}
}
What I am trying to do is to write a program wherein you input two digits and
then they are converted into words which gets printed. The problem is that this program
hangs after you input the two digits and I have no idea why. Any and all help is appreciated.
I am a beginner and all I can use to solve this is basically if and switch. Thanks again.
#include <stdio.h>
int main (void)
{
int firstNum, secondNum;
printf("Enter a two digit number: ");
scanf("%d%d", &firstNum,&secondNum);
if (firstNum == 1 && secondNum == 0){
printf("You entered the number ten\n");}
if (firstNum == 1 && secondNum == 1){
printf("You entered the number eleven\n");}
if (firstNum == 1 && secondNum == 2){
printf("You entered the number twelve\n");}
if (firstNum == 1 && secondNum == 3){
printf("You entered the number thirteen\n");}
if (firstNum == 1 && secondNum == 4){
printf("You entered the number forteen\n");}
if (firstNum == 1 && secondNum == 5){
printf("You entered the number fifteen\n");}
if (firstNum == 1 && secondNum == 6){
printf("You entered the number sixteen\n");}
if (firstNum == 1 && secondNum == 7){
printf("You entered the number seventeen\n");}
if (firstNum == 1 && secondNum == 8){
printf("You entered the number eighteen\n");}
if (firstNum == 1 && secondNum == 9){
printf("You entered the number nineteen\n");}
switch(firstNum){
case 2: printf("You entered the number twenty-");break;
case 3: printf("You entered the number thirty-");break;
case 4: printf("You entered the number forty-");break;
case 5: printf("You entered the number fifty-");break;
case 6: printf("You entered the number sixty-");break;
case 7: printf("You entered the number seventy-");break;
case 8: printf("You entered the number eighty-");break;
case 9: printf("You entered the number ninty-");break;
}
switch (secondNum){
case 1: printf("one.\n");break;
case 2: printf("two.\n");break;
case 3: printf("three.\n");break;
case 4: printf("four.\n");break;
case 5: printf("five.\n");break;
case 6: printf("six.\n");break;
}
return 0;
}
Your program "hangs" because it is waiting for a second number.
Instead of 42ENTER, type 42fooENTER.
You need to verify the return value from scanf()
if (scanf("%d%d", &firstNum, &secondNum) != 2) {
fprintf(stderr, "Oops, the scanf didn't read 2 numbers.\n");
} else {
/* continue with program */
/* you might as well see what scanf got from the input */
printf("scanf got the values %d and %d.\n", firstNum, secondNum);
}
A very simple code (Specially for beginners).
#include <stdio.h>
#include <conio.h>
int main()
{
int num,n,r;
printf("Enter a two-digit number: ");
scanf("%d",&num);
n = num/10;
r = num%10;
switch(n)
{
case 1: switch(r)
{
case 0: printf("Ten");
break;
case 1: printf("Eleven");
break;
case 2: printf("Twelve");
break;
case 3: printf("Thirteen");
break;
case 4: printf("Fourteen");
break;
case 5: printf("Fifteen");
break;
case 6: printf("Sixteen");
break;
case 7: printf("Seventeen");
break;
case 8: printf("Eighteen");
break;
case 9: printf("Nineteen");
}
break;
case 2: printf("Twenty-");
break;
case 3: printf("Thirty-");
break;
case 4: printf("Fourty-");
break;
case 5: printf("Fifty-");
break;
case 6: printf("Sixty-");
break;
case 7: printf("Seventy-");
break;
case 8: printf("Eighty-");
break;
case 9: printf("Ninety-");
break;
}
if(n != 1)
{
switch(r)
{
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: ;
}
}
getch();
}
Your program reads data from the console and the console is in "cooked" mode. In this mode, the console collects the input and allows the user to edit it. Data is sent to the program after you press Return or Enter.
The mode you want is "raw" mode. There are various ways to enter raw mode but that depends on your OS.
The quick fix is to enter the two digits and press Return
I want to create a program that requests from the user 10 grades and then filters them to pass and fail, then prints the number of passes and fails. I did the program but the output is wrong.
int pass,fail,grade,studentcounter;
pass=0;
fail=0;
grade=0;
studentcounter=10;
while (studentcounter!=0)
{
printf("enter the next grade\n");
scanf("%d",grade);
student--;
}
switch (grade)
{
case 1:
if (grade >= 50)
pass++;
break;
case 2:
if (grade <= 49)
fail++;
break;
}
}
printf("the number of fail is %d",fail);
printf("the number of pass is %d",pass);
}
The problem is that the program request the ten grades but at the end it will print the number of fail and the number of pass as zero. Why?
You are entering a grade number. A switch statement tests that grade against the cases, and i am pretty sure the grades are not 1 percent or 2 percent. An if statement would be a more logical choice in this situation.
Second of all, you have a code block which is never used. First you set studentcounter to zero, then you say "only execute this block when studentcounter is NOT zero"...
studentcounter=0;
while (studentcounter!=0) {
printf("enter the next grade\n");
scanf("%d",grade);
student--;
}
The third problem is, you misspelled grade.
you can rewrite your code as follows:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int pass,fail,grade,studentcounter;
pass=0;
fail=0;
grade=0;
studentcounter=0;
while (studentcounter < 10) {
printf("enter the next grade:\n");
scanf("%d",&grade);
if (grade >= 50) {
pass++;
} else {
fail++;
}
studentcounter++;
}
printf("the number of fail is: %d \n",fail);
printf("the number of pass is: %d \n",pass);
return 0;
}
Sorry if I overlooked something; I don't have time to throw it into my editor :P
cheers
you need to keep the count of pass/fails inside the while loop, the grade variable will be overwritten at every input.
edit:
also, dont use a switch statement.
Ok, the code as presented is a pile of crap. I will leave it as an exercise for you to sort out what I fixed for you:
#include <stdio.h>
int main(int argc, char *argv[])
{
int pass = 0;
int fail = 0;
int grade= 0;
int studentcounter;
for (studentcounter=1; studentcounter<=10; studentcounter++ )
{
printf("Enter grade for student #%-2d :", studentcounter);
scanf("%d",&grade);
if(grade >=50)
pass++;
if(grade<=49)
fail++;
}
printf("the number of fail is %d\n",fail);
printf("the number of pass is %d\n",pass);
}
PS. If this is homework, please give credit when you turn it in. You can learn a lot by looking at other people's code, but never claim to create that which you haven't.
hmm, since you have to use swicth i will suggest the following:
Keep a variable which checks whether the grade is more than 50 or not and then use this variable inside switch:
char pass_fail = (grade >= 50)? y : n;
switch( pass_fail )
{
case 'y':
// print pass
break;
case 'n':
// print fail
break;
}
hope this helps you
BTW, there is a solution that uses 'switch' in a reasonable fashion. I won't get into a discussion of the advantages/pitfalls of this approach or the arcaneness of the 'C' language, but just to prove it's possible, here it is:
#include <stdio.h>
int main(void)
{
int pass, fail, grade, answer, studentcounter;
pass = 0;
fail = 0;
grade = 0;
studentcounter = 10;
while ( studentcounter-- )
{
printf("enter the next grade\n");
scanf("%d", &grade);
answer = ( grade > 49 );
switch ( answer )
{
case 1:
pass++;
break;
default:
fail++;
break;
}
}
printf("the number of fail is %d \n", fail);
printf("the number of pass is %d \n", pass);
}
C 'case' statements do not work the way you are expecting.
They operate on 'constant-expressions' which means that in order to accomplish the task you have given, 'Determine if a grade is pass or fail' one would have to write a convoluted switch statement of the form
switch ( grade )
{
case 100:
case 99:
case 98:
case 97:
case 96:
case 95:
case 94:
case 93:
case 92:
case 91:
case 90:
case 89:
case 88:
case 87:
case 86:
case 85:
case 84:
case 83:
case 82:
case 81:
case 80:
case 79:
case 78:
case 77:
case 76:
case 75:
case 74:
case 73:
case 72:
case 71:
case 70:
case 69:
case 68:
case 67:
case 66:
case 65:
case 64:
case 63:
case 62:
case 61:
case 60:
case 59:
case 58:
case 57:
case 56:
case 55:
case 54:
case 53:
case 52:
case 51:
case 50:
pass++;
break;
default:
fail++;
break;
}
This would probably give you the correct answer, however, you may receive a 'fail' on your homework for writing such a monster.
I would try to think of another problem that has 'while, switch and if' statements or perhaps you could modify your current program such that, instead of accepting 10 grades, it prompted the user if they wished to enter another grade and accepted only the answer 'Y', 'y', or 'N', 'n' thus 'switching' on that answer to continue.
2 errors:
1: The while loop should end after the switch statement.
2: Your variable name is "studentcounter" but you are decrementing "student".
Check the following code. This should work.
void main()
{
int pass,fail,grade,studentcounter;
pass=0;
fail=0;
grade=0;
studentcounter=10;
while (studentcounter!=0)
{
printf("enter the next grade\n");
scanf("%d",grade);
studentcounter--;
switch (grade)
{
case 1:
if (grade >= 50)
pass++;
break;
case 2:
if (grade <= 49)
fail++;
break;
}
}
printf("the number of fail is %d",fail);
printf("the number of pass is %d",pass);
}