Selasa, 26 November 2013

Conditional If-Else Statement with Example: Turbo C

To overcome the disadvantage of if statement, in computer programming the if-else statement is introduced. It is a two way decision statement which executes either first statement (or block of statements) or second statement (or block of statements) based on the condition.

For the true part if takes care and for the false part else takes care. The syntax of if-else statement along with equivalent flow chart is shown below:

if (condition)
 statement 1 or (block of statement 1)
else
 statement 2 or (block of statement 2)
Conditional If-Else Statement with Example: Turbo C

According to Flowchart, compiler will first check the condition. If the condition is true, the right side of statement(s) will execute otherwise left side of statement(s) will execute. For example 

Program to check whether the number is even or odd: Let num is the given number. After dividing num by 2, if the remainder is zero, then the given number num is even otherwise, given number num is odd. The equivalent statement can be written as:

if (num%2==0)
    Write: “Number is Even”
else
    Write: “Number is odd”
[End of if]

Algorithm:

Step 1: [Read the number to check]
              Read: NUM
Step 2: [Check the number]
              if(NUM%2==0)
                    Write: ‘Number is Even’
              else
           Write: ‘Number is Odd;
    End of if
Step 3:  Exit

The C program to perform the algorithm:

main()
{
   int num;
   printf(“Enter an integer number here:”);
   scanf(“%d”,&num);
   if(num%2==0)
      printf(“The number num %d is EVEN”,num);
   else
      printf(“The number num %d is ODD”,num);
   getch();
}

Nested-If statement

Tidak ada komentar:

Posting Komentar