Here we learn about the control structures of C. The compiler normally takes the program line by line and executes them in a sequence ( one after another ). But this may not always be the case. Based on certain conditions existing in the data, we may want to change the data – Then we use an If statement. In a limiting case, you may need to choose one out of several possible options – by using a Switch statement.

Sometimes you also need to repeat the same set of statements repeatedly. Such statements are called loops. The number of times you do this may be or may not be known at the time of writing a program. This will lead us to for, while, and Do While loops.

Control Structures in C

So far, we have only seen a program as a sequence of instructions the program beginning at the first line & ends in the last. However, such simple structures do not always exist in practice. Depending on the situation, we may have to skip certain instructions, repeat certain instructions etc.. Such facilities are provided by the control structures. Basically there are two types of very popular structures. One will allow us to make decisions while the other will make repeated executions of a set of instructions possible. We shall see them one after another.

The if statement:

The basic structure of the statement is

If ( expression) 
    Program statement 
    Next statement

i.e if the expression inside the parenthesis is satisfied, then the program statement is executed & then next statement is executed. If it is false, the program statement is skipped, but the next statement is executed. A non programming example could be like this.

If ( the weather cold)
    I shall wear woolen clothes
    I go for a walk.

i.e. if the weather is cold ( expression is true) I shall wear woolen clothes ( program statement). (then) I go for a walk ( next statement). If the weather is not cold(expression false), I go for a walk ( skip the program statement, go to a next statement) we shall see a more academic example in the following program.

CALCULATE THE ABSOLUTE VALUE OF AN INTEGER

#include<stdio.h>
main ()
    {
    int number;
    printf (“ Type in your number: “);
    scanf(“%d “, &number);
    if ( number <0)
    number = -number;
    printf(“ The absolute value is %dn”,number);
}

Output:

Type in your number: -100
The absolute value is 100

Output(Re-run):

Type in your number: 2000
The absolute value is 2000

A more frequently used version of decision is

If (condition) then { statement 1 }
    Else
        { statement 2 ) type of statements

i.e if the condition is satisfied statement 1 is executed if it false statement 2 is executed. In either case the statement next to statement 2 is executed.

We shall see some programs that use such control statements.

Write a program to calculate tax

Algorithm:

  1. Enter pay and status
  2. Check for status, if it results true compute tax with 20%
  3. Print the tax.

PROGRAM TO TEST IF….ELSE STATEMENT

