Sunday, 11 April 2021

【ICTSEM2】STPM ICT C Programming Examples ( if statement / if else statement / if-else-if statement )



Conditional Structure

if statement

Syntax: if (condition)
              action;


The action is performed if the condition is true; on the other hand the action is ignored.


Example:




#include <stdio.h>
main()
{
  int num;
  printf("Enter a number: ");
  scanf("%d",&num);
  
  if (num>=1)
  printf("%d is a positive number",num);
}

 

Output:

Enter a number: 25
25 is a positive number


if else statement

Syntax: if (condition)
                   true action;
              else
                   false action;


The true action is performed if the condition is true; on the other hand the other action is executed.


 Example:



#include<stdio.h>
main()
{
    int mark;
    printf("Enter mark :\n");
    scanf("%d",&mark);
    if (mark>=50)
    {
        printf("Congratz,you are passed!");
    }
    else
    {
        printf("It's ok,try your best again.");
    }
}

 

Output:

Enter mark :38
It's ok, try your best again.


if-else-if statement

Syntax: if (condition 1)
                   statement 1;
              else
                   if (condition 2)
                      statement 2;
             else
                   if (condition 3)
                       statement 3;
              else  
                     other statement;


An "is...else" structure is placed in another "if...else" structure to test more than one condition.


 Example:



#include<stdio.h>
main()
{
    char response;
    printf("Have u paid water bill?");
    scanf("%c",&response);
    {
          if (response=='y'||response=='Y')
          printf("Thank you.");
          else if (response=='n'||response=='N')
          printf("Please pay immediately.");
        else
        printf("Invalid answer");
    }
}

Output:

Have u paid water bill? No
Please pay immediately.


No comments:

Post a Comment