Back to Study material
OOP


UNIT 2


Control Structures and Functions


The if-else statement in C is used to perform the operations based on some specific condition. The operations specified in if block are executed if and only if the given condition is true.

There are the following variants of if statement in C language.

  • If statement
  • If-else statement
  • If else-if ladder
  • Nested if

If Statement

The if statement is used to check some given condition and perform some operations depending upon the correctness of that condition. It is mostly used in the scenario where we need to perform the different operations for the different conditions. The syntax of the if statement is given below.

  1. If(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

if statement in c

Let's see a simple example of C language if statement.

  1. #include<stdio.h>    
  2. Int main(){    
  3. Int number=0;    
  4. Printf("Enter a number:");    
  5. Scanf("%d",&number);    
  6. If(number%2==0){    
  7. Printf("%d is even number",number);    
  8. }    
  9. Return 0;  
  10. }    

Output

Enter a number:4

4 is even number

Enter a number:5

Program to find the largest number of the three.

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.    Int a, b, c;   
  5.     Printf("Enter three numbers?");  
  6.    Scanf("%d %d %d",&a,&b,&c);  
  7.    If(a>b && a>c)  
  8.    {  
  9.        Printf("%d is largest",a);  
  10.    }  
  11.    If(b>a  && b > c)  
  12.    {  
  13.        Printf("%d is largest",b);  
  14.    }  
  15.    If(c>a && c>b)  
  16.    {  
  17.        Printf("%d is largest",c);  
  18.    }  
  19.    If(a == b && a == c)   
  20.    {  
  21.        Printf("All are equal");   
  22.    }  
  23. }  

Output

Enter three numbers?

12 23 34

34 is largest

If-else Statement

The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition. The syntax of the if-else statement is given below.

  1. If(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of the if-else statement in C

if-else statement in c

Let's see the simple example to check whether a number is even or odd using if-else statement in C language.

  1. #include<stdio.h>    
  2. Int main(){    
  3. Int number=0;    
  4. Printf("enter a number:");    
  5. Scanf("%d",&number);     
  6. If(number%2==0){    
  7. Printf("%d is even number",number);    
  8. }    
  9. Else{    
  10. Printf("%d is odd number",number);    
  11. }     
  12. Return 0;  
  13. }    

Output

Enter a number:4

4 is even number

Enter a number:5

5 is odd number

Program to check whether a person is eligible to vote or not.

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.    Int age;   
  5.    Printf("Enter your age?");   
  6.    Scanf("%d",&age);  
  7.    If(age>=18)  
  8.    {  
  9.        Printf("You are eligible to vote...");   
  10.    }  
  11.    Else   
  12.    {  
  13.        Printf("Sorry ... you can't vote");   
  14.    }  
  15. }  

Output

Enter your age?18

You are eligible to vote...

Enter your age?13

Sorry ... You can't vote

If else-if ladder Statement

The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario where there are multiple cases to be performed for different conditions. In if-else-if ladder statement, if a condition is true then the statements defined in the if block will be executed, otherwise if some other condition is true then the statements defined in the else-if block will be executed, at the last if none of the condition is true then the statements defined in the else block will be executed. There are multiple else-if blocks possible. It is similar to the switch case statement where the default is executed instead of else block if none of the cases is matched.

  1. If(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. Else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. Else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

if-else-if ladder statement in c

The example of an if-else-if statement in C language is given below.

  1. #include<stdio.h>    
  2. Int main(){    
  3. Int number=0;    
  4. Printf("enter a number:");    
  5. Scanf("%d",&number);     
  6. If(number==10){    
  7. Printf("number is equals to 10");    
  8. }    
  9. Else if(number==50){    
  10. Printf("number is equal to 50");    
  11. }    
  12. Else if(number==100){    
  13. Printf("number is equal to 100");    
  14. }    
  15. Else{    
  16. Printf("number is not equal to 10, 50 or 100");    
  17. }    
  18. Return 0;  
  19. }    

Output

Enter a number:4

Number is not equal to 10, 50 or 100

Enter a number:50

Number is equal to 50

Program to calculate the grade of the student according to the specified marks.

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.    Int marks;   
  5.    Printf("Enter your marks?");  
  6.    Scanf("%d",&marks);   
  7.    If(marks > 85 && marks <= 100)  
  8.    {  
  9.        Printf("Congrats ! you scored grade A ...");   
  10.    }  
  11.    Else if (marks > 60 && marks <= 85)   
  12.    {  
  13.        Printf("You scored grade B + ...");  
  14.    }  
  15.    Else if (marks > 40 && marks <= 60)   
  16.    {  
  17.        Printf("You scored grade B ...");  
  18.    }  
  19.    Else if (marks > 30 && marks <= 40)   
  20.    {  
  21.        Printf("You scored grade C ...");   
  22.    }  
  23.    Else   
  24.    {  
  25.        Printf("Sorry you are fail ...");   
  26.    }  
  27. }  

Output

Enter your marks?10

Sorry you are fail ...

Enter your marks?40

You scored grade C ...

Enter your marks?90

Congrats ! you scored grade A ...

Switch Statement

The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Here, We can define various statements in the multiple cases for the different values of a single variable.

The syntax of switch statement in c language is given below:

  1. Switch(expression){    
  2. Case value1:    
  3. //code to be executed;    
  4. Break;  //optional  
  5. Case value2:    
  6. //code to be executed;    
  7. Break;  //optional  
  8. ......    
  9.    
  10. Default:     
  11. Code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of an integer or character type.

2) The case value must be an integer or character constant.

