If Else Statement - C Language Tutorial

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


  1. if (test expression is true)
  2. {
  3. statement1;
  4. statement2;
  5. }
  6. else
  7. {
  8. statement1;
  9. statement2;
  10. }





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.


Thank you for sharing Your Knowledge with others who need It.-Team LetML

Post a Comment

Copyright © LetML. Blogger Templates Designed by OddThemes