Why is my IF statement not working? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why is my IF statement not working?

I tried to experiment with the Conditionals example. It compiles okay, and runs, but the IF statement never fires if I guess a number greater than 75. Why? #include <stdio.h> int main() { printf("Enter a number from 1 to 100:"); int score = getchar(); if (score > 75) printf("You passed.\n"); return 0; }

10th Sep 2020, 2:56 PM
Nick
Nick - avatar
5 Answers
+ 4
That's because you are taking input as a character, not as integer. Thus the value is getting stored as it's ASCII value You can check it by printing the value of "score" just after the input to see what is being stored in it.
10th Sep 2020, 3:00 PM
Arsenic
Arsenic - avatar
+ 3
You are using getchar(). This function will treat every input as sequence of characters. When you input 6, it considers it as a character, that is '6', whose ascii value is 6. If you enter 89 (for example), then 8 and 9 will be treated as individual characters, that is '8' & '9', and getchar() takes in account only the first character, that is, it will consider '8' and will ignore '9'. So ultimately you are checking for 8. Hence, your program can only check for values from 0-9. Use scanf() function if you want your program to run correctly. Use the below statement. scanf("%d", &score);
10th Sep 2020, 3:03 PM
Charitra
Charitra - avatar
+ 3
Thank you for all your help. Here is my solution, based on the advice: #include <stdio.h> int main() { char str[100]; int i; printf("Enter a number from 1 to 100:"); scanf("%d", &i); if (i >= 75) printf("You passed.\n"); else printf("This is not the way.\n"); return 0; } Pointers and critique welcome!
10th Sep 2020, 4:04 PM
Nick
Nick - avatar
+ 3
Nick In the first program, you are taking input as single charecter by getchar(). So if you input 75, then only it read 7, as character and on storing to int, it stored its ascii value 55. So 55>=75 false. Input a 'lower case character' to check if working... In second Program works fine but char str[100] you are not using anywhere, so you can remove..
10th Sep 2020, 4:20 PM
Jayakrishna 🇮🇳
+ 1
getchar() reads one character of the input stream. If you enter 99 it will reach the charactet nine and return the ASCII value which is 57. Therefore 57 < 75 yields false. As Charitra Agarwal said, use scanf
10th Sep 2020, 3:06 PM
Arturop
Arturop - avatar