3) The case value can be used only inside the switch statement.

4) The break statement in switch case is not must. It is optional. If there is no break statement found in the case, all the cases will be executed present after the matched case. It is known as fall through the state of C switch statement.

Let's try to understand it by the examples. We are assuming that there are following variables.

  1. Int x,y,z;  
  2. Char a,b;  
  3. Float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

Switch(x)

Switch(f)

Case 3;

Case 2.5;

Switch(x>y)

Switch(x+2.5)

Case 'a';

Case x;

Switch(a+b-2)

 

Case 1+2;

Case x+2;

Switch(func(x,y))

 

Case 'x'>'y';

Case 1,2,3;

Flowchart of switch statement in C

flow of switch statement in c

Functioning of switch case statement

First, the integer expression specified in the switch statement is evaluated. This value is then matched one by one with the constant values given in the different cases. If a match is found, then all the statements specified in that case are executed along with the all the cases present after that case including the default statement. No two cases can have similar values. If the matched case contains a break statement, then all the cases present after that will be skipped, and the control comes out of the switch. Otherwise, all the cases following the matched case will be executed.

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. Int main(){    
  3. Int number=0;     
  4. Printf("enter a number:");    
  5. Scanf("%d",&number);    
  6. Switch(number){    
  7. Case 10:    
  8. Printf("number is equals to 10");    
  9. Break;    
  10. Case 50:    
  11. Printf("number is equal to 50");    
  12. Break;    
  13. Case 100:    
  14. Printf("number is equal to 100");    
  15. Break;    
  16. Default:    
  17. Printf("number is not equal to 10, 50 or 100");    
  18. }    
  19. Return 0;  
  20. }    

Output

Enter a number:4

Number is not equal to 10, 50 or 100

Enter a number:50

Number is equal to 50

Switch case example 2

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.    Int x = 10, y = 5;   
  5.    Switch(x>y && x+y>0)  
  6.    {  
  7.        Case 1:   
  8.        Printf("hi");  
  9.        Break;   
  10.        Case 0:   
  11.        Printf("bye");  
  12.        Break;  
  13.        Default:   
  14.        Printf(" Hello bye ");  
  15.    }   
  16.          
  17. }  

Output

Hi 

C Switch statement is fall-through

In C language, the switch statement is fall through; it means if you don't use a break statement in the switch case, all the cases after the matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. Int main(){    
  3. Int number=0;    
  4.  
  5. Printf("enter a number:");  
  6. Scanf("%d",&number);  
  7.  
  8. Switch(number){  
  9. Case 10:  
  10. Printf("number is equal to 10\n");  
  11. Case 50:  
  12. Printf("number is equal to 50\n");  
  13. Case 100:  
  14. Printf("number is equal to 100\n");  
  15. Default:  
  16. Printf("number is not equal to 10, 50 or 100");  
  17. }  
  18. Return 0;  
  19. }    

Output

Enter a number:10

Number is equal to 10

Number is equal to 50

Number is equal to 100

Number is not equal to 10, 50 or 100

Output

Enter a number:50

Number is equal to 50

Number is equal to 100

Number is not equal to 10, 50 or 100

Nested switch case statement

We can use as many switch statement as we want inside a switch statement. Such type of statements is called nested switch case statements. Consider the following example.

  1. #include <stdio.h>  
  2. Int main () {  
  3.  
  4.   Int i = 10;  
  5.   Int j = 20;  
  6.   
  7.   Switch(i) {  
  8.     
  9.      Case 10:   
  10.         Printf("the value of i evaluated in outer switch: %d\n",i);  
  11.      Case 20:  
  12.         Switch(j) {  
  13.            Case 20:  
  14.               Printf("The value of j evaluated in nested switch: %d\n",j);  
  15.         }  
  16.   }  
  17.     
  18.   Printf("Exact value of i is : %d\n", i );  
  19.   Printf("Exact value of j is : %d\n", j );  
  20.   
  21.   Return 0;  
  22. }  

Output

The value of i evaluated in outer switch: 10

The value of j evaluated in nested switch: 20

Exact value of i is : 10

Exact value of j is : 20

If-else vs switch

What is an if-else statement?

An if-else statement in C programming is a conditional statement that executes a different set of statements based on the condition that is true or false. The 'if' block will be executed only when the specified condition is true, and if the specified condition is false, then the else block will be executed.

Syntax of if-else statement is given below:

  1. If(expression)  
  2. {  
  3.    // statements;  
  4. }  
  5. Else  
  6. {  
  7.   // statements;  
  8. }  

What is a switch statement?

A switch statement is a conditional statement used in C programming to check the value of a variable and compare it with all the cases. If the value is matched with any case, then its corresponding statements will be executed. Each case has some name or number known as the identifier. The value entered by the user will be compared with all the cases until the case is found. If the value entered by the user is not matched with any case, then the default statement will be executed.

Syntax of the switch statement is given below:

  1. Switch(expression)  
  2. {  
  3.  Case constant 1:  
  4.  // statements;  
  5.  Break;  
  6.  Case constant 2:  
  7.  // statements;  
  8.  Break;  
  9.  Case constant n:  
  10.  // statements;  
  11.  Break;  
  12. Default:  
  13. // statements;  
  14. }  

Similarity b/w if-else and switch

Both the if-else and switch are the decision-making statements. Here, decision-making statements mean that the output of the expression will decide which statements are to be executed.

Differences b/w if-else and switch statement

The following are the differences between if-else and switch statement are:

  • Definition

If-else

