Use of if for counting

Program 15) Write a program to counts the number of boys whose weight is less than 50Kg and height is greater than 170cm.

The program has to least two conditions, one for weight and another for height. This is done using the compound relation
                         if (weight < 50 && height > 170)
This would have been equivalently done using two if statements as follows:
                        if (weight < 50)
                           if (height > 170)
                              count = count +1 ;
If the value of weight is less than 50, then the following statement is executed, which in turn is another if statement. This if statement tests height and if the height is greater than 170, then the count is incremented by 1.

                                  PROGRAM
main( )
 {
        int count, i ;
        float weight, height ;

        count = 0 ;
        printf ("Enter weight and height for 10 boys\n") ;
   
        for (i = 1; i <= 10; i++) 
         {
              scanf ("%f %f", &weight, &height) ;
              if (weight < 50 && height > 170)
                         count = count + 1 ;
         }
        printf ("Number of boys with weight < 50kg\n") ;
        printf ("and height > 170cm = %d\n", count) ;
        getch( ) ;
 }

Output:         Enter weight and height for 10 boys
                      45        176.5
                      55        174.2
                      47        168.0
                      49        170.7
                      54        169.0
                      53        170.5
                      49        167.0
                      47        167
                      51        170
                      Number of boys with weight < 50kg
                      and height > 170cm = 3 

No comments:

Post a Comment