Why my switch case always goes to default case? - c

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.

Related

Program for spelling out integer number digits: (in switch statement) does not match case values, why?

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;
}

Why will my program not flag characters?

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");
}
}

why does "type mismatch in redeclaration of hexadecimal" keep popping up?

I am a totally newbie about C programming. so my program is very long, sorry.
my professor wants to have a number system- binary to decimal, decimal to binary, octal to decimal, hexadecimal to binary. he also want to have a loop( if he wants to exit press [E], if not then press any key). Now i'm having a problem with this hexadecimal because it keeps saying " type mismatch in redeclaration" and i don't know now how to solve this problem.
so heres my not yet finished program because of "hexadecimal" problem. help me with this error. don't mind the octal to decimal, I am currently programming it :)
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define MAX 1000
long num, decimal(long), octal(long), binary(long),j;
char hexadecimal(char), k[MAX];
main()
{
char choice;
clrscr();
printf("[B]inary to Decimal\n");
printf("[D]ecimal to Binary\n");
printf("[O]ctal to Decimal\n");
printf("[H]exadecimal to Binary\n");
printf("[E]xit\n");
printf(" Enter your choice....");
choice=getche();
switch(choice)
{
case 'b':
case 'B': binary(j); break;
case 'd':
case 'D': decimal(num); break;
case 'o':
case 'O':
case 'h':
case 'H': hexadecimal(k[MAX]); break;
case 'e':
case 'E': return 0;
default: printf("\n Invalid choice.... press any key to REPEAT");
getch();
main();
}
printf("\nDo you want to [E]xit?");
choice=getch();
switch(choice)
{
case 'e':
case 'E': printf("\nInvalid choice... press any key to repeat");
getch();
main();
}
getch();
return 0;
}
long binary(long j)
{
long binary_val,decimal_val=0, base=1, rem;
printf("Enter a binary number( 1s & 0s): ");
scanf("%ld",&j);
binary_val=j;
while(j>0)
{
rem=j % 10;
decimal_val=decimal_val + rem * base;
j= j/ 10;
base=base * 2;
}
printf(" The Binary Number is %ld\n",binary_val);
printf(" Its decimal equivalent is = %d\n",decimal_val);
}
long decimal(long num)
{
long decimal_num, remainder, base=1, binary=0;
printf(" \nEnter a decimal integer: ");
scanf("%ld",&num);
decimal_num=num;
while(num>0)
{
remainder= num % 2;
binary=binary + remainder * base;
num=num/2;
base= base * 10;
}
printf(" Input number is %d\n",decimal_num);
printf(" Its binary equivalent is = %ld",binary);
}
char hexadecimal(char k[MAX])
{
long int i=0;
clrscr();
printf(" Enter any Hexadecimal number: ");
scanf("%s",&k);
printf("\n Equivalent binary value: ");
while(k[i])
{
switch(k[i])
{
case '0': printf("0000"); break;
case '1': printf("0001"); break;
case '2': printf("0010"); break;
case '3': printf("0011"); break;
case '4': printf("0100"); break;
case '5': printf("0101"); break;
case '6': printf("0110"); break;
case '7': printf("0111"); break;
case '8': printf("1000"); break;
case '9': printf("1001"); break;
case 'a':
case 'A': printf("1010"); break;
case 'b':
case 'B': printf("1011"); break;
case 'c':
case 'C': printf("1100"); break;
case 'd':
case 'D': printf("1101"); break;
case 'e':
case 'E': printf("1110"); break;
case 'f':
case 'F': printf("1111"); break;
default: printf("\n Invalid hexadecimal digit %c",k[i]); return 0;
}
i++;
}
}
The error you are getting type mismatch in redeclaration of hexadecimalis a result of the difference between the function you prototyped and implemented.
Your prototype is:
char hexadecimal(char), k[MAX];
This line prototypes a function hexadecimal that returns a char and takes a char as an argument AND this line also declares a global char array k of size MAX.
Your actual function is:
char hexadecimal(char k[MAX])
This function is a function that returns a char, but instead of taking a char like your prototype it instead takes a char array of size MAX. As you can see the prototyped function and the function itself are not the same. By making the functions exactly the same you will fix your issue.
To be honest, you don't need to pass anything into that function nor make a global char array as you can locally hold the array based on your code. The only other time you use the array you just pass it to this function which means it is better of as a local to that function anyway. So, you can simply do this:
char hexadecimal(void)
{
char k[MAX]
//same code below...
Now the function takes no arguments and k is still declared in the function, but is local instead of global. The prototype for this function would simply be:
char hexadecimal(void);

C - Switch with multiple case numbers

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();
}

Simple C Program To Convert Two Digits Into Words

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

Resources