Based on the result of the expression in the 'if-else' statement, the block of statements will be executed. If the condition is true, then the 'if' block will be executed otherwise 'else' block will execute.

Switch statement

The switch statement contains multiple cases or choices. The user will decide the case, which is to execute.

  • Expression

If-else

It can contain a single expression or multiple expressions for multiple choices. In this, an expression is evaluated based on the range of values or conditions. It checks both equality and logical expressions.

Switch

It contains only a single expression, and this expression is either a single integer object or a string object. It checks only equality expression.

  • Evaluation

If-else

An if-else statement can evaluate almost all the types of data such as integer, floating-point, character, pointer, or Boolean.

Switch

A switch statement can evaluate either an integer or a character.

  • Sequence of Execution

If-else

In the case of 'if-else' statement, either the 'if' block or the 'else' block will be executed based on the condition.

Switch

In the case of the 'switch' statement, one case after another will be executed until the break keyword is not found, or the default statement is executed.

  • Default Execution

If-else

If the condition is not true within the 'if' statement, then by default, the else block statements will be executed.

Switch

If the expression specified within the switch statement is not matched with any of the cases, then the default statement, if defined, will be executed.

  • Values

If-else

Values are based on the condition specified inside the 'if' statement. The value will decide either the 'if' or 'else' block is to be executed.

Switch

In this case, value is decided by the user. Based on the choice of the user, the case will be executed.

  • Use

If-else

It evaluates a condition to be true or false.

Switch

A switch statement compares the value of the variable with multiple cases. If the value is matched with any of the cases, then the block of statements associated with this case will be executed.

  • Editing

If-else

Editing in 'if-else' statement is not easy as if we remove the 'else' statement, then it will create the havoc.

Switch

Editing in switch statement is easier as compared to the 'if-else' statement. If we remove any of the cases from the switch, then it will not interrupt the execution of other cases. Therefore, we can say that the switch statement is easy to modify and maintain.

  • Speed

If-else

If the choices are multiple, then the speed of the execution of 'if-else' statements is slow.

Switch

The case constants in the switch statement create a jump table at the compile time. This jump table chooses the path of the execution based on the value of the expression. If we have a multiple choice, then the execution of the switch statement will be much faster than the equivalent logic of 'if-else' statement.

Let's summarize the above differences in a tabular form.

 

If-else

Switch

Definition

Depending on the condition in the 'if' statement, 'if' and 'else' blocks are executed.

The user will decide which statement is to be executed.

Expression

It contains either logical or equality expression.

It contains a single expression which can be either a character or integer variable.

Evaluation

It evaluates all types of data, such as integer, floating-point, character or Boolean.

It evaluates either an integer, or character.

Sequence of execution

First, the condition is checked. If the condition is true then 'if' block is executed otherwise 'else' block

It executes one case after another till the break keyword is not found, or the default statement is executed.

Default execution

If the condition is not true, then by default, else block will be executed.

If the value does not match with any case, then by default, default statement is executed.

Editing

Editing is not easy in the 'if-else' statement.

Cases in a switch statement are easy to maintain and modify. Therefore, we can say that the removal or editing of any case will not interrupt the execution of other cases.

Speed

If there are multiple choices implemented through 'if-else', then the speed of the execution will be slow.

If we have multiple choices then the switch statement is the best option as the speed of the execution will be much higher than 'if-else'.

 


The looping can be defined as repeating the same process multiple times until a specific condition satisfies. There are three types of loops used in the C language. In this part of the tutorial, we are going to learn all the aspects of C loops.

Why use loops in C language?

The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so that instead of writing the same code again and again, we can repeat the same code for a finite number of times. For example, if we need to print the first 10 natural numbers then, instead of using the printf statement 10 times, we can print inside a loop which runs up to 10 iterations.

Advantage of loops in C

1) It provides code reusability.

2) Using loops, we do not need to write the same code again and again.

3) Using loops, we can traverse over the elements of data structures (array or linked lists).

Types of C Loops

There are three types of loops is given below:

  1. Do while
  2. While
  3. For

Do-while loop

The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is used when it is necessary to execute the loop at least once (mostly menu driven programs).

The syntax is given below:

  1. Do{  
  2. //code to be executed  
  3. }while(condition);  

While loop

The while loop in c is to be used in the scenario where we don't know the number of iterations in advance. The block of statements is executed in the while loop until the condition specified in the while loop is satisfied. It is also called a pre-tested loop.

The syntax of while loop in c language is given below:

  1. While(condition){  
  2. //code to be executed  
  3. }  

For loop

The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance.

