The if Statement

I l @ ve RuBoard

The if Statement

Let's start with a simple example of an if statement shown in Listing 7.1. This program reads in a list of daily low temperatures (in Celsius) and reports the total number of entries and the percentage that were below freezing. It uses scanf() in a loop to read in the values. Once during each loop cycle, it increments a counter to keep track of the number of entries. An if statement detects temperatures below freezing and keeps track of their number separately.

Listing 7.1 The colddays.c program.
 /* colddays.c -- finds percentage of days below freezing */ #include <stdio.h> #define SCALE "Celsius" #define FREEZING 0 int main(void) {   float temperature;   int cold_days = 0;   int all_days = 0;   printf("Enter the list of daily low temperatures.\n");   printf("Use %s, and enter q to quit.\n", SCALE);   while (scanf("%f", &temperature) == 1)   {        all_days++;        if (temperature < FREEZING)             cold_days++;   }   if (all_days != 0)        printf("%d days total: %.1f%% were below freezing.\n",               all_days, 100.0 * (float) cold_days / all_days);   if (all_days == 0)        printf("No data entered!\n");   return 0; } 

Here is a sample run:

 Enter the list of daily low temperatures. Use Celsius, and enter q to quit.  12 5 -2.5 0 6 8 -3 -10 5 10 q  10 days total: 30.0% were below freezing. 

The while loop test condition uses the return value of scanf() to terminate the loop when scanf() encounters non-numeric input. By using float instead of int for temperature , the program is able to accept input like -2.5 as well as 8 .

The new statement in the while block is this:

 if (temperature < FREEZING) cold_days++; 

This if statement instructs the computer to increase freezing by 1 if the value just read ( temperature ) is less than zero. What happens if temperature is not less than zero? Then the cold_days++; statement is skipped , and the while loop moves on to read the next temperature value.

The program uses the if statement two more times to control the output. If there is data, the program prints the results. If there is no data, the program reports that fact. (Soon you'll see a more elegant way to handle this part of the program.)

To avoid integer division, the example uses the cast to float when the percentage is being calculated. You don't really need the type cast, for in the expression 100.0 * cold_days / all_days , the subexpression 100.0 * cold_days is evaluated first and is forced into floating point by the automatic type conversion rules. Using the type cast documents your intent, however, and protects the program from faulty compilers.

if Basics

The if statement is called a branching statement because it provides a junction where the program has to select which of two paths to follow. The general form is this:

 if (  expression  )  statement  

If expression evaluates to true (nonzero), the statement is executed. Otherwise, it is skipped. As with a while loop, statement can be a single statement or a single block or compound statement. The structure is very similar to that of a while statement. The chief difference is that in an if statement, the test and (possibly) the execution are done just once, but in the while loop, the test and execution can be repeated several times.

Normally, expression is a relational expression; that is, it compares the magnitude of two quantities , as in the expressions x > y and c == 6 . If expression is true ( x is greater than y , or c does equal 6 ), then the statement is executed. Otherwise, the statement is ignored. More generally , any expression can be used, and an expression with a value is taken to be false.

The statement portion can be a simple statement, as in the example, or it can be a compound statement or block, marked off by braces.

 if (score > big)     printf("Jackpot!\n");  /* simple statement   */ if (joe > ron) {                          /* compound statement */     joecash++;     printf("You lose, Ron.\n"); } 

Note that the entire if structure counts as a single statement, even when it uses a compound statement.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net