C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
return 0;
}

Here are two different runs of this program:


Click here to view code image


On a scale of 1 to 10, how happy are you?
5
Better than average, right?
Maybe things will get better soon!
On a scale of 1 to 10, how happy are you?
9
Great for you!
Things are going well for you!

The goal of this program is to demonstrate that if...else statements do not have to be limited to
two choices. Frankly, you can set as many if...else if...else if...else conditions as
you’d like. For example, you could have a custom message for every number between 1 and 10 in
this program. Each test eliminates some of the possibilities. This is why the second test works only
for numbers 5 through 7 , even though the test is for whether the number is greater or equal to 5 ;
numbers 8 and higher were already eliminated with the first if test.


The Absolute Minimum
The goal of this chapter was to show you ways to test data and execute one set of code
or another, depending on the result of that test. You don’t always want the same code to
execute every time someone runs your program because the data is not always the
same. Key concepts from this chapter include:


  • Use relational operators to compare data.

  • Remember that a true relational result produces a 1 , and a false relational result
    produces a 0.

  • Use if to compare data and else to specify what to do if the if test fails.

  • Put braces around the if body of code and around the else body of code. All the
    code in the braces either executes or does not execute, depending on the relational
    comparison.

  • Don’t put a semicolon after if or else. Semicolons go only at the end of each
    statement, inside the body of the if or the else.

Free download pdf