The syntax of for loop in c language is given below:

  1. For(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

Do while

The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of several parts of the statements. The do-while loop is mainly used in the case where we need to execute the loop at least once. The do-while loop is mostly used in menu-driven programs where the termination condition depends upon the end user.

do while loop syntax

The syntax of the C language do-while loop is given below:

  1. Do{  
  2. //code to be executed  
  3. }while(condition);  

Example 1

  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. Void main ()  
  4. {  
  5.    Char c;  
  6.    Int choice,dummy;    
  7.    Do{  
  8.    Printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");  
  9.    Scanf("%d",&choice);  
  10.    Switch(choice)  
  11.    {  
  12.        Case 1 :   
  13.        Printf("Hello");   
  14.        Break;  
  15.        Case 2:    
  16.        Printf("Javatpoint");  
  17.        Break;  
  18.        Case 3:  
  19.        Exit(0);   
  20.        Break;  
  21.        Default:   
  22.        Printf("please enter valid choice");      
  23.    }  
  24.    Printf("do you want to enter more?");   
  25.    Scanf("%d",&dummy);  
  26.    Scanf("%c",&c);  
  27.    }while(c=='y');  
  28. }  

Output

1. Print Hello

2. Print Javatpoint

3. Exit

1

Hello

Do you want to enter more?

y

 

1. Print Hello

2. Print Javatpoint

3. Exit

2

Javatpoint

Do you want to enter more?

n

Flowchart of do while loop

flowchart of do while loop in c language

do while example

There is given the simple program of c language do while loop where we are printing the table of 1.

  1. #include<stdio.h>  
  2. Int main(){    
  3. Int i=1;      
  4. Do{    
  5. Printf("%d \n",i);    
  6. i++;    
  7. }while(i<=10);   
  8. Return 0;  
  9. }     

Output

1

2

3

4

5

6

7

8

9

10

Program to print table for the given number using do while loop

  1. #include<stdio.h>  
  2. Int main(){    
  3. Int i=1,number=0;    
  4. Printf("Enter a number: ");    
  5. Scanf("%d",&number);    
  6. Do{    
  7. Printf("%d \n",(number*i));    
  8. i++;    
  9. }while(i<=10);    
  10. Return 0;  
  11. }    

Output

Enter a number: 5

5

10

15

20

25

30

35

40

45

50

Enter a number: 10

10

20

30

40

50

60

70

80

90

100

Infinitive do while loop

The do-while loop will run infinite times if we pass any non-zero value as the conditional expression.

  1. Do{  
  2. //statement  
  3. }while(1);  

While loop

While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance.

Syntax of while loop in C language

The syntax of while loop in c language is given below:

  1. While(condition){  
  2. //code to be executed  
  3. }  

Flowchart of while loop in C

flowchart of c while loop

Example of the while loop in C language

Let's see the simple program of while loop that prints table of 1.

  1. #include<stdio.h>  
  2. Int main(){    
  3. Int i=1;      
  4. While(i<=10){      
  5. Printf("%d \n",i);      
  6. i++;      
  7. }  
  8. Return 0;  
  9. }    

Output

1

2

3

4

5

6

7

8

9

10

Program to print table for the given number using while loop in C

  1. #include<stdio.h>  
  2. Int main(){    
  3. Int i=1,number=0,b=9;    
  4. Printf("Enter a number: ");    
  5. Scanf("%d",&number);    
  6. While(i<=10){    
  7. Printf("%d \n",(number*i));    
  8. i++;    
  9. }    
  10. Return 0;  
  11. }   

Output

Enter a number: 50

50

100

150

200

250

300

350

400

450

500

Enter a number: 100

100

200

300

400

500

600

700

800

900

1000

Properties of while loop

  • A conditional expression is used to check the condition. The statements defined inside the while loop will repeatedly execute until the given condition fails.
  • The condition will be true if it returns 0. The condition will be false if it returns any non-zero number.
  • In while loop, the condition expression is compulsory.
  • Running a while loop without a body is possible.
  • We can have more than one conditional expression in while loop.
  • If the loop body contains only one statement, then the braces are optional.

Example 1

  1. #include<stdio.h>  
  2. Void main ()  
  3. {  
  4.    Int j = 1;  
  5.    While(j+=2,j<=10)  
  6.    {  
  7.        Printf("%d ",j);   
  8.    }  
  9.    Printf("%d",j);  
  10. }  

Output

3 5 7 9 11

Example 2

  1. #include<stdio.h>  
  2. Void main ()  
  3. {  
  4.    While()  
  5.    {  
  6.        Printf("hello Javatpoint");   
  7.    }  
  8. }  

Output

Compile time error: while loop can't be empty 

Example 3

  1. #include<stdio.h>  
  2. Void main ()  
  3. {  
  4.    Int x = 10, y = 2;  
  5.    While(x+y-1)  
  6.    {  
  7.        Printf("%d %d",x--,y--);  
  8.    }  
  9. }  

Output

Infinite loop

Infinitive while loop in C

If the expression passed in while loop results in any non-zero value then the loop will run the infinite number of times.

  1. While(1){  
  2. //statement  
  3. }  

 

For loop

The for loop in C language is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like the array and linked list.

Syntax of for loop in C

The syntax of for loop in c language is given below:

  1. For(Expression 1; Expression 2; Expression 3){  
  2. //code to be executed  
  3. }  

Flowchart of for loop in C

for loop in c language flowchart

C for loop Examples

Let's see the simple program of for loop that prints table of 1.

  1. #include<stdio.h>  
  2. Int main(){  
  3. Int i=0;        
  4. For(i=1;i<=10;i++){      
  5. Printf("%d \n",i);      
  6. }     
  7. Return 0;  
  8. }     

Output

1

2

3

4

5

6

7

8

9

10

C Program: Print table for the given number using C for loop

  1. #include<stdio.h>  
  2. Int main(){  
  3. Int i=1,number=0;      
  4. Printf("Enter a number: ");    
  5. Scanf("%d",&number);    
  6. For(i=1;i<=10;i++){      
  7. Printf("%d \n",(number*i));    
  8. }    
  9. Return 0;  
  10. }    

Output

Enter a number: 2

2

4

6

8

10

12

14

16

18

20

Enter a number: 1000

1000

2000

3000

4000

5000

6000

7000

8000

9000

10000

Properties of Expression 1

  • The expression represents the initialization of the loop variable.
  • We can initialize more than one variable in Expression 1.
  • Expression 1 is optional.
  • In C, we can not declare the variables in Expression 1. However, It can be an exception in some compilers.

Example 1

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.    Int a,b,c;  
  5.    For(a=0,b=12,c=23;a<2;a++)  
  6.    {  
  7.        Printf("%d ",a+b+c);  
  8.    }  
  9. }  

