Control statements

Control Statements

πŸ‘‰ Simple if
πŸ‘‰ If_else
πŸ‘‰ Else if ladder
πŸ‘‰ Switch  (multi statement)


Simple If :
  1. It checks whether the given expression is  boolen or not .
2.  If the condition is true it executes the statement,if false jumps to next instruction.
 
Syntex ;      
                      
If(condition)
{
  Statement 1;
}
  Statement 2;


    Eg:      // Program to display a number if it is negative

#include <stdio.h>
int main() {
    int number;

    printf("Enter an integer: ");
    scanf("%d", &number);

    // true if number is less than 0
    if (number < 0) {
        printf("You entered %d.\n", number);
    }

    printf("The if statement is easy.");

    return 0;
}

Output :
 
Enter an integer: -2
You entered -2
The if statement is easy

Note :  " ; " Shouldn't use after the condition " If(condition)" _ if(condition); ❌

If else : 
         1. If condition is true statement 1is executed.
         2.Else statement 2 is executed.     
Syntex:
If(condition)
{
Statement 1;
}
else
{
Statement 2;
}   

Eg:
        To find greatest number between two
Void main( )
int a,b;
Printf("enter any two numbers\n");
Scanf("%d%d",&a,&b);
If (a>b)
{
Printf(" a is greater ");
}
else
{
Printf(" b is greater);

}

Out put :
enter any two numbers - 2,3
3 is greater.
 
Note :  we can't create condition under else part.

Else if  ladder ;  
Syntax 
 
If(condition)
{
Statement 1;
}
else if(condition)
{
Statement 2;
}
else if 
{
Statement n;
}

 Eg ;
             To find relation between two values

Void main ( )
{
int a,b;
Printf ("enter any two numbers\n");
Scanf("%d%d,&a,&b);

If (a==b)
{
Printf("both are equal \n");
}
else if(a>b)
{
  Printf ("a greater than b");
}
else if (a<b)
{
Printf("b greater than a");
}

Output : 
      enter any two numbers -  5,10
      10 is greater than 5

Switch statement (multi statement) ;

Why switch πŸ€”πŸ€”

  1.Incase no match is found in if else ladder.
  2.As no. Of alternatives increases complexity of the program increases to avoid this we use multi decision statements are used.

Syntax 
 
Switch(condition/expression/value)
{
Case 1: statement 1;
              break ;
Case 2: statement 2;
                break;
Case 3: statement 3;
               break;
Case n: statement n;
                break;
Default : statement ;
                   break ;


Eg ;

Void main ( )
{
Int n ;
Printf ("enter the n value");
Scanf("%d",&n);
Switch (n)
Case 1:printf("Sunday "); break;
Case 2: printf (" Monday"); break ;
Case 3: printf("Tuesday ");break;
Case 4: printf(" Wednesday "); break;
Case 5: printf(" Thursday ");break;
Case 6 :printf(" Friday ");break;
Case 7:printf(" Saturday ");break;
Default: printf(" Enter number in between 1 to 7"); break;
}
  
Output : enter the n value  -   6 
                Friday


Note ; 1 .  ": " Is used after condition not ";"  -                           case 5: .
              2. Break statement is optional.


Comments