08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 4 ■ Programs with Selection Logic

Program P4.8

//request a score; print letter grade

#include <stdio.h>

int main() {

int score;

printf("Enter a score: ");

scanf("%d", &score);

printf("\nGrade ");

if (score < 50) printf("F\n");

else if (score < 75) printf("B\n");

else printf("A\n");

}

The second printf prints a blank line followed by the word Grade followed by one space but does

not end the line. When the letter grade is determined, it will be printed on this same line.

We saw that the if...else statement takes the form

if (<condition>) <statement1> else <statement2>

where <statement1> and <statement2> can be any statements. In particular, either one

(or both) can be an if...else statement. This allows us to write so-called nested if statements.

This is especially useful when we have several related conditions to test, as in this example. In the

program, we can think of the part:

if (score < 50) printf("F\n");

else if (score < 75) printf("B\n");

else printf("A\n");

as

if (score < 50) printf("F\n");

else <statement>

where <statement> is this if...else statement:

if (score < 75) printf("B\n");

else printf("A\n");

If score is less than 50, the program prints F and ends. If not, it follows that score must be greater

than or equal to 50.

Knowing this, the first else part checks if score is less than 75. If it is, the program prints B

and ends. If not, it follows that score must be greater than or equal to 75.

Knowing this, the second else part (else printf("A\n"); which matches the second if)

prints A and ends.

84

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!