Output

35 36

Example 2

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.    Int i=1;  
  5.    For(;i<5;i++)  
  6.    {  
  7.        Printf("%d ",i);  
  8.    }  
  9. }  

Output

1 2 3 4

Properties of Expression 2

  • Expression 2 is a conditional expression. It checks for a specific condition to be satisfied. If it is not, the loop is terminated.
  • Expression 2 can have more than one condition. However, the loop will iterate until the last condition becomes false. Other conditions will be treated as statements.
  • Expression 2 is optional.
  • Expression 2 can perform the task of expression 1 and expression 3. That is, we can initialize the variable as well as update the loop variable in expression 2 itself.
  • We can pass zero or non-zero value in expression 2. However, in C, any non-zero value is true, and zero is false by default.

Example 1

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.    Int i;  
  5.    For(i=0;i<=4;i++)  
  6.    {  
  7.        Printf("%d ",i);  
  8.    }  
  9. }  

Output

0 1 2 3 4

Example 2

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.    Int i,j,k;  
  5.    For(i=0,j=0,k=0;i<4,k<8,j<10;i++)  
  6.    {  
  7.        Printf("%d %d %d\n",i,j,k);  
  8.        j+=2;  
  9.        k+=3;  
  10.    }  
  11. }  

Output

0 0 0

1 2 3

2 4 6

3 6 9

4 8 12 

Example 3

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.    Int i;  
  5.    For(i=0;;i++)  
  6.    {  
  7.        Printf("%d",i);  
  8.    }  
  9. }  

Output

Infinite loop

Properties of Expression 3

  • Expression 3 is used to update the loop variable.
  • We can update more than one variable at the same time.
  • Expression 3 is optional.

Example 1

  1. #include<stdio.h>  
  2. Void main ()  
  3. {  
  4.    Int i=0,j=2;  
  5.    For(i = 0;i<5;i++,j=j+2)  
  6.    {  
  7.        Printf("%d %d\n",i,j);  
  8.    }  
  9. }  

Output

0 2

1 4

2 6

3 8

4 10   

Loop body

The braces {} are used to define the scope of the loop. However, if the loop contains only one statement, then we don't need to use braces. A loop without a body is possible. The braces work as a block separator, i.e., the value variable declared inside for loop is valid only for that block and not outside. Consider the following example.

  1. #include<stdio.h>  
  2. Void main ()  
  3. {  
  4.    Int i;  
  5.    For(i=0;i<10;i++)  
  6.    {  
  7.        Int i = 20;  
  8.        Printf("%d ",i);  
  9.    }  
  10. }  

Output

20 20 20 20 20 20 20 20 20 20  

Infinitive for loop in C

To make a for loop infinite, we need not give any expression in the syntax. Instead of that, we need to provide two semicolons to validate the syntax of the for loop. This will work as an infinite for loop.

  1. #include<stdio.h>  
  2. Void main ()  
  3. {  
  4.    For(;;)  
  5.    {  
  6.        Printf("welcome to javatpoint");  
  7.    }  
  8. }  

Nested Loops in C

C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Let's observe an example of nesting loops in C.

Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.

Syntax of Nested loop

  1. Outer_loop  
  2. {  
  3.    Inner_loop  
  4.   {  
  5.         // inner loop statements.  
  6.   }  
  7.       // outer loop statements.  
  8. }  

Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while' loop.

Nested for loop

The nested for loop means any type of loop which is defined inside the 'for' loop.

  1. For (initialization; condition; update)   
  2. {  
  3.    For(initialization; condition; update)  
  4.    {  
  5.           // inner loop statements.  
  6.    }  
  7.    // outer loop statements.  
  8. }  

Example of nested for loop

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.   Int n;// variable declaration  
  5.   Printf("Enter the value of n :");  
  6.   // Displaying the n tables.  
  7.   For(int i=1;i<=n;i++)  // outer loop  
  8.   {  
  9.       For(int j=1;j<=10;j++)  // inner loop  
  10.       {  
  11.           Printf("%d\t",(i*j)); // printing the value.  
  12.       }  
  13.       Printf("\n");  
  14.   }  

Explanation of the above code

  • First, the 'i' variable is initialized to 1 and then program control passes to the i<=n.
  • The program control checks whether the condition 'i<=n' is true or not.
  • If the condition is true, then the program control passes to the inner loop.
  • The inner loop will get executed until the condition is true.
  • After the execution of the inner loop, the control moves back to the update of the outer loop, i.e., i++.
  • After incrementing the value of the loop counter, the condition is checked again, i.e., i<=n.
  • If the condition is true, then the inner loop will be executed again.
  • This process will continue until the condition of the outer loop is true.

Output:

Nested Loops in C

Nested while loop

The nested while loop means any type of loop which is defined inside the 'while' loop.

  1. While(condition)  
  2. {  
  3.    While(condition)  
  4.    {  
  5.         // inner loop statements.  
  6.    }  
  7. // outer loop statements.  
  8. }  

