If Else Statement


Description

Just if condition doesn't allows you to do something, when if condition isn't true. To do something on false condition, if else statement comes in use.

If else statement consists of two blocks of statements, where if block is implemented when test expression is true and else block is implemented when test expression is false.

Syntax

if (test expression is true)
{
statement1;
statement2;
}
else
{
statement1;
statement2;
}

Source code

  1. //Finding largest number using if else statement
  2. #include <stdio.h>
  3. #include <conio.h>
  4. void main()
  5. {
  6. int a,b;
  7. clrscr();
  8. printf("Enter the value of a:");
  9. scanf("%d",&a);
  10. printf("Enter the value of b:");
  11. scanf("%d",&b);
  12. if(a>b)
  13. printf("Value of a is greater than b");
  14. else
  15. printf("Value of b is greater than a");
  16. getch();
  17. }

Program working steps

  • First line of the program is the comment, which tells you what the program is all about, 2nd & 3rd lines are preprocessor statments which include definition of functions like printf, scanf, clrscr etc.
  • From void main() function the program execution starts.
  • On 7th line there is declaration of variable a and b with integer data type.
  • Clears the screen clrscr()
  • From 9th to 12th line program takes the input from the user and stores the value in the variable a and b using printf and scanf statements.
  • if(a>b) condition is true it will execute 14th line. If condition is false compiler will check whether there is an else statement or not, as there is a else statement it will execute 16th line statement.
  • In the above example we have used single statement condition body, you can use multiple statement condition body using opening and closing curly brackets.
  • And last is the getch statement which takes the single input character from the keyboard without displaying on the window screen.