Beginners switch case action is always default - c

i have just entered a switch case code.. i don't understand why when i am pressing '1', it is still going to the default case always.
#include <stdio.h>
int main() {
char c = 0;
int x = 0, y = 0;
printf("Please write 2 numbers:\n");
scanf("%d %d", &x, &y);
printf("Please choose an action from the math menu:\n\n1.add\n2.sub\n");
scanf(" %c", &c);
switch (c)
{
case 1:
printf("%d + %d is %d\n", x, y, x+y);
break;
default: printf("Wrong value\n");
break;
}
return 0;
}

As c is declared as having character type then entered 1 and 2 are characters correspondingly '1' and '2'.
So write
switch (c)
{
case '1':
printf("%d + %d is %d\n", x, y, x+y);
break;
case '2':
printf("%d - %d is %d\n", x, y, x-y);
break;
default: printf("Wrong value\n");
break;
}

The character 0 to 9 are actually ascii values 48 to 57. switch( (int)(c-48) ) would work. The express (int)(c-48) changes the ascii digits to integers.

An alternative to the previous answer using character literals:
switch(c)
{
case '1':
...
break;
...
}
This allows you to even handle 'q' and the like.
When doing 'q', keep in mind the case sensitivity:
switch(c)
{
case 'q':
case 'Q':
... handle q
break;
}
In short: You are reading a char, treat it as a char.

Related

Why is the default case matched in this switch statement?

I've got a question about switch statements.
Here is my code:
#include<stdio.h>
int main()
{
float a=0.0f;
float b=0.0f;
char operation=0;
printf("Enter expression:");
scanf("%f %c %f",&a,&operation,&b);
switch(operation)
{
case '+':
printf("=%.2f\n",a+b);
break;
case '-':
printf("=%.2f\n",a-b);
break;
case '*':
printf("=%.2f\n",a*b);
break;
case '/':
if(b==0)
printf("\ndivision by zero error.\n");
else
printf("=%.2f\n",a/b);
break;
case '%':
if(b==0)
printf("\ndivision by zero error.\n");
else
printf("=%d\n",(int)a%(int)b);
break;
default:
printf("invalid operation\n");
break;
}
return 0;
}
And this is result about two different input, one right, one wrong.
Why, when I enter two letters instead of two numbers, does it go into the default case?
a+b won't match the format string of your scanf since it expects floats not chars (like a or b), therefore scanf does not do anything.
scanf returns the number of items it was able to read which will be 0 in this case. Checking its return value is not a bad idea.
And since operation is initialized to 0 the default case will execute.
scanf("%f %c %f",&a, &operation, &b);
So, when you enter a+b:
'a' is not a float
scanf fails (you can check this by looking at its return value)
operation is still with its default value which is 0
Inside the switch statement, none of the cases('+', '-', '*', '/', '%') get matched because char operation = 0;
Therefore, the default block is executed.
Because you need to check the return value of scanf
// scanf("%f %c%f", &a, &operation, &b);
if (scanf("%f %c%f", &a, &operation, &b) != 3) {
fprintf(stderr, "Unable to convert input!\n");
exit(EXIT_FAILURE);
}

Variable not Updating, While Loop not working