Example of nested while loop

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.   Int rows;  // variable declaration  
  5.   Int columns; // variable declaration  
  6.   Int k=1; // variable initialization  
  7.   Printf("Enter the number of rows :");  // input the number of rows.  
  8.   Scanf("%d",&rows);  
  9.   Printf("\nEnter the number of columns :"); // input the number of columns.  
  10.   Scanf("%d",&columns);  
  11.      Int a[rows][columns]; //2d array declaration  
  12.      Int i=1;  
  13.   While(i<=rows) // outer loop  
  14.   {  
  15.       Int j=1;  
  16.      While(j<=columns)  // inner loop  
  17.       {  
  18.           Printf("%d\t",k);  // printing the value of k.  
  19.           k++;   // increment counter  
  20.           j++;  
  21.       }  
  22.       i++;  
  23.       Printf("\n");  
  24.   }  
  25. }  

Explanation of the above code.

  • We have created the 2d array, i.e., int a[rows][columns].
  • The program initializes the 'i' variable by 1.
  • Now, control moves to the while loop, and this loop checks whether the condition is true, then the program control moves to the inner loop.
  • After the execution of the inner loop, the control moves to the update of the outer loop, i.e., i++.
  • After incrementing the value of 'i', the condition (i<=rows) is checked.
  • If the condition is true, the control then again moves to the inner loop.
  • This process continues until the condition of the outer loop is true.

Output:

Nested Loops in C

Nested do..while loop

The nested do..while loop means any type of loop which is defined inside the 'do..while' loop.

  1. Do  
  2. {  
  3.   Do  
  4.  {   
  5.      // inner loop statements.  
  6.   }while(condition);  
  7. // outer loop statements.  
  8. }while(condition);  

Example of nested do..while loop.

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.  /*printing the pattern 
  5.     ******** 
  6.     ******** 
  7.     ******** 
  8.     ******** */  
  9. Int i=1;  
  10. Do           // outer loop  
  11. {  
  12.    Int j=1;  
  13.    Do       // inner loop  
  14.   {  
  15.      Printf("*");  
  16.      j++;  
  17.   }while(j<=8);  
  18.    Printf("\n");  
  19.    i++;  
  20.     }while(i<=4);  
  21. }  

Output:

Nested Loops in C

Explanation of the above code.

  • First, we initialize the outer loop counter variable, i.e., 'i' by 1.
  • As we know that the do..while loop executes once without checking the condition, so the inner loop is executed without checking the condition in the outer loop.
  • After the execution of the inner loop, the control moves to the update of the i++.
  • When the loop counter value is incremented, the condition is checked. If the condition in the outer loop is true, then the inner loop is executed.
  • This process will continue until the condition in the outer loop is true.

Infinite Loop in C

What is infinite loop?

An infinite loop is a looping construct that does not terminate the loop and executes the loop forever. It is also called an indefinite loop or an endless loop. It either produces a continuous output or no output.

When to use an infinite loop

An infinite loop is useful for those applications that accept the user input and generate the output continuously until the user exits from the application manually. In the following situations, this type of loop can be used:

  • All the operating systems run in an infinite loop as it does not exist after performing some task. It comes out of an infinite loop only when the user manually shuts down the system.
  • All the servers run in an infinite loop as the server responds to all the client requests. It comes out of an indefinite loop only when the administrator shuts down the server manually.
  • All the games also run in an infinite loop. The game will accept the user requests until the user exits from the game.

We can create an infinite loop through various loop structures. The following are the loop structures through which we will define the infinite loop:

  • For loop
  • While loop
  • Do-while loop
  • Go to statement
  • C macros

For loop

Let's see the infinite 'for' loop. The following is the definition for the infinite for loop:

  1. For(; ;)  
  2. {  
  3.    // body of the for loop.  
  4. }  

As we know that all the parts of the 'for' loop are optional, and in the above for loop, we have not mentioned any condition; so, this loop will execute infinite times.

Let's understand through an example.

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.   For(;;)  
  5.   {  
  6.     Printf("Hello javatpoint");  
  7.   }  
  8. Return 0;  
  9. }  

In the above code, we run the 'for' loop infinite times, so "Hello javatpoint" will be displayed infinitely.

Output

Infinite Loop in C

While loop

Now, we will see how to create an infinite loop using a while loop. The following is the definition for the infinite while loop:

  1. While(1)  
  2. {  
  3.   // body of the loop..  
  4. }  

In the above while loop, we put '1' inside the loop condition. As we know that any non-zero integer represents the true condition while '0' represents the false condition.

Let's look at a simple example.

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.  Int i=0;  
  5.  While(1)  
  6.  {  
  7.      i++;   
  8.      Printf("i is :%d",i);  
  9.  }  
  10. Return 0;  
  11. }  

In the above code, we have defined a while loop, which runs infinite times as it does not contain any condition. The value of 'i' will be updated an infinite number of times.

Output

Infinite Loop in C

Do..while loop

The do..while loop can also be used to create the infinite loop. The following is the syntax to create the infinite do..while loop.

  1. Do  
  2. {  
  3.    // body of the loop..  
  4. }while(1);  

The above do..while loop represents the infinite condition as we provide the '1' value inside the loop condition. As we already know that non-zero integer represents the true condition, so this loop will run infinite times.

Goto statement

We can also use the goto statement to define the infinite loop.

  1. Infinite_loop;  
  2. // body statements.  
  3. Goto infinite_loop;  

In the above code, the goto statement transfers the control to the infinite loop.

Macros

We can also create the infinite loop with the help of a macro constant. Let's understand through an example.

  1. #include <stdio.h>  
  2. #define infinite for(;;)  
  3. Int main()  
  4. {  
  5.   
  6.  Infinite  
  7.  {  
  8.      Printf("hello");  
  9.  }  
  10.  
  11.    Return 0;  
  12. }  

In the above code, we have defined a macro named as 'infinite', and its value is 'for(;;)'. Whenever the word 'infinite' comes in a program then it will be replaced with a 'for(;;)'.

