July 10, 2018

Decision Making in C


   In C programs, statements are executed sequentially in the order in which they appear in the program. Sometimes it may happen that the programmer requires to alter the flow of execution, or to perform the same operation for fixed iterations or whenever the condition does not satisfy. 

In such a situation control statements enable us to specify the order in which the various instructions in the program are to be executed. They define how the control is transferred to other parts of the program.



The different types of control statements in C language are:

  1. Decision making statements
    •  if statement
    •  switch statement
  2. Iterative statements
    •  while statement
    •  do...while statement
    •  for statement
  3. Jump statements
    •  break
    •  continue
    •  goto


Control Statements in C


Compound Statement of Block

A compound statement or a block is a group of statements enclosed within a pair of curly braces { }. The statements inside a block are executed sequentially. The general form is:

{
    statement 1;
    statement 2;
    ..........
    ..........
    statement N;
}

Example:
{
    pi = 3.14;
    radius = 10.0;
    area = pi*radius*radius;
}


A compound statement is syntactically equivalent to a single statement and can appear anywhere in the program where a single statement is allowed.


The following program demonstrates compound statement.

#include <stdio.h>

int main(void)
{
    float pi, radius, area;
  
    /* a compound statement */
    {
        pi = 3.14;
        radius = 10.0;
        area = pi*radius*radius;
    }
   
    printf("Area of Circle = %f", area);   

    return 0;
}

Output:

Area of Circle = 314.000000


Decision making statements

Decision making is about deciding the order of execution of statements based on certain conditions or repeat a group of statements until certain specified conditions are met.

Following are decision-making statements:

  • The if statement
  • The switch statement


Decision making with if statement

The if statement may be implemented in different forms depending on the complexity of conditions to be tested. The different forms are:

  1. Simple if statement
  2. The if...else statement
  3. Nested if...else statement
  4. The if-else-if statement

Simple if Statement

if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not. The general form of a simple if statement is:

if (Test Expression) /* no semi-colon */
{
    statement 1;
    ...........
    statement n;
}
statement x;

The if structure may include 1 statement or n statements enclosed within curly brackets. 


The simple if statement works as follows: 


  • First the Test Expression is evaluated.
  • If the Test Expression evaluates to true (non-zero), then the statements of the if block (statement 1 to n) are executed.
  • If the Test Expression evaluates to false (zero), then the statements of the if block (statement 1 to n) are skipped and the statement (statement x) after if block is executed.

The statement in an if construct is any valid C language statement and the Test Expression is any valid C language expression that may include logical operations. Note that there is no semi-colon after the Test Expression. This is because the condition and statement should be put together as a single statement.


Flow Diagram: 

Simple if Statement


Example :

#include <stdio.h>

int main(void)
{
    int x, y;
  
    x = 25;
    y = 15;
   
    if (x > y)
    {
        printf("x is greater than y");
    }
   
    return 0;
}

Output:

x is greater than y

Explanation: 

In the Test Expression, we check if the value of x is greater than y. If the Test Expression evaluates to true the statement followed by if statement is executed. The message displayed will be "x is greater than y". If the condition is false nothing is displayed.


The if...else Statement

An if statement can be followed by an optional else statement, which executes when the Test Expression is false

The general form of a simple if...else statement is:

if(Test Expression)
{
    statement block 1;
}
else
{
    statement block 2;
}
statement x;

In the above syntax, we have written statement block. A statement block may include one or more statements.


The if...else statement works as follows: 

  • First the Test Expression is evaluated.
  • If the Test Expression is true, statement block 1 is executed and statement block 2 is skipped.
  • If the Test Expression is false, statement block 2 is executed and statement block 1 is ignored.

Now in any case after the statement block 1 or 2 gets executed, the control will pass to statement x. Therefore, statement x is executed in every case.


Flow Diagram:

The if...else Statement


Example :  

The following program finds whether a number is even or odd.

#include <stdio.h>

int main(void)
{
    int n;
   
    printf("\n Enter the number : ");
    scanf("%d", &n);
   
    if(n%2 == 0)
        printf("\n %d is even", n);
    else
        printf("\n %d is odd", n);
   
    return 0;
}

1st run:

Run the program and enter an even number, you will get the following output:

Output:


Enter the number : 4
4 is even

2nd run:

Run the program again but this time, enter an odd number.

Output:


Enter the number : 3
3 is odd

Explanation:

