Control Statements in C

Control Statements in C

This tutorial tells you about different control statements that are used in C for the flow of control. This is sometimes called decision-making statements.

What are control statements?

All those statements which decide the upcoming statements are executed or not are called control statements. They are also known as decision-making statements.

Generally, a C program is executed in the flow directive from top to bottom and left to right. In this flow, all the statements written in the program are executed one after another in the sequence they are written.

But many times, the programmers want that some statements remain unexecuted on the basis of certain conditions. The programmer wants to execute the statements iff some condition becomes true otherwise not.

This can be done in the program by using control statements or decision-making statements.

What are different types of statements used in C?

The following are the different types of control statements that are used in the C programming language. 
  1. If statements (if, if ... else, nested if, ladder if)
  2. Conditional statements
  3. Switch statements
  4. Goto statements
  5. For loop
  6. While loop
  7. Do loop
  8. Break statement
  9. Continue statement

Simple if statements in C

if statement executes on the basis of the condition written with it. If the condition is written with ' if ' statement evaluates to true then only the if statements execute all the expressions written inside it. 

If the condition written with ' if ' statement evaluates to false, if statement skips the execution of all statements written inside it. for example:


Example: Simple if in c


#include<stdio.h>
int main() 
 {   
  printf("Example of if statement in C \n");

  int n = 10;

  if ( n %2 == 0)      
   {
    n = n*2;// if block
   }

  printf("Answer = %d", n);      
 }

Output

Example of if statement in C
Answer = 20

Explanation

We take n, a variable of integer data type and initialize it with 10. Then the control goes to ' if ' statement. Here, the condition written inside ' if ' statement is checked whether it is true or not.

If the condition seems true then the statements written inside ' if ' block is executed otherwise not and the control goes out of ' if ' block. Here, (10%2 == 0) is true because % takes remainder and when we divide 10 and 2 we get 0 as remainder. 

So, ' if ' condition becomes true and hence the instructions or statements written inside ' if ' block is executed and 10*2 i.e., 20 is stored inside n.

Now, the control goes out of ' if ' block, and 20 get printed as output on the screen.

if-else statements in C

Else statements also have a block that contains all statements that are executed when the condition written with if evaluates to false. Else block is optional and is used depending upon the situation.

Else statements are optional in a program and are used only when the programmer has the optional statements to execute when if block does not. for example

Example: if-else in c


#include<stdio.h>
int main()
 {
  float purchase, discount;

  printf("Enter Purchase\n");
  scanf("%f", &purchase);

  if (purchase>1000)
   {
    discount = 0.2*purchase;
   }

  else
   {
    discount = 0.1*purchase;
   }

  printf("Discount = %f  \n", discount);
  printf("Final Price = %f", (purchase-discount));
 }


Output


Enter Purchase
8354
Discount = 1670.800049  
Final Price = 6683.200195

In the above c programs, d=0.2*p is executed when if block is true otherwise else block is executed.




// A program in C language to check whether a given number is positive or not.

#include<stdio.h>
void main() 
 {
  int num;

  printf("Enter any number \n");
  scanf("%d", &num);

  if (num > 0)
   {
    printf("%d is a positive number", num);
   }

  else
   {
    printf("%d is a negative number", num);
   }
 }

Output


Enter any number
99
99 is a positive number

Nested if statements in C

In a program, when the execution of some statements depends upon two or more conditions then the programmer either use nested if or ladder if or combination of both.

Nested if is a process of introducing another if statements into the if block of if statement of a program.


Syntax of nested if in c