Output

Infinite Loop in C

Till now, we have seen various ways to define an infinite loop. However, we need some approach to come out of the infinite loop. In order to come out of the infinite loop, we can use the break statement.

Let's understand through an example.

  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4. Char ch;  
  5. While(1)  
  6. {  
  7.     Ch=getchar();  
  8.     If(ch=='n')  
  9.     {  
  10.         Break;  
  11.     }  
  12.     Printf("hello");  
  13. }  
  14. Return 0;  
  15. }  

In the above code, we have defined the while loop, which will execute an infinite number of times until we press the key 'n'. We have added the 'if' statement inside the while loop. The 'if' statement contains the break keyword, and the break keyword brings control out of the loop.

Unintentional infinite loops

Sometimes the situation arises where unintentional infinite loops occur due to the bug in the code. If we are the beginners, then it becomes very difficult to trace them. Below are some measures to trace an unintentional infinite loop:

  • We should examine the semicolons carefully. Sometimes we put the semicolon at the wrong place, which leads to the infinite loop.
  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4. Int i=1;  
  5. While(i<=10);  
  6. {  
  7. Printf("%d", i);  
  8. i++;  
  9. }  
  10. Return 0;  
  11. }  

In the above code, we put the semicolon after the condition of the while loop which leads to the infinite loop. Due to this semicolon, the internal body of the while loop will not execute.

  • We should check the logical conditions carefully. Sometimes by mistake, we place the assignment operator (=) instead of a relational operator (= =).
  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4. Char ch='n';  
  5. While(ch='y')  
  6. {  
  7. Printf("hello");  
  8. }  
  9. Return 0;  
  10. }  

In the above code, we use the assignment operator (ch='y') which leads to the execution of loop infinite number of times.

  • We use the wrong loop condition which causes the loop to be executed indefinitely.
  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.  For(int i=1;i>=1;i++)  
  5.  {  
  6.      Printf("hello");  
  7.  }  
  8. Return 0;  
  9. }  

The above code will execute the 'for loop' infinite number of times. As we put the condition (i>=1), which will always be true for every condition, it means that "hello" will be printed infinitely.

  • We should be careful when we are using the break keyword in the nested loop because it will terminate the execution of the nearest loop, not the entire loop.
  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.  While(1)  
  5.  {  
  6.      For(int i=1;i<=10;i++)  
  7.      {  
  8.          If(i%2==0)  
  9.          {  
  10.              Break;  
  11.          }  
  12.      }  
  13.  }  
  14.    Return 0;  
  15. }  

In the above code, the while loop will be executed an infinite number of times as we use the break keyword in an inner loop. This break keyword will bring the control out of the inner loop, not from the outer loop.

  • We should be very careful when we are using the floating-point value inside the loop as we cannot underestimate the floating-point errors.
  1. #include <stdio.h>  
  2. Int main()  
  3. {  
  4.  Float x = 3.0;  
  5. While (x != 4.0) {  
  6.  Printf("x = %f\n", x);  
  7.  x += 0.1;  
  8. }  
  9.    Return 0;  
  10. }  

In the above code, the loop will run infinite times as the computer represents a floating-point value as a real value. The computer will represent the value of 4.0 as 3.999999 or 4.000001, so the condition (x !=4.0) will never be false. The solution to this problem is to write the condition as (k<=4.0).

Break statement

The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. The break statement in C can be used in the following two scenarios:

  1. With switch case
  2. With loop

Syntax:

  1. //loop or switch case   
  2. Break;  

Flowchart of break in c

c language break statement flowchart

Example

  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. Void main ()  
  4. {  
  5.    Int i;  
  6.    For(i = 0; i<10; i++)  
  7.    {  
  8.        Printf("%d ",i);  
  9.        If(i == 5)  
  10.        Break;  
  11.    }  
  12.    Printf("came outside of loop i = %d",i);  
  13.      
  14. }  

Output

0 1 2 3 4 5 came outside of loop i = 5

Example of C break statement with switch case

C break statement with the nested loop