I am working on an accumulator that asks for different inputs and based on those inputs, updates values in an accumulator. My loop however, doesn't seem to run when I ask for a decimal, hexadecimal, or octal to be inputed. Could someone possibly take a look and give some suggestions to fix it? Thank you! Also Im suppose to somehow use a while loop in my print_menu() function that will check is the input is valid. Any suggestions?
#include <stdio.h>
#include <string.h>
short get_operand(char mode);
void print_acc(short acc);
char print_menu(void);
int main(void);
int main(){
char mode = 'D';
short acc = 8;
char input[10];
char option;
char valid_input[7] = "OHDCSQ";
while (mode != 'Q'){
print_acc(acc);
print_menu();
scanf("%s", &input);
printf("%s\n", input);
option = (char) toupper(input[0]);
switch(option){
case 'O':
mode = 'O';
printf("mode\n");
printf("Mode is Octal\n");
break;
case 'H':
mode = 'H';
printf("Mode is Hexadecimal\n");
break;
case 'D':
mode = 'D';
printf("Mode is Decimal\n");
break;
case 'C':
acc = 0;
break;
case 'S':
get_operand(mode);
if (mode == 'H'){
scanf("%hx", &acc);
printf("%hx", acc);
print_acc(acc);
}
else if (mode == 'O'){
scanf("%ho", &acc);
printf("%ho", acc);
print_acc(acc);
}
else{
scanf("%hd", &acc);
printf("%hd", acc);
print_acc(acc);
}
case 'Q':
mode = 'Q';
printf("\n");
break;
}
//return acc;
}
}
void print_acc(short acc){
printf("\n");
printf("****************************************\n");
printf("* Accumulator: *\n");
printf("* Hex : %04hx *\n", acc);
printf("* Octal : %08ho *\n", acc);
printf("* Decimal : %06hd *\n", acc);
printf("****************************************\n");
}
char print_menu(void){
printf("\n");
printf("Please Select one of the following options:\n");
printf("O Octal Mode\n");
printf("H Hecadecimal Mode\n");
printf("D Decimal Mode\n");
printf("\n");
printf("C Clear Accumulator\n");
printf("S Set Accumulator\n");
printf("\n");
printf("Q Quit\n");
printf("\n");
printf("Option: ");
}
short get_operand(char mode){
switch(mode){
case 'H':
printf("Enter Hex value:");
break;
case 'O':
printf("Enter Octal value:");
break;
default:
printf("Enter decimal value: ");
break;
}
return mode;
}
In the 'S' case where you read in a number, you forget to add a break statement at the end of the case. This results in the code falling through to the Q case which causes the loop to exit.
Add the break and the loop will continue as expected:
case 'S':
...
break;
case 'Q':
...
This is also incorrect:
scanf("%s", &input);
%s expects a char *, but you're passing the address of an array (a char (*)[10] to be presice). Pass in the array directly, which will decay to a pointer to the first element to yield the correct type:
scanf("%s", input);
Also, change print_menu and get_operand to return void, since you're not using the return value and in the former case failing to include one.

why my program is giving garbage value in o/p after providing sufficient inputs? code is as follows:

Why my program is giving garbage value in O/P after providing sufficient inputs?
I have given I/P as 10 & 40 & choose multiplication option as 3.
My code is as follows:
int main()
{
int a,b,c,x;
printf("Enter a & b \n"); //printing
scanf("%d %d, &a,&b");
printf("1. add \n 2. sub \n 3. multiply \n 4. div \n 5. mod \n 6. and \n 7. or\n 8. not \n 9. xor \n");
printf("Enter your choice \n");
scanf("%d, &x");
switch(x)
{
case 1: c=a+b;
break;
case 2: c=a-b;
break;
case 3: c=a*b;
break;
case 4: c=a/b;
break;
case 5: c=a%b;
break;
case 6: c=a && b;
break;
case 7: c=a || b;
break;
case 8: c=~a;
break;
case 9: c=a^b;
break;
default: printf("Make correct choice\n");
}
printf("result is: %d",c);
return 0;
}
You are passing a string to scanf function in line number 5 & 8 and no buckets to hold the scanned/read arguments.
The scanf function's prototype is as follows:
int scanf(const char *format_string, ...);
Where the format_string is string containing format specifiers such as %d, %f...etc
And "..." in prototype means variable number of arguments. The arguments are buckets to hold the values that scanf fills by reading the format_string.
Hence the corrected lines of code should be
line 5. scanf("%d %d", &a,&b);
line 8. scanf("%d", &x);
Another notewothy thing is the variable arguments for scanf are always pointers to objects.
Syntax of scanf function is
scanf(“format string”, argument list);
So for example, change
scanf("%d %d, &a,&b");
scanf("%d, &x");
to
scanf("%d %d", &a,&b);
scanf("%d", &x);
first of all your input nothing to be scan from your console or any other input.
please check scanf() sysntax.
#include<stdio.h>
int main()
{
int a,b,c,x;
printf("Enter a & b \n"); //printing
scanf("%d %d", &a, &b);
printf("1. add \n 2. sub \n 3. multiply \n 4. div \n 5. mod \n 6. and \n 7. or\n 8. not \n 9. xor \n");
printf("Enter your choice \n");
scanf("%d", &x);
switch(x)
{
case 1: c=a+b;
break;
case 2: c=a-b;
break;
case 3: c=a*b;
break;
case 4: c=a/b;
break;
case 5: c=a%b;
break;
case 6: c=a && b;
break;
case 7: c=a || b;
break;
case 8: c=~a;
break;
case 9: c=a^b;
break;
default: printf("Make correct choice\n");
}
printf("result is: %d",c);
return 0;
}

Can't execute Switch statement inside For Loop more than 10 times - C

