Control Statements in C

Share this article

Control statements enable us to specify the flow of program control — that is, the order in which the instructions in a program must be executed. They make it possible to make decisions, to perform tasks repeatedly or to jump from one section of code to another.

Types of Control Statements

There are four types of control statements in C:

  1. Decision making statements (if, if-else)
  2. Selection statements (switch-case)
  3. Iteration statements (for, while, do-while)
  4. Jump statements (break, continue, goto)

Decision Making Statement: the if-else Statement

The if-else statement is used to carry out a logical test and then take one of two possible actions depending on the outcome of the test (ie, whether the outcome is true or false).

Syntax:

if (condition)
{
  // statements
}
  else
{
  // statements
}

If the condition specified in the if statement evaluates to true, the statements inside the if-block are executed and then the control gets transferred to the statement immediately after the if-block. Even if the condition is false and no else-block is present, control gets transferred to the statement immediately after the if-block.

The else part is required only if a certain sequence of instructions needs to be executed if the condition evaluates to false. It is important to note that the condition is always specified in parentheses and that it is a good practice to enclose the statements in the if block or in the else-block in braces, whether it is a single statement or a compound statement.

The following program checks whether the entered number is positive or negative.

#include<stdio.h>
int main( ) {
  int a;
  printf("n Enter a number:");
   scanf("%d", &a);

   if(a>0)
    { 
     printf( "n The number %d is positive.",a);
    }
    else
    {
     printf("n The number %d is negative.",a);
    }

  return 0;
   }

The following program compares two strings to check whether they are equal or not.


#include <string.h>

int main( ) {
    char a[20] ,  b[20];

    printf("n Enter the first string:");
    scanf("%s",a);
    printf("n Enter the second string:");
    scanf("%s",b);

    if((strcmp(a,b)==0))
      {
       printf("nStrings are the same");
       }
    else
      {
      printf("nStrings are different");
      }

  return 0;
}

The above program compares two strings to check whether they are the same or not. The strcmp function is used for this purpose. It is declared in the string.h file as:

int strcmp(const char *s1, const char *s2);

It compares the string pointed to by s1 to the string pointed to by s2. The strcmp function returns an integer greater than, equal to, or less than zero,  accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

Therefore in the above program, if the two strings a and b are equal , the strcmp function should return a 0. If it returns a 0, the strings are the same; else they are different.

Nested if and if-else Statements

It is also possible to embed or to nest if-else statements one within the other. Nesting is useful in situations where one of several different courses of action need to be selected.

The general format of a nested if-else statement is:

if(condition1)
{
// statement(s);
}
else if(condition2)
{
//statement(s);
}
.
.
else if (conditionN)
{
//statement(s);
}
else
{
//statement(s);
}

The above is also called the if-else ladder. During the execution of a nested if-else statement, as soon as a condition is encountered which evaluates to true, the statements associated with that particular if-block will be executed and the remainder of the nested if-else statements will be bypassed. If neither of the conditions are true, either the last else-block is executed or if the else-block is absent, the control gets transferred to the next instruction present immediately after the else-if ladder.

The following program makes use of the nested if-else statement to find the greatest of three numbers.

#include<stdio.h>

int main( ) {
    int a, b,c;
    a=6,b= 5, c=10;
    if(a>b)
      {
        if(b>c)
          {
            printf("nGreatest is: " , a);
          }
        else if(c>a)
           {
             printf("nGreatest is: ", c);
           }
      }
    else if(b>c)     //outermost if-else block
       {
         printf("nGreatest is: " , b);
       }
      else
      {
        printf( "nGreatest is: " , c);
      }
    return 0;
}

The above program compares three integer quantities, and prints the greatest. The first if statement compares the values of a and b. If a>b is true, program control gets transferred to the if-else statement nested inside the if block, where b is compared to c. If b>c is also true, the value of a is printed; else the value of c and a are compared and if c>a is true, the value of c is printed. After this the rest of the if-else ladder is bypassed.

However, if the first condition a>b is false, the control directly gets transferred to the outermost else-if block, where the value of b is compared with c (as a is not the greatest). If b>c is true the value of b is printed else the value of c is printed. Note the nesting, the use of braces, and the indentation. All this is required to maintain clarity.

Selection Statement: the switch-case Statement

A switch statement is used for multiple way selections that will branch into different code segments based on the value of a variable or expression. This expression or variable must be of integer data type.

Syntax:

switch (expression)
{
  case value1:
    code segment1;
    break;
  case value2:
    code segment2;
    break;
.
.
.
  case valueN:
    code segmentN;
    break;
  default:
    default code segment;
}

