C Exercise 31
100 Classic C Language Examples
**Problem:** Enter the first letter of a day of the week to determine which day it is. If the first letter is the same for multiple days, continue by checking the second letter.
**Program Analysis:** It is better to use a switch statement. If the first letter is the same, use a switch statement or an if statement to check the second letter.
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
//
#include
<
stdio.h
int
main
(
)
{
char
i
,
j;
printf
(
"
Please enter the first letter:
\
n
"
)
;
scanf
(
"
%c
"
,&
i
)
;
getchar
(
)
;
// The issue with scanf("%c",&j); is that the second time it reads a newline character instead of the input character, so you need to add a getchar() to consume the newline
switch
(
i
)
{
case
'
m
':
printf
(
"
monday
\
n
"
)
;
break
;
case
'
w
':
printf
(
"
wednesday
\
n
"
)
;
break
;
case
'
f
':
printf
(
"
friday
\
n
"
)
;
break
;
case
'
t
':
printf
(
"
Please enter the next letter
\
n
"
)
;
scanf
(
"
%c
"
,&
j
)
;
if
(
j
=='
u
'
)
{
printf
(
"
tuesday
\
n
"
)
;
break
;
}
if
(
j
=='
h
'
)
{
printf
(
"
thursday
\
n
"
)
;
break
;
}
case
'
s
':
printf
(
"
Please enter the next letter
\
n
"
)
;
scanf
(
"
%c
"
,&
j
)
;
if
(
j
=='
a
'
)
{
printf
(
"
saturday
\
n
"
)
;
break
;
}
if
(
j
=='
u
'
)
{
printf
(
"
sunday
\
n
"
)
;
break
;
}
default
:
printf
(
"
error
\
n
"
)
;
break
;
}
return
0
;
}
The output of the above example is:
Please enter the first letter:
s
请输入下一个字母
a
saturday