if (True_Condition_1)
 {

   if (True_Condition_2)
    {
      expression_1;
    }

   else
    {
     expression_2;
    }

else
 {
   expression_3;
 }

Explanation:

expression_1 is executed when the True_Condition_1 and True_Condition_2 becomes True.
expression_2 is executed when True_Condition_1 becomes True and True_Condition_2 becomes False.
expression_3 is only executed when True_Condition_1 becomes False. 

Ladder if statements in C


Ladder if is a process of introducing another if statements inside the else block of if statement of a program.

Syntax of ladder if in c

if (True_Condition_1)
 {
  expression_1  
 }

else
 {

   if
     {
      expression_2;
     }

   else
    {
     expression_3; 
    }

 }

Explanation:

expression_1 is executed when the True_Condition_1 becomes True.
expression_2 is executed when True_Condition_1 becomes False and True_Condition_2 becomes True.
expression_3 is only executed when True_Condition_1 and True_Condition_2 both become False.

Let understand nested if and ladder if in an easier manner. 

In nested if, another condition is tested only when the first condition becomes true but in the case of ladder if, another condition is tested only when the first condition becomes false and that is why in case of ladder if, another if statement is introduced inside the else block.

Conditional statements in C


The conditional statement is the only statement in C language which requires three operands to complete its operations. 

It is a replacement of if-else statement i.e., the programs that are made in multiple lines using an if-else statement can be made in a simple one-line using conditional operator or by writing condition statements in C.

The conditional statement is formed by the combination of two symbols ( ? and :).

It works exactly like an if-else statement where it tests for some condition first and after its evaluation executes either expression 1 or expression 2 as shown below in the syntax.

Syntax of Conditional operator in C

(True Condition) ? expression_1 : expression_2;

Example: conditional statement in c



#include<stdio.h>
void main() 
 {
  int number1, number2, big;

  printf("Enter first value \n");
  scanf("%d", &number1);

  printf("Enter second value \n");
  scanf("%d", &number2);

  big = (number1>number2) ? number1 : number2;

  printf("Greatest number = %d", big);
 }   


Output


Enter first value
685
Enter second value
321
Greatest number = 685

Example: conditional operator in c



// A program to find the greatest among three numbers using the conditional operator or conditional statement.

#include<stdio.h>
void main() 
 {   
 int num1, num2, num3, big;
 
 printf("Enter first value");
 scanf("%d", &num1);
 
 printf("Enter second value");
 scanf("%d", &num2);

 printf("Enter third value");
 scanf("%d", &num3);

 big = num1>num2 ? (num1>num3 ? num1 : num3) : (num2>num3 ? num2 : num3);
 
 printf("Greatest number = %d", big);
 }

Output


Enter first value
108
Enter second value
356
Enter third value
1001
Greatest number = 1001

Switch statements in C


Switch case is a multiplier that selects one amongst multiple choices.

This statement selects on the basis of the value of the variable or the result of the expression. One out of many case statements written inside its block is executed.

The case that is been selected by the switch statement is having the value to the value of the variable or the result of the expression written with the switch statements after selecting the cause, all the statements corresponding to the case executed one by one till the break statement encounters.

If no case has been selected by switch statement then the statements of default will be executed as shown in the syntax below.

Syntax of switch-case statements in c

switch (variable or expression)
 {
  case value_1: expression_1;

  expression_2;
  break;

  case value_2: expression_3;

  case value_3: expression_4;

  expression_5;

  expression_6;
  break;



  default: expression_7; 
  break;
 }

Example: switch case in c



#include<stdio.h>
int main() 
 {
  int num;

  printf("Enter any number \n");
  scanf("%d", &num);

  switch(num+1)
   {
    case 3: num++;
    num++;
    break;

    case 0: num--;

    case 2: num++;
    break;

    case 1: num++;
    break;

    default: num++;
   }

  printf("The new number is %d", num);
 }  


Output


Enter any number
5
The new number is 6

Explanation:

If you give 2 as input then 2 is stored in num and switch statement fetch (num+1) i.e., (2+1 = 3) and 3 is scan by switch statements.

Now it will match each and every case statement with 3 and execute the written instructions according to its rule. It will go to case 3 (note that 2 is stored inside the num) and num is incremented by 1 and num get updated to 3, again num is increased by 1 by the case 3-second instruction and num becomes 4.

There is a break statement inside case 3 that means it will go out of the switch statements and finally 4 get stored inside num and is printed on the screen as output.

If you want to do more experiments with switch and case statements in C then you must try the above-written code with yourself just copy the code and give different numbers as input and see what you get as an output on the screen.


Example: switch case in c



 // A program to find whether the character is consonant or vowel

#include<stdio.h>
int main()   
 {
  char alphabet;

  printf("Enter any alphabet \n");
  scanf("%c", &alphabet);

  switch(alphabet)
   {
    case 'A' : 
    case 'E' : 
    case 'I' : 
    case 'O' : 
    case 'U' : 
 
    case 'a' : 
    case 'e' : 
    case 'i' : 
    case 'o' : 
    case 'u' : printf("%c is a vowel", alphabet);
    break;

    default: printf("%c is a consonant", alphabet);
   }
 }

Output


Enter any alphabet
N
N is a consonant

Goto statements in C

goto statement is different from all other decision making statements in c because it branches unconditionally, goto statements do not make a decision under the influence of any condition like other decision-making statements do.

Goto statement requires only a label that is ended with the colon and it can be anywhere throughout the program before goto statement or after goto statement.

Forward jumping and Backward jumping in C

If the label is written after goto statement then the program control jumps in the forward direction but if the label is written before goto statement, the program control jumps in the backward direction.

In both cases, there are some statements that remain unexecuted or keep on executing for an infinite time period which is not good for a program and that is why goto always used under some condition using if statements.

Example: goto statement in c


#include<stdio.h>
void main() 
 {
  nks:
  printf("Learning Mania : Learn New Things Everyday \n");

  goto nks;
 }   


Output


Learning Mania : Learn New Things Everyday
Learning Mania : Learn New Things Everyday
Learning Mania : Learn New Things Everyday
Learning Mania : Learn New Things Everyday
.
.
.

The above-written code goes executing infinite times. To control this infinite execution of goto statements we should make use of if statements. Let's see how to control this.


Example: goto statement in c


#include<stdio.h>
void main() 
 {
  int num = 1;

  nks:
  printf("Learning Mania : Learn New Things Everyday \n");

  num++;

  if (num <= 10)
   {
    goto nks;
   }

 }   


Output


Learning Mania : Learn New Things Everyday 
Learning Mania : Learn New Things Everyday 
Learning Mania : Learn New Things Everyday 
Learning Mania : Learn New Things Everyday 
Learning Mania : Learn New Things Everyday 
Learning Mania : Learn New Things Everyday 
Learning Mania : Learn New Things Everyday 
Learning Mania : Learn New Things Everyday 
Learning Mania : Learn New Things Everyday 
Learning Mania : Learn New Things Everyday

Let us see another easy program that uses goto statements. You will understand goto statement better. Have a look at this.


Example: goto statement in c

     1+2+3+4+5+......+n            */


// A program to print the following series:

#include<stdio.h>
void main() 
 {
  int i, n;

  printf("Enter n: \n");
  scanf("%d", &n);

  i = 1;

  series:
  printf("%d+", i);
  i++;

  if (i <= n)
   {
    goto series;
   }

 }


Output


Enter n: 
21
1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+

Loops in C 


What is a loop? Basically, Loops are the statements that are used to execute certain statements more than one but a definite number of times. In C, there are two types of loops.
  1. Entry control loop
  2. Exit control loop
Entry control loop has two variations namely for loop and while loop but Exit control loop has only one variation named as do loop.

For loop in C

If a user wants to execute a block of instructions repeatedly then for loop is used. It is an entry control statement in C.
For loop is an entry control loop that tests some condition first and only after that condition becomes true executes the body of the loop.
Initially, in the first attempt, if the condition becomes false, the entry control loop for loop will not execute the body of the loop even for once.
For loop provides all the three necessity execution of loop variable statements to be executed in a single line by separating with a semicolon
  1. initialization of a loop variable
  2. tests for some condition
  3. increment or decrement

Example: for loop in c


//  A program to print the table of any given number
#include<stdio.h>
int main() 
 {
  int num, i;

  printf("Enter number\n");
  scanf("%d", &num);

  printf("The table of the number %d is given below: \n", num);

  for(i=1; i<=10; i++)
   {
    printf("%d x %d = %d \n", num, i, num*i);
   }

 }


Output


Enter number
21
The table of the number 21 is given below:
21 x 1 = 21 
21 x 2 = 42 
21 x 3 = 63 
21 x 4 = 84 
21 x 5 = 105 
21 x 6 = 126 
21 x 7 = 147 
21 x 8 = 168 
21 x 9 = 189 
21 x 10 = 210 

For loop is also used to execute a block of instructions, for is a keyword that is written in the code to use for loop.

We first write initialization statement inside for loop syntax like i=0 is an initialization statement in the above example. Initialization statement is followed by condition.

We need to write condition next as shown in the above example i<= num is the condition statements followed by the condition which are to be tested. Finally, the loop variable is either incremented or decremented depending upon the program.

Now, let us discuss how for loop is executed. Firstly, initialization statement executes initialization and after the execution of initialization statement, it will go and check the condition.

If the condition meets True then the control moves inside the for loop block and executes each line of codes written inside it but if the condition is false then it will terminate the loop.

If condition is true the control move inside and it will execute the statements after the execution of these statements, it will go and check the modify statement what we call increment and decrement statements.

After checking modify statements it once again check the condition and if condition is true again then control moves inside for loop block and executes all statements written inside the block.

It will again go and check the modify statements and then it will check the condition means the loop will repeat here only as long as the condition is true. If the condition has failed then the control comes out of that.


While loop in C

While loop is also an entry control loop like for loop that tests some conditions first and when the condition evaluates to True allows the body of the loop to execute.

While loop is used only when the programmer wants loop to execute on the basis of user's input (infinite number of times).

Example: while loop in c


#include<stdio.h>
int main() 
 {
  int num = 15;              // local variable

  while(num <= 20)        // while loop
   {
    printf("value = %d \n", num);
    num++;
   }

 }   


Output


value = 15 
value = 16 
value = 17 
value = 18 
value = 19 
value = 20

Do loop in C

Do loop is an exit control loop that allows the body of the loop to execute first and after that go for testing some conditions.

Example: do loop in c


#include<stdio.h>
int main() 
 {
  char op;
  do
   {
    float purchase, discount;
   
    printf("Enter Purchase\n");
    scanf("%f", &purchase);

    if (purchase>1000)
     {
      discount = 0.2*purchase;
     }

    else
     {
      discount = 0.1*purchase;
     }

    printf("Discount = %f  \n", discount);
    printf("Final Price = %f", (purchase-discount));
    
    printf("\n \nDo you wanna continue >> 'Y/N' \n\n");
    scanf("%c", &op);
   }
  while(op == 'Y');
 }   


Output


Enter Purchase
999
Discount = 99.900002  
Final Price = 899.099976
 
Do you wanna continue >> 'Y/N' 

Y
Enter Purchase
1011
Discount = 202.199997  
Final Price = 808.799988
 
Do you wanna continue >> 'Y/N' 

Y
Enter Purchase
11111
Discount = 2222.199951  
Final Price = 8888.799805
 
Do you wanna continue >> 'Y/N' 

N

Break and Continue statements in C

Break and continue both the statements when executes in a loop stops the execution of all the other loop statements coming after these statements.

In this, break statements stops the execution of the loop in between whereas continue statements let it complete till the end of its execution i.e, when its condition becomes false.

Example: break and continue in c


#include<stdio.h>
int main() 
 {
  char option;
  
  do
   {
    int i, num;

    printf("Enter number to be checked \n");
    scanf("%d", &num);

    for(i=2; i<num; i++)
     {
      if (num % i == 0)
       {
        break;
       }
     }

    if (num == 1)
     {
      printf("1 is neither prime nor composite. \n");
     }

    else
     {
      if(i == num)
       {
        printf("%d IS A PRIME NUMBER", num);
       }

      else
       {
        printf("%d IS NOT A PRIME NUMBER", num);
       }
     }
      
      printf("\n \nDo you wanna continue >> 'Y/N' \n\n");
      scanf("%c", &option);
   }
   
  while(option == 'Y');
        
 }


Output


Enter number to be checked 
1
1 is neither prime nor composite. 

 
Do you wanna continue >> 'Y/N' 

Y
Enter number to be checked 
509
509 IS A PRIME NUMBER
 
Do you wanna continue >> 'Y/N' 

Y
Enter number to be checked 
111111
111111 IS NOT A PRIME NUMBER
 
Do you wanna continue >> 'Y/N' 

N

<< Previous                                                                                        Next >>
Previous
Next Post »

Comment Below: ConversionConversion EmoticonEmoticon