Title: The If Statement
1The If Statement
2if
- Used to make decisions in a program.
- Used in combination with else to create many
possible actions in a program.
3if
- This example scans in a temperature from the user.
main () float temp scanf (f,temp) if (
temp lt 0.) printf (It is cold!\n)
4if
- If the temperature is less than 0.0
main () float temp scanf (f,temp) if (
temp lt 0.) printf (It is cold!\n)
5if
- then the program will run the stuff inside the
curly braces!
main () float temp scanf (f,temp) if (
temp lt 0.) printf (It is cold!\n)
6if
- In this case, that means it prints It is cold!
main () float temp scanf (f,temp) if (
temp lt 0.) printf (It is cold!\n)
7if
- More complicated actions can happen with the
else statement.
main () float temp scanf (f,temp) if (
temp lt 0.) printf (It is cold!\n) else
printf (Not too bad\n)
8if
- Now if the condition is FALSE
main () float temp scanf (f,temp) if (
temp lt 0.) printf (It is cold!\n) else
printf (Not too bad\n)
9if
- the program will run the code between the curly
braces AFTER the else!
main () float temp scanf (f,temp) if (
temp lt 0.) printf (It is cold!\n) else
printf (Not too bad\n)
10if
- In this case, it will print Not too bad.
main () float temp scanf (f,temp) if (
temp lt 0.) printf (It is cold!\n) else
printf (Not too bad\n)
11if is tricky, too
main () int i,j scanf (d,i) scanf
(d,j) if ( ij) printf (They are the
same!\n)
12if is tricky, too
- is for assigning a value to the variable.
- is for testing a value in the variable.
main () int i,j scanf (d,i) scanf
(d,j) if ( ij) printf (They are the
same!\n)
13if is tricky, too
- In general, floats cannot be equal, so dont test
for that. - Rarely a problem.
main () if (potTemp 298.7) printf
(Will not happen!\n)
14if is tricky, too
main () if (mystation yourstation)
printf (Same station!\n)
15if is tricky, too
- Use !strcmp(string1,string2) for strings
- Means string compare.
main () if (!strcmp(mystation,yourstation))
printf (Same station!\n)
16In Assignment 8
while(!feof(fin)) fscanf(fin,s d d d d
d,station,tempcode,) / DECODE THE
OBSERVATION / tempF ((float) tempcode
)/10.0 blah blah blah / IS THIS THE STATION
REQUESTED BY THE USER? / if (!strcmp(mystation,s
tation) /PRINT OUT THE OBS FOR THE CITY
/