The value of this expression is either generated during program execution or read in as user input. The case whose value is the same as that of the expression is selected and executed. The optional default label is used to specify the code segment to be executed when the value of the expression does not match with any of the case values.

The break statement is present at the end of every case. If it were not so, the execution would continue on into the code segment of the next case without even checking the case value. For example, supposing a switch statement has five cases and the value of the third case matches the value of expression. If no break statement were present at the end of the third case, all the cases after case 3 would also get executed along with case 3. If break is present only the required case is selected and executed; after which the control gets transferred to the next  statement immediately after the switch statement. There is no break after defaultbecause after the default case the control will either way get transferred to the next statement immediately after switch.

Example: a program to print the day of the week.

#include<stdio.h>

int main( ) {
  int day;
  printf("nEnter the number of the day:");
  scanf("%d",&day);

  switch(day)
    {
      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("Invalid choice");
      }
   return 0;
}

This is a very basic program that explains the working of the switch-case construct. Depending upon the number entered by the user, the appropriate case is selected and executed. For example, if the user input is 5, then case 5 will be executed. The break statement present in case 5 will pause execution of the switch statement after case 5 and the control will get transferred to the next statement after switch, which is:

return 0;

It is also possible to embed compound statements inside the case of a switch statement. These compound statements may contain control structures. Thus, it is also possible to have a nested switch by embedding it inside a case.

