1

I am a beginner C programmer so my question may sound vague but please bear it with me ;). So I was trying to create a program in which the user enters the subject he has passed in (There are three options : Math, Physics or both) and based on the input the computer prints the prize money on the screen. But when I execute the program it just exits after the first IF STATEMENT, for example if I enter the option BOTH or PHYSICS, The output still shows $5 prize which should be only shown when math is given as the input. Can you guys kindly guide me what mistake I am making? Thanks in advance, Bilal Ahmed.

#include<stdio.h>
int main(int argc, char const *argv[])

{
char Math,Physics,Both,subject;
printf("Please enter the name of the subjects you have passed in...\nOptionA)Math\nOptionB)Physics\nOptionC)Both\n");

scanf("%s", & subject);
if (subject= Math)
{
printf("you will receive $5\n");
}
else if (subject= Physics)
{
printf("you will receive $10\n");
}
else if (subject= Both)
{
printf("you will receive $15\n");
}
return 0
} 
Lodger
  • 15
  • 5
  • `=` is not `==` – KamilCuk Sep 08 '20 at 08:44
  • C doesn't have a string class and `char` is not that (non-existing) string class. From there on, please study the chapters regarding arrays and strings in your C programming book. – Lundin Sep 08 '20 at 08:46
  • Additionally, the = vs == bug, known since the 1970s, is no doubt addressed by that same book. A good book will tell you to enable and read compiler warnings. – Lundin Sep 08 '20 at 08:47

2 Answers2

4

char data type is to store a single character not a string. So as to take input a string you need a character array. You need to understand the difference between handling a single character and a string in C.

char Math,Physics,Both,subject;     // subject needs to be a character array 
printf("Please enter the name of the subjects you have passed in...\nOptionA)Math\nOptionB)Physics\nOptionC)Both\n");

scanf("%s", & subject);   // Also %s doesn't require & operator with character array.
//for character we use %c 

So you need to declare subject as char subject[15]. Leaving space for null terminator.

Second to compare strings you need to use strcmp in C. So an example of comparisons is :-

if(strcmp(subject, "Math") == 0){
    //stuff
}
...
ameyCU
  • 16,489
  • 2
  • 26
  • 41
2

The statement of

(subject= Math)

assigns the value of Math to subject and evaluates to it. If it's truey, then it will enter that branch of the if. You've meant

(subject== Math)

to only compare without assignment, and also don't forget to initialize your variables. Happy coding!

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175