Home Segments Index Top Previous Next

158: Mainline

Suppose, for example, that you want to write a program that displays a message that depends on a stock's price–earnings ratio. Specifically, if the stock's price divided by the previous year's per-share profit is greater than 30, you want your program to display It is expensive!; if the price–earnings ratio is less than 10, you want your program to display It is cheap!.

Further suppose that you are able to assign the price–earnings ratio to a variable named ratio, using the read function, scanf.

One solution is to write a program that uses an if statement in which the embedded statements are display statements:

#include  
main ( ) { 
  int ratio; 
  scanf ("%i", &ratio); 
  if (ratio < 10) printf ("It is cheap!\n"); 
  if (ratio > 30) printf ("It is expensive!\n"); 
} 
--- Data ---
35 
--- Result --- 
It is expensive!