In such case, it breaks only the inner loop, but not outer loop.

  1. #include<stdio.h>  
  2. Int main(){  
  3. Int i=1,j=1;//initializing a local variable    
  4. For(i=1;i<=3;i++){      
  5. For(j=1;j<=3;j++){    
  6. Printf("%d &d\n",i,j);    
  7. If(i==2 && j==2){    
  8. Break;//will break loop of j only    
  9. }    
  10. }//end of for loop    
  11. Return 0;  
  12. }    

Output

1 1

1 2

1 3

2 1

2 2

3 1

3 2

3 3

As you can see the output on the console, 2 3 is not printed because there is a break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 are printed because the break statement is used to break the inner loop only.

Break statement with while loop

Consider the following example to use break statement inside while loop.

  1. #include<stdio.h>  
  2. Void main ()  
  3. {  
  4.    Int i = 0;  
  5.    While(1)  
  6.    {  
  7.        Printf("%d  ",i);  
  8.        i++;  
  9.        If(i == 10)  
  10.        Break;   
  11.    }  
  12.    Printf("came out of while loop");  
  13. }  

Output

0  1  2  3  4  5  6  7  8  9  came out of while loop 

Break statement with do-while loop

Consider the following example to use the break statement with a do-while loop.

  1. #include<stdio.h>  
  2. Void main ()  
  3. {  
  4.   Int n=2,i,choice;  
  5.   Do  
  6.   {  
  7.       i=1;  
  8.       While(i<=10)  
  9.       {  
  10.           Printf("%d X %d = %d\n",n,i,n*i);  
  11.           i++;  
  12.       }  
  13.       Printf("do you want to continue with the table of %d , enter any non-zero value to continue.",n+1);  
  14.       Scanf("%d",&choice);  
  15.    If(choice == 0)  
  16.       {  
  17.           Break;  
  18.       }  
  19.       n++;  
  20.   }while(1);  
  21. }  

Output

2 X 1 = 2

2 X 2 = 4

2 X 3 = 6

2 X 4 = 8

2 X 5 = 10

2 X 6 = 12

2 X 7 = 14

2 X 8 = 16

2 X 9 = 18

2 X 10 = 20

Do you want to continue with the table of 3 , enter any non-zero value to continue.1

3 X 1 = 3

3 X 2 = 6

3 X 3 = 9

3 X 4 = 12

3 X 5 = 15

3 X 6 = 18

3 X 7 = 21

3 X 8 = 24

3 X 9 = 27

3 X 10 = 30

Do you want to continue with the table of 4 , enter any non-zero value to continue.0

Continue statement

The continue statement in C language is used to bring the program control to the beginning of the loop. The continue statement skips some lines of code inside the loop and continues with the next iteration. It is mainly used for a condition so that we can skip some code for a particular condition.

Syntax:

  1. //loop statements  
  2. Continue;  
  3. //some lines of the code which is to be skipped  

Continue statement example 1

  1. #include<stdio.h>  
  2. Void main ()  
  3. {  
  4.    Int i = 0;   
  5.    While(i!=10)  
  6.    {  
  7.        Printf("%d", i);   
  8.        Continue;   
  9.        i++;  
  10.    }  
  11. }  

Output

Infinite loop

Continue statement example 2

  1. #include<stdio.h>  
  2. Int main(){  
  3. Int i=1;//initializing a local variable       
  4. //starting a loop from 1 to 10    
  5. For(i=1;i<=10;i++){      
  6. If(i==5){//if value of i is equal to 5, it will continue the loop    
  7. Continue;    
  8. }    
  9. Printf("%d \n",i);    
  10. }//end of for loop    
  11. Return 0;  
  12. }    

Output

1

2

3

4

6

7

8

9

10

As you can see, 5 is not printed on the console because loop is continued at i==5.

C continue statement with inner loop

In such case, C continue statement continues only inner loop, but not outer loop.

  1. #include<stdio.h>  
  2. Int main(){  
  3. Int i=1,j=1;//initializing a local variable    
  4. For(i=1;i<=3;i++){      
  5. For(j=1;j<=3;j++){    
  6. If(i==2 && j==2){    
  7. Continue;//will continue loop of j only    
  8. }    
  9. Printf("%d %d\n",i,j);    
  10. }    
  11. }//end of for loop    
  12. Return 0;  
  13. }    

Output

1 1

1 2

1 3

2 1

2 3

3 1

3 2

3 3

As you can see, 2 2 is not printed on the console because inner loop is continued at i==2 and j==2.

Goto statement

The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the program control to a predefined label. The goto statment can be used to repeat some part of the code for a particular condition. It can also be used to break the multiple loops which can't be done by using a single break statement. However, using goto is avoided these days since it makes the program less readable and complecated.

Syntax:

  1. Label:   
  2. //some part of the code;   
  3. Goto label;  

Goto example

Let's see a simple example to use goto statement in C language.

  1. #include <stdio.h>  
  2. Int main()   
  3. {  
  4.  Int num,i=1;   
  5.  Printf("Enter the number whose table you want to print?");   
  6.  Scanf("%d",&num);  
  7.  Table:   
  8.  Printf("%d x %d = %d\n",num,i,num*i);  
  9.  i++;  
  10.  If(i<=10)  
  11.  Goto table;    
  12. }  

Output:

Enter the number whose table you want to print?10

10 x 1 = 10

10 x 2 = 20

10 x 3 = 30

10 x 4 = 40

10 x 5 = 50

10 x 6 = 60

10 x 7 = 70

10 x 8 = 80

10 x 9 = 90

10 x 10 = 100

When should we use goto?

The only condition in which using goto is preferable is when we need to break the multiple loops using a single statement at the same time. Consider the following example.

  1. #include <stdio.h>  
  2. Int main()   
  3. {  
  4.  Int i, j, k;    
  5.  For(i=0;i<10;i++)  
  6.  {  
  7.    For(j=0;j<5;j++)  
  8.    {  
  9.      For(k=0;k<3;k++)  
  10.      {  
  11.        Printf("%d %d %d\n",i,j,k);  
  12.        If(j == 3)  
  13.        {  
  14.          Goto out;   
  15.        }  
  16.      }  
  17.    }  
  18.  }  
  19.  Out:   
  20.  Printf("came out of the loop");   
  21. }  

0 0 0

0 0 1

0 0 2

0 1 0

0 1 1

0 1 2

0 2 0

0 2 1

0 2 2

0 3 0

Came out of the loop

 

Reference Books

1 “Thinking in C++”, Volume 1 and 2 by Bruce Eckel, Chuck Allison, Pearson

Education

2 “Mastering C++”, 1/e by Venugopal, TataMcGraw Hill.

3 “Object Oriented Programming with C++”, 3/e by E. Balaguruswamy, Tata

McGraw Hill.

4 “Starting Out with Object Oriented Programming in C++”, by Tony Gaddis,

Wiley India.

 


Index
Notes
Highlighted
Underlined
:
Browse by Topics
:
Notes
Highlighted
Underlined