Learn C if ..else ! Nested if ..else Statement

C if else Statement !


The if else statement is an extension of the simple If Statement .The general form is if the test expression is true ,then the true -block statement (s), immediately following the if statements are execute ;otherwise ,the false -block statement (s) are execute .In either case ,either true-block or false -block will be execute ,not both ,In the both cases,the control is transferred subsequently .

Syntax of if- else :

if (test-expression )
{
  // body of if
}
else
{
  // body of else
}

Example : C if else statement 

Code:

//check the number entered by user is odd or even number :
#include<stdio.h>
void main ()
{
    int  num ;
    printf("Enter a Number:");
    scanf ("%d",&num);
    if (num %2==0)
    {
        printf("%d is even number:",num);
    }
    else
    {
         printf("%d is odd number:",num);
    }

}

Output :

Enter a Number: 44
44 is even number.

When user entered  44 the test expression  (num %2==0) is evaluated to true . Hence, the statement inside the body of if statement   printf("%d is even number:",num); is executed and the statement inside the body of else is skipped.


Nested If Else Statement {if--else if --else Statement }


When a series if decisions are involved we may have ti use more then one if..else statement is nested form.
The nested if..else statement allows you to check for multiple test expressions and execute different codes for more than two conditions.

Syntax of nested if ...else Statement !

if (test condition 1)
{
//statement  to be executed if test condition 1 is true
}
else if(test condition 2)
{
// statement to be execute  if test  condition 1 is false test condition is true.
}
 else
{
// statement to be execute  if all test condition is false .
}

Example : C Nested if ...else Statement 

Code:

// Program to relate two int number  using =, > or <
#include <stdio.h>
void main()
{
    int fast, second ;
    printf("Enter two number: ");
    scanf("%d %d", &fast,&second);
    //checks if two number  are equal.
    if(fast == second)
    {
        printf("Output: %d = %d",fast,second);
    }
    //checks if fast is greater than second .
    else if (fast>second)
    {
        printf("Output: %d >%d", fast, second);
    }
    // if both test expression is false
    else
    {
        printf("output: %d < %d",fast, second);
    }
}

Output:

Enter two number:44
 44
Output:  44=44 

Thanks For Watching .



*

Post a Comment (0)
Previous Post Next Post