in switch case if I give option as 'aa' it prints a+b instead of it does not print default condition.why it accepting 'aa' as option?
#include <stdio.h>
int main() {
int a=10,b=20;
char ch;
scanf("%c",&ch);
switch(ch) {
case 'a':
printf("%d",a+b);
break;
case 'b':
printf("%d",a*b);
default:
printf("thank u");
}
}
Char is represented in memory with 1 byte. If you want an string, like 'aaa', in memory we have 3 characters with one byte => 3 * 1 = 3 bytes. We represent this with an array. Like char string[200], here we have char * 200.
When you try to read 'aaa' from stdin in char, you read first character from stdin, because you don't allocate memory for all characters.
Try to print in stdout 'ch'. After you put scanf("%c", &ch), put printf("%c", ch); and will print first character from stdin.
#include <stdio.h>
int main() {
int a=10,b=20;
char ch; // One character
scanf("%c",&ch); // Read one character, if we read 'aaa', ch is equal with 'a' beacause we read first one character from stdin.
switch(ch) { //here ch is equal with one character.
case 'a':
printf("%d",a+b);
break;
case 'b':
printf("%d",a*b);
default:
printf("thank u");
}
}