0

I am trying to execute below program but it give same output, in if else condition. In output I only get Working day only even I give value as sunday.

#include <stdio.h>
int main(void)
{
char day; 
printf("Enter Day name: \n"); 
scanf("%c", &day);

if (day =="sunday"){
    printf("Holiday");
    }
    else{
        printf("Working day.");
    }
return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    `day` is a `char`. It cannot hold several characters and the zero terminator. You can compare it to other characters (`day == 'X'` or `day == '\0'`, ...) not to *strings*. – pmg Jun 13 '22 at 10:09
  • 2
    You need to study strings before using them. C doesn't have a string class. This code should give a fair amount of warnings. – Lundin Jun 13 '22 at 10:11
  • Does this answer your question? [How do I properly compare strings in C?](https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c) – Gerhardh Jun 13 '22 at 10:22
  • You should get used to run your programs in a debugger. As soon as you try to check that `day` really contains `"sunday"` you should see some "surprising" content. And reading your compiler warnings should not be optional. They should also point to some error in your code. – Gerhardh Jun 13 '22 at 10:24

1 Answers1

1

The program is invalid.

To enter a string you need to declare a character array instead of an object of the type char where the entered string will be stored. For example

char day[10];
printf("Enter Day name: \n"); 
scanf("%9s", day);

To compare strings you need to use standard function strcmp declared in the header <string.h>.

#include <string.h>

//...

if ( strcmp( day, "sunday" ) == 0 ){
    printf("Holiday\n");
    }
else{
        printf("Working day.\n");
    }
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335