In the above program, integer variable n is declared. The user enters the number. The value is tested with if statement. If the Test Expression (n%2==0) is true the statement followed by if statement is executed and the statement followed by else statement is skipped. Otherwise the statement followed by else statement is executed and the statement followed by if statement is ignored.



Nested if…else Statement

We can add if...else statement inside if block or else block. This is called nesting of if...else.

if(Test Expression 1)
{
    if(Test Expression 2)
    {
        statement block 1;
    }

    else
    {
        statement block 2;
    }
}

else
{
    if(Test Expression 3)
    {
        statement block 3;
    }

    else
    {
        statement block 4;
    }
}

We can nest if...else statement to any depth.


The nested if...else statement works as follows:

  • First, Test Expression 1 is checked, if it is true, then the Test Expression 2 is checked, if it is true then statement block 1 is executed. Otherwise, statement block 2 is executed.
  • Otherwise, if the Test Expression 1 is false, then Test Expression 3 is checked, if it is true then statement block 3 is executed. Otherwise, statement block 4 is executed.

Flow Diagram:

Nested if...else Statement


Example:

The following program asks the user to enter three numbers and displays the larger of them.

#include <stdio.h>

int main(void)
{
    int a, b, c;
  
    printf("Enter three numbers : ");
    scanf("%d%d%d \n",&a, &b, &c);
   
    if(a > b)
    {
        if(a > c)
        {
            printf("a is the greatest");
        }
        else
        {
            printf("c is the greatest");
        }
    }
    else
    {
        if(b > c)
        {
            printf("b is the greatest");
        }
        else
        {
            printf("c is the greatest");
        }
    }
   
    return 0;
}

Output:

Enter three numbers : 12 9 11
a is the greatest


The if-else-if Statement

C language supports if-else-if statements to test additional conditions apart from the initial Test Expression. The if-else-if construct works in the same way as a normal if statement. Its construct is given below:

if(Test Expression 1)
{
    statement block 1;
}
else if(Test Expression 2)
{
    statement block 2;
}
...........................
else
{
    statement block x;
}

statement y;

Note that it is not necessary that every if statement should have an else block as C supports simple if statements. After the first Test Expression or the first if branch, the programmer can have as many else-if branches as he wants depending on the expressions that have to be tested.

The if-else-if statement works as follows:
 

The Test Expression is evaluated from the top of the ladder to downwards. As soon as a true Test Expression is found, the statement associated with it is executed and the control is transferred to the statement y (skipping the rest of the ladder). When all the Test Expressions become false, then the final else containing the default statement will be executed.



Flow Diagram:

The if-else-if Statement


Example:

The following program tests whether a number entered by the user is negative, positive, or equal to zero.

#include <stdio.h>

int main(void)
{
    int num;
   
    printf("\n Enter any number : ");
    scanf("%d", &num);
   
    if(num==0)
        printf("\n The value is equal to zero");
    else if(num > 0)
        printf("\n The number is positive");
    else
        printf("\n The number is negative");
   
    return 0;
}

Output:

Enter any number : 12
The number is positive


Points to Remember


  • In case the statement block contains only one statement, putting curly brackets becomes optional. 

    int x = 3;
    if(x > 0)
        printf("Success");

    No curly braces are required in the above case, but if there are more than one statement in the statement block, putting curly brackets becomes mandatory.

  • The expression given in the if statement may not be always true or false. For example, if(1) or if(0). When such statement is encountered, the compiler will display a warning message "condition is always true" or "condition is always false"

  • if(exp != 0) is often written as if(exp) 

    The value of expression (exp != 0) will be true if exp is non-zero and false if exp is zero. The value of expression (exp) will be true if exp is non-zero (as non-zero is true in C) and false if exp is zero. Hence we can write if(exp) instead of if(exp != 0).

    So whenever you see code in this form:

    if(exp)
        statement x;

    read it as - if exp is non-zero execute statement x.

  • if(exp == 0) is often written as if(!exp)

    The value of expression (exp == 0) will be true if exp is zero and false if exp is non-zero. The expression (!exp) will be true if exp is zero and false if exp is non-zero. Hence we can write if(!exp) instead of if(exp == 0).

    So whenever you see code in this form:

    if(!exp)
        statement y;

    read it as - if exp is zero execute statement y.



next    The while Loop in C
top    Index
prev    Type Conversion in C



No comments:

Post a Comment