if-else statement

View

Sometimes we require executing a set of one or more statements based on TRUEness of some condition and another set of one or more statements based on FALSEness of same condition. In such situation we can use if-else statement.

Syntax- of if-else block

                                    if ( condition )
                                    {
                                                Statements set 1;                    // one or more statements
                                    }
                                    else
                                    {
                                                Statements set 2;                    // one or more statements
                                    }


Here, a condition is specified with if. If the condition is TRUE then statement(s) inside if-block will be executed. If the condition is FALSE, then statement(s) inside else-block will be executed.

 Flowchart-

Example-

A shopkeeper gives discount of 10% if customer makes purchase of rupees 1000 or more. If purchase amount is input through the keyboard, write a program to print discount and Net amount.

 /* Program to display discount and net amount [discount1.c] */
#include < stdio.h >
#include < conio.h >

void main ( )
{
            // Variable Declaration
            float pa, dis, na;
            clrscr ( );
                                                                                                       
            // Input
            printf ( “ \n Enter the Purchase Amount \n “ );
            scanf ( “ %f “, &pa );

            // Processing
            if ( pa > = 1000 )
            {
                        dis = pa * 0.1;
            }
            else
            {
                        dis = 0 ;
            }
            na = pa – dis ;
   
            // Output
            printf ( “ \n Discount = %f “, dis );
            printf ( “ \n Net Amount = %f “, na );
            getch ( );
}

 

Note- Use of curly brackets (parentheses) in if-block and else-block is not compulsory if there is only one statement inside them.


Last modified: Tuesday, 21 September 2021, 9:43 AM