All programs written using the switch-case statement can also be written using the if-else statement. However, it makes good programming sense to use the if statement when you need to take some action after evaluating some simple or complex condition which may involve a combination of relational and logical expressions (eg, (if((a!=0)&&(b>5))).

If you need to select among a large group of values, a switch statement will run much faster than a set of nested ifs. The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean expression.

The switch statement must be used when one needs to make a choice from a given set of choices. The switch case statement is generally used in menu-based applications. The most common use of a switch-case statement is in data handling or file processing. Most of file handling involves the common functions: creating a file, adding records, deleting records, updating records, printing the entire file or some selective records. The following program gives an idea of how the switch case statement may be used in data handling. It does not involve the code for file processing as we can discuss file handling in C only after we have learnt advanced concepts like pointers, structures and unions.

Example: A switch case statement used in data file processing.

#include<stdio.h>

int main() { //create file &set file pointer .
  int choice;
  printf("n Please select from the following options:");
  printf("n 1. Add a record at the end of the file.");
  printf("n 2. Add a record at the beginning of the file:");
  printf("n 3. Add a record after a particular record:";
  printf("nPlease enter your choice:(1/2/3)?");
  scanf("%d",&choice);

   switch(choice)
     {
       case 1:
         //code to add record at the end of the file
         break;
       case 2:
         //code to add record at the beginning of the file
         break;
       case 3:
         //code to add record after a particular record
         break;
       default:
         printf("n Wrong Choice");
      }
  return 0;
}

The above example of switch-case generally involves nesting the switch-case construct inside an iteration construct like do-while.

Iteration Statements

Iteration statements are used to execute a particular set of instructions repeatedly until a particular condition is met or for a fixed number of iterations.

1. The for statement

The for statement or the for loop repeatedly executes the set of instructions that comprise the body of the for loop until a particular condition is satisfied.

Syntax:

for(initialization; termination; increment/decrement) { //statements to be executed }

The for loop consists of three expressions:

  • The initialization expression, which initializes the looping index. The looping index controls the looping action. The initialization expression is executed only once, when the loop begins.
  • The termination expression, which represents a condition that must be true for the loop to continue execution.
  • The increment/decrement expression is executed after every iteration to update the value of the looping index.

The following program uses the for loop to print the series: 0,1,1,2,3,5,8,13 … to n terms.

#include<stdio.h>
int main() {
  int i,n, a, b, sum=0;
  printf("Enter the number of terms:");
  scanf("%d",&n);
  a=0; b=1;
  printf("%dn %d",a ,b);
  
  for(i=2; i< n; i++)   { 
    sum=a+b;  
    printf("n%d",sum);
    a=b;
    b=sum;
  }

  return 0; 
}

If the first two elements 0 and 1 are excluded, it is seen that each of the next elements in the series is the sum of the previous two elements. For example, the third element is a sum of the first two elements (0+1), the fourth element is a sum of the second and the third elements (1+1=2), the fifth element is a sum of the third and the fourth elements (1+2=3) and so on. Therefore, each time it is the sum of the previous two elements that is printed. The previous value of b becomes the new value of a and the previous value of sum becomes the new value of b. The newly calculated sum becomes the next element and is subsequently printed. These steps are executed repeatedly until the looping index i does not reach one less than the number of terms entered by the user. The looping index i begins from 2 as the first two terms have already been printed. It could also range from 0 to 1 less than n-2 as:

for(i=0;i<(n-2);i++)

or from 1 to n-2 as:

for(i=1; i<(n-2);i++)

The for statement is very versatile and can be written in four different ways:

1. Omitting the Initialization Expression

In this case, the looping index is initialized before the for loop. Thus the for loop takes the following form:

i=0;/*initialization*/ 
for(; condition;increment/decrement expression)  {  
  //statements to be executed 
}

Notice that the semicolon that terminates the initialization expression is present before the condition expression.

2. Omitting the Condition

In this case the condition is specified inside the body of the for loop, generally using an if statement. The while or do-while statements may also be used to specify the condition. Thus the for loop takes the following form:


for(initialization; ; increment/decrement expression)  {
   condition //statements to be executed
}

Again, it can be seen that the semicolon that terminates the condition is present in the for statement. The following program explains how the condition can be omitted:

#include<stdio.h> 
int main()  {
  int i,n, a, b, sum=0;
  printf("Enter the number of terms:");
  scanf("%d",&n); 
  a=0;
  b=1;
  printf("%dn %d", a, b);

  for(i=2; ;i++)  {
    if(i==(n-1)) { //condition specified using if statement  
      break;
    }
    
    sum=a+b;
    printf("n%d",sum);
    a=b;
    b=sum;
  }

  return 0;
}

3. Omitting the increment /decrement Expression:

In this case the increment/decrement expression is written inside the body of the for loop.

Example:

#include<stdio.h>
int main()  {
  int i,n, a, b, sum=0;
  printf("Enter the number of terms:");
  scanf("%d",&n);
  a=0;
  b=1;
  printf("%dn %d",a,b);

  for(i=2;i<n;)  {
    sum=a+b;
    printf("n%d",sum);
    a=b;  
    b=sum;
    i++;  //increment expression 
   }

   return 0;
}

4. Omitting all Three Expressions:

It is also possible to omit all three expressions, but they should be present in the ways discussed above. If all three expressions are omitted entirely — ie, they are not mentioned in the ways discussed above — then the for loop becomes an infinite or never-ending loop. In this case, the for loop takes the following form:

for(;;) {
  //statements 
}

2. The while statement

The while statement executes a block of statements repeatedly while a particular condition is true.

while (condition)  {
  //statement(s) to be executed 
}

The statements are executed repeatedly until the condition is true.

Example: Program to calculate the sum of the digits of a number (eg, 456; 4+5+6 = 15)

#include<stdio.h>
int main() {
  int n, a,sum=0;
  printf("n Enter a number:");
  scanf("%d", &n);

  while(n>0) {
    a=n%10; //extract the digits of the number  
    sum=sum+a; //sum the digits  
    n=n/10; //calculate the quotient of a number when divided by 10. 
   }   

  printf("n Sum of the digits=t %d",sum);
  return 0; 
}

The above program uses the while loop to calculate the sum of the digits of a number. For example, if the number is 456, the while loop will calculate the sum in four iterations as follows. It would be helpful to remember that % gives the remainder and / the quotient.

Iteration 1: n>0  Condition is true(n=456)
a=n%10=6;
sum=sum+a=6;
n=n/10= 45;  New value of n is 45.

Iteration 2: n>0 Condition is true(n=45)
a=n%10=5;
sum=sum+a=6+5=11;
n=n/10= 4;   New value of n is 4.

Iteration 3: n>0 Condition is true(n=4)
a=n%10=4;
sum=sum+a=11+4=15;
n=n/10= 0;  ew value of n is 0.

Iteration 4: n>0 Condition is false(n=0).
After the fourth iteration control exits the while loop and prints the sum to be 15.

Example 2: Program to check whether the entered number is a palindrome or not.

A palindrome is a number which remains the same when its digits are read or written from right to left or vice versa, eg 343 is a palindrome, but 342 is not. The following program works on the logic that if the reverse of the number is same as the original number then the entered number is a palindrome, otherwise it is not.

#include<stdio.h>  
int main() {
  int a, n, m, reverse=0;
  printf("n Enter a number:");
  scanf("%d", &n);  
  m=n;

  while(n>0) {
    a=n%10; reverse=reverse*10 +a;
    n=n/10;
   }  
  if (m== reverse) 
     {  
    printf(" n The number is a palindrome.");
     } 
    else  
     { 
    printf("n The number is not a palindrome.");
  } 

  return 0;
}

The above program uses almost the same logic as the program concerning the sum of digits. As was seen in that program, n becomes 0 in the last iteration. However, we need to compare the original value of n to the reverse of the number to determine whether it is a palindrome or not. Therefore, the value of n has been stored in m, before entering the while loop. The value of m is later compared with reverse to decide whether the entered number is a palindrome or not.

The while loop works in the following way:

Let n=343;

Iteration 1:
a= n%10=3;
reverse=reverse*10+a=0*10+3=3;
n=n/10=34;

Iteration 2:
a=n%10=4;
reverse=reverse*10+a=3*10+4=34;
n=n/10=3;

Iteration 3:
a= n%10=3;
reverse=reverse*10+a=34*10+3=343;
n=n/10=0;

Iteration 4:
n>0 condition false(n=0).
Control exits from the while loop.

3. The do-while loop

The do-while statement evaluates the condition at the end of the loop after executing the block of statements at least once. If the condition is true the loop continues, else it terminates after the first iteration.
Syntax:

do { 
  //statements to be executed;  
} 
while(condition);

Note the semicolon which ends the do-while statement. The difference between while and do-while is that the while loop is an entry-controlled loop — it tests the condition at the beginning of the loop and will not execute even once if the condition is false, whereas the do-while loop is an exit-controlled loop — it tests the condition at the end of the loop after completing the first iteration.

For many applications it is more natural to test for the continuation of a loop at the beginning rather than at the end of the loop. For this reason, the do-while statement is used less frequently than the while statement.

Most programs that work with while can also be implemented using do-while. The following program calculates the sum of digits in the same manner, except that it uses the do-while loop:

#include<stdio.h> 
int main() { 
  int n, a,sum=0;
  printf("n Enter a number:");
   scanf("%d", &n);  
   do {
     a=n%10;
     sum=sum+a;
     n=n/10;
    }
    while(n>0);
      
    printf("n Sum of the digits=t %d",sum);

    return 0;
  }

However, the do-while statement should be used only in situations where the loop must execute at least once whether or not the condition is true.

A practical use of the do-while loop is in an interactive menu-driven program where the menu is presented at least once, and then depending upon the choice of the user, the menu is displayed again or the session is terminated. Consider the same example that we saw in switch-case. Without using an iteration statement like do-while, the user can choose any option from the menu only once. Moreover, if a wrong choice is entered by mistake the user doesn’t have the option of entering his choice again. Both these faults can be corrected by using the do-while loop.

#include<stdio.h>

int main() {  //create file &set file pointer .  
  int choice;
  char ch;
  printf("n Main Menu ");
  printf("n 1. Add a record at the end of the file."); 
  printf("n 2. Add a record at the beginning of the file:"); 
  printf("n 3. Add a record after a particular record:";  
  printf("nPlease enter your choice:(1/2/3)?");
  scanf("%d",&choice);

  do  {   
    switch(choice)  { 
      case 1: 
        //code to add record at the end of the file  break; 
      case 2:
        //code to add record at the beginning of the file break; 
      case 3: 
        //code to add record after a particular record  break;  
      default: printf("n Wrong Choice");  
    }  
    printf(" Do you want to continue updating records(y/n)?");
    scanf("%c", ch);
    }
    while (ch=='y'||ch=='Y');

    return 0;  
  }

FAQs About Control Statements in C

What are control statements in C?

Control statements in C are programming constructs that allow you to control the flow of a program. They include conditional statements, loops, and branching statements.

What is the purpose of conditional statements in C?

Conditional statements, such as if, else if, and switch, allow you to execute different blocks of code based on specified conditions. They enable your program to make decisions and perform actions accordingly.

How do I use the if statement in C?

The if statement is used to execute a block of code if a specified condition is true. It can be followed by an optional “else” statement to specify an alternative action if the condition is false.

What is the difference between if and switch statements?

if statements are used for general conditional branching, while switch statements are used for multi-way branching based on the value of an expression. if statements are more flexible and can handle complex conditions, whereas switch statements are ideal for situations where a variable can match specific values.

When should I use a while loop over a for loop?

Use a while loop when you need to repeat a block of code as long as a condition remains true but without a fixed number of iterations. for loops are more suitable for situations with a known number of iterations.

What are the common mistakes to avoid when using control statements in C?

Common mistakes include not using braces for code blocks in if and loop statements, forgetting to update loop control variables, and creating infinite loops by not changing loop conditions correctly. Properly structuring your code and handling corner cases are essential.

Can I use multiple else if conditions in an if statement?

Yes, you can use multiple else if conditions in an if statement to evaluate a series of conditions sequentially. This allows you to choose from several alternatives based on the first condition that is true.

Surabhi SaxenaSurabhi Saxena
View Author

My name is Surabhi Saxena, I am a graduate in computer applications. I have been a college topper, and have been awarded during college by the education minister for excellence in academics. I love programming and Linux. I have a blog on Linux at www.myblogonunix.wordpress.com.

C
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week