C - if else statement

Introduction

The syntax of the if-else statement is as follows:

if(expression)
  Statement1;
else
  Statement2;

Next_statement;

You'll always execute either Statement1 or Statement2 depending on whether expression results in the value true or false:

If expression evaluates to true, Statement1 is executed and the program continues with Next_statement.

If expression evaluates to false, Statement2 that follows the else keyword is executed, and the program continues with Next_statement.

The following code uses if statements to decide on a discount.

Demo

#include <stdio.h>

int main(void)
{
      const double unit_price = 3.50;                     // Unit price in dollars
      int quantity = 0;
      printf("Enter the number that you want to buy:");   // Prompt message
      scanf(" %d", &quantity);                            // Read the input

      // Test for order quantity qualifying for a discount
      double total = 0.0;                                 // Total price
      if(quantity > 10)                                   // 5% discount
        total = quantity*unit_price*0.95;
      else                                                // No discount
        total = quantity*unit_price;//from ww w.  jav  a  2s  .  c  om
      printf("The price for %d is $%.2f\n", quantity, total);
      return 0;
}

Result

how It Works

if-else statement does all the work:

double total = 0.0;                                  // Total price
if(quantity > 10)                                    // 5% discount
      total = quantity*unit_price*0.95;
else                                                 // No discount
total = quantity*unit_price;

the total price will be stored in the variable total.

if quantity is greater than 10, the first assignment statement will be executed, which applies a 5 percent discount.

otherwise, the second assignment will be executed, which applies no discount to the price.

the result of the calculation is output by the printf() statement:

printf("The price for %d is $%.2f\n", quantity, total);

%d specifier applies to quantity because it is an integer of type int.

%.2f specifier applies to the floating-point variable, total, and outputs the value with two digits after the decimal point.

Related Topic