Else if ladder



The if-else ladder is used to test a set of conditions in sequence. If any of the conditional expression in the sequence is evaluates to true, then it will execute the corresponding code block but if all the condition is false then it will execute a default code present in else block, (which is an optional) and exits whole if-else ladder.  

 

Syntax  

if (condition 1) 

{ 

    statement(s) 1; 

} 

else if(condition 2) 

{ 

    statement(s) 2; 

} 

. 

. 

else if (condition n) 

{ 

    statement(s) n; 

} 

else  

{ 

    default statement(s); 

} 

 

Flowchart   

 

Program   

// use input is positive, negative or zero  


#include <stdio.h>
#include <conio.h>
void main()
{
    int a;
    printf("enter a value of a: ");
    scanf("%d", &a);
    if (a > 0)
    {
        printf("number is positive");
    }
    else if (a == 0)
    {
        printf("Number is zero !");
    }
    else
    {
        printf("number is negative");
    }
    getch();
}

Output  

Enter a value of a:  

The number is positive! 

 

QUESTION:- write a c program to choose option from user input and display the message. 


#include <stdio.h> 
#include <conio.h> 
void main() 
    int ch
    printf("[1] Add \n"); 
    printf("[2] Delete \n"); 
    printf("[3] Edit \n"); 
    printf("[4] Exit \n"); 
    printf("Enter a number : "); 
    scanf("%d", &ch); 
    if(ch == 1
    { 

        printf("Add option selected."); 
    } 
    else if(ch == 2
    { 
      printf("Delete option selected."); 
    } 
    else if(ch == 3
    { 
        printf("Edit option selected."); 
    } 
    else if(ch == 4)  
    { 
        printf("Exit option selected."); 
    } 
    else // default statement  

    { 
        printf("Invalid input!"); 
    } 
    getch(); 
}
 

 

      OUTPUT

           [1] Add 

           [2] Delete       

           [3] Edit         

           [4] Exit         

           Enter a number : 1

           Add option selected.


Follow our page for regular updates.

0 Comments