i'm currently learning C, and i have an exercise, request for 20 characters and show the amount of ('a','e','i','o','u').
I coded this:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
char letter;
int a = 0, e = 0, i = 0, o = 0, u = 0, x;
for(x = 0; x < 20; x++)
{
printf("\nEnter a character: ");
letter = getchar();
letter = tolower(letter);
switch(letter)
{
case 'a':
a += 1;
break;
case 'e':
e += 1;
break;
case 'i':
i += 1;
break;
case 'o':
o += 1;
break;
case 'u':
u += 1;
break;
default:
continue;
}
system("cls");
}
printf("\nAmount of 'a': %d", a);
printf("\nAmount of 'e': %d", e);
printf("\nAmount of 'i': %d", i);
printf("\nAmount of 'o': %d", o);
printf("\nAmount of 'u': %d\n", u);
system("pause");
return 0;
}
But this only can be executed 10 times. Why this happens?
PD. Sorry for my poor english.
As mentioned in the comments, you are processing 20 characters, but half of them are newlines. If you take out your line system("cls") this becomes apparent:
% ./ctest
Enter a character: a
Enter a character:
Enter a character: b
Enter a character:
Enter a character: c
At the first prompt, I typed a<RET> and the first loop iteration (x=0) processed the a but there is still a <RET> waiting in the input buffer. The second loop iteration (x=1) gets the next available character, <RET> and processes it, the the third loop iteration (x=2) prints its prompt and waits for new input.
You can further see how this works by getting it to process 20 characters you are counting. For example, if I provide the input aaaaaeeeeeiiiiiooooo<RET>, which is 21 characters, you can see that the first 20 are processed:
% ./ctest
Enter a character: aaaaaeeeeeiiiiiooooo
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Enter a character:
Amount of 'a': 5
Amount of 'e': 5
Amount of 'i': 5
Amount of 'o': 5
Amount of 'u': 0
To fix this problem you should either read and discard the newline character or use a different method of reading that can ignore the newlines.
You need to ignore newline chars.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
char letter;
int a = 0, e = 0, i = 0, o = 0, u = 0, x;
for (x = 0; x < 20; x++)
{
printf("\nEnter a character: ");
letter = getchar();
letter = tolower(letter);
if (letter == '\n')
{
x--;
system("cls");
continue;
}
if (letter)
{
switch (letter)
{
case 'a':
a += 1;
break;
case 'e':
e += 1;
break;
case 'i':
i += 1;
break;
case 'o':
o += 1;
break;
case 'u':
u += 1;
break;
default:
break;
}
}
system("cls");
}
printf("\nAmount of 'a': %d", a);
printf("\nAmount of 'e': %d", e);
printf("\nAmount of 'i': %d", i);
printf("\nAmount of 'o': %d", o);
printf("\nAmount of 'u': %d\n", u);
system("pause");
return 0;
}
You can use scanf instead of getchar, it will also solve it.

How to have a C program respond to a letter and spit out something else?

I can't seem to get this program to compile.
I keep getting the error:
'Ammonia' undeclared 'Carbon_Monoxide' undeclared
and so on. Am I using the right function with switch?
/*This program will report the content of a compressed-gas cylinder based on the first letter of the cylinder's color.*/
#include <stdio.h>
int main (void)
{
int x;
char o, b, y, g;
int pause;
o = Ammonia;
b = Carbon_Monoxide;
y = Hydrogen;
g = Oxygen;
printf(" Enter a character representing the observed color of the cylinder \n" );
scanf("%d", &x);
switch (x)
{
case 'o': printf("The content is Ammonia\n");
case 'b': printf("The content is Carbon Monoxide\n");
case 'y': printf("The content is Hydrogen\n");
case 'g': printf("The content is Oxygen\n");
default: printf("Character out of range \n");
}
printf("After Switch \n");
printf("Enter new character to continue \n");
scanf("%d", &pause);
return 0;
}
It has nothing to do with your switch statement, but you will probably have to puzzle over the meaning of these four lines:
o = Ammonia;
b = Carbon_Monoxide;
y = Hydrogen;
g = Oxygen;
You don't use the variables thus defined anywhere, and the symbols "Ammonia", "Carbon_Monoxide" and so on are not defined - this is the cause of the error you are seeing.
Since this is homework, I don't want to give you the answer straight, but look at what you're doing with those chars (o, b, y, g) and ask yourself if it makes sense.
Also, on the switch statement, I'm pretty sure you need a break; after each case, else it will print each case's statement
try:
#include <stdio.h>
int main (void)
{
char x;
int pause;
printf(" Enter a character representing the observed color of the cylinder \n" );
scanf("%c", &x);
while(x){
switch (x)
{
case 'o': printf("The content is Ammonia\n"); break;
case 'b': printf("The content is Carbon Monoxide\n"); break;
case 'y': printf("The content is Hydrogen\n"); break;
case 'g': printf("The content is Oxygen\n"); break;
default: printf("Character out of range \n");
}
printf("After Switch \n");
printf("Enter new character to continue \n");
scanf(" %c", &x);
if(x == 'q'){
break;
}
}
return 0;
}

Resources