#include<stdio.h> 
main()
    {
    char status;
    float tax,pay;
    printf("Enter the payment:n");
    scanf("%f",&pay);
    printf("Enter statusn");
    scanf(%c",&status);
    if (status = = 's') 
        tax=0.20 * pay;
    else
        tax=0.14*pay;
    printf("Tax=%f",tax);
}

PROGRAM TO DETERMINE IF A NUMBER IS EVEN OR ODD

#include<stdio.h>
main ()
    {
    int number_to_test, reminder;
    printf (“Enter your number to be tested.: “);
    scanf(“%d”, &number_to_test);
    reminder = number_to_test %2;
    if ( reminder==0)
    printf(“ The number is even.n”);
    if (reminder !=0)
    printf(“ The number is off.n”);
}

Output:

Enter your number to be tested: 2455
The number is odd.

Output (Re-run):

Enter your number to be tested: 1210
The number is even

THIS PROGRAM DETERMINES IF A YEAR IS A LEAP YEAR

#include<stdio.h>
main ()
    {
    int year, rem_4,rem_100,rem_400;
    printf(“Enter the year to be tested:”);
    scanf(“%d”, &year);
    rem_4 = year % 4;
    rem_100 = year % 100;
    rem_400 = year % 400;
    if ( ( rem_4 ==0 && rem_100 !=0) || rem_400 = = 0 )
    printf (“ It’s a leap year.n);
    else
    printf (“Nope, it’s not a leap year.n);
}

Output:

Enter the year to be tested: 1955
Nope, it’s not a leap year. 

Output ( Re-run):

Enter the year to be tested: 2000
It’s a leap year.

Output(Re-run)

Enter the year to be tested: 1800
Nope, it’s not a leap year

PROGRAM TO EVALUATE SIMPLE EXPRESSION OF THE FORM NUMBER OPERATOR NUMBER

#include<stdio.h>
main ()
    {
    float value1, value2;
    char operator;
    printf (“Type in your expression.n”);
    scanf (%f %c %f”,&value1, & operator, & value2);
    if ( operator = = ‘+’)
    printf(“%.2fn”,value1 + value2);
    else if ( operator = = ‘-’)
    printf(“%.2fn”,value1 – value2);
    else if ( operator = = ‘*’)
    printf(%.2fn”,value1 * value2);
    else if (operator = = ‘/’)
    printf(%.2fn”,value1/value2);
}

Output:

Type in your expression.
123.5 + 59.3
182.80

Output (Re-run):

Output ( Re-run):

THIS PROGRAM FINDS THE LARGEST OF THE 3 GIVEN NUMBERS USING A NESTED IF CONSTRUCT

#include <stdio.h>
main ()
    {
    int num1, num2, num3, max;
    printf(“Enter 3 integer number:”);
    scanf(%d %d %d”,&num1, &num2, &num3);
    max = num3;
    if ( num1 > num2)
    { 
      if (num1 > num3)
      max = num1;
    }
    else if (num2 > num3)
      max = num2;
    printf(“The given number are %3d, %3d,and %3dn”,num1,num2,num3)
    printf(“The largest number = %3dn”,max);
 }

Output:

Enter 3 integer numbers: 5 87 12
The given numbers are 5, 87, and 12
The largest number = 87 

The switch statement

When there are a number of else alternatives as above, way of representing is by the switch statement. The general format of a switch statement is:

Switch (expression)
   {
    case value1:
      program statement
      program statement
      ...
      break;
    case value2:
      program statement
      program statement
      ...
      break;
      ...
    case value’n’:
      program statement
      program statement
      ...
      break;
    default:
      program statement
      program statement
      ...
      break;
}

Program to evaluate simple expression of the form value operator value

#include<stdio.h>
main()
{
      float value1, value2;
      char operator;
      printf(“Type in your expression. n”);
      scanf (%f %c %f”,&value1,&operator,&value2);
      switch(operator) 
      {
        case '+':
          printf(“%.2f n”, value1 + value2);
          break;
        case '-':
          printf(“%.2f n”, value1 - value2);
          break;
        case '*':
          printf(“%.2f n”, value1 * value2);
          break;
        case '/':
          if(value2 == 0)
          printf(“division by zero. n”);
          else
          printf(“%.2f n”, value1 / value2);
          break;
        default:
          printf(“Unknown Operator n”); 
          break
       }
}

Loops

The other type of control structures that we need are loops. Quite often, a set of instructions will have to be repeated again & again. For example, if you are calculating salary of 1000 employees, the portion of the program pertaining to the salary of employees will have to be repeated 1000 times, each time with a different set of data. The easiest way to do it is to start some sort of a counter, say i, to zero; each time one set of instructions are completed, the counter is increased by one and when it reaches 1000, we have to stop the repetitions. This can be done by the programmer also, but C provides special construct to do this.

In certain other cases, we will not be sure as to how many times the repetitions are to be done, but we have to continue till some conditions are satisfied – like all records getting exhausted or as long as some employees remain etc.. C provides facilities for such type of loops also.

We shall see them one after another.

The for loop:

This is the simplest form of loops, where you know before hand how many repetitions ( ” iterations” in computer terminology ) are to be done. Like the case of 1000 employees or 100 students of a class etc. The format is:

for (variable = initial ; variable = how long value to continue; amount of increment ) 
{
    Lines to be repeated
}

It is obvious that the initial value of variable need not always be 0 or 1; it can be anything. Similarly after each operation, you need not increment by 1. It can be 2,3 … anything, even negative you want to count backwards). Note that you are only specifying the method of incrementing, the actual incrementing is done by the C control. It sets the variable to the initial value, after each iteration, increments suitably, checks whether the terminating condition is met with, if not repeats the operations. Of course, it is the duty of the programmer to ensure that at some stage, the loop terminates – if the terminating condition never emerges out of the successive increments the program will go into an infinite loop.

Let us see a few examples for the for loop.

Program:
Suppose we want to find the average of N given numbers. Obviously we input the numbers one after the other, add them into a sum and then divide by N. Let us also presume that N is also given at run time.

#include <stdio.h>
#include<math.h>
main()
    {
    int n,i,num,sum=0;
    float avg;
    /* N is the number of numbers, num is the number ( read one at a time) & sum is the total*/
    
    printf("input how many numbers are theren");
    scanf("%d",&n);
    for (i=1; i<n; i=i+1)
    {
        printf("input the next numbern");
        scanf("%d",&num);
        sum=sum+num;
    }
    avg=sum/n;
    printf("the average of the numbers is:n %f",avg);
}

The steps are fairly simple to understand.

a) The computer prints on the terminal, Input how many numbers are there.
b) If, say, 10 numbers are to be added, the number 10 is given as the input.
c) Then, inside the loop, the system keeps asking ( 10 times in this case) input the next number.
d) Every time, the next number of the set of numbers for which average is to be calculated is inputted.
e) In the end, the sum & average are calculated.

The point to be noted is that the loop keeps incrementing itself as long as i< or=n automatically and stops once n become greater than n i.e. we technically say there were “n iterations”

Program:
Now we will look one more simple but popular program to find the factorial of a number. It the number is, say, 5 it’s factorial is 5 x 4 x 3 x 2 x 1 i.e the product numbers from 1 to n.

#include<stdio.h>
#include <math.h>
main()
    {
     int n,prod=0;
     printf("input the numbern");
     scanf("%dn",&n);
     for (i=1; i<n; i=i+1)
       {
       prod=(prod*i);
       }
     printf("The factorial isn,%d",prod);
}

of course, the initial value of the loop need not always start with 1.

Program:
Let us illustrate by a simple case. We want to find the sum of the first 50 even numbers. The program looks something like this:

#include<stdio.h>
main()
    {
    int i,sum=0;
    for(i=2; i<=100; ++i)
      {
      sum=sum+i;
      }
    printf("The sum of the numbers is,%dn",sum);
}