ball 4789466 640 Loops in C programming

Loops in C programming


Loops in C programming language are used to solve programming problems that require repetition logic. They allow us to write
statements once and get the computer to execute them repeatedly as long as some condition is true.

While Loops

A while loop repeatedly executes a block of code while a given condition is true. It stops when the condition evaluates to false.

Syntax:

while (condition){
statement to be executed repeatedly as long as the condition is true;
}

For example:

#include <stdio.h>

int main(){
	
	int i = 10;
	
	while(i){  // the loop continues until i = 0, because 0 evaluates to false
		
		printf("%d\n", i);
		i--;               // decrement i
		}
	
	return 0;
}

/** Output **
10
9
8
7
6
5
4
3
2
1
**/

Here is how the code works:

  • i is equal to 10 initially. The loop evaluates the value of i. In C, every non-zero value evaluates to true.
  • the value of i is printed and then decremented to 9 by (i--).
  • the cycle repeats again and again until the value of i becomes 0. When the condition is tested 0 evaluates to false and the loop immediately terminates.

Lets us look at another example:

#include <stdio.h>

int main(){
	
	int i = 10;
	
	while(i>3){  // the loop continues while i>3, otherwise the conditions evaluates false
		
		printf("%d\n", i);
		i--;
		}
	
	return 0;
}

/** Output **
10
9
8
7
6
5
4
**/

One application of the while loop is when creating a program that calculates the highest common factor(HCF) or greatest common divisor (GCD) of two positive integers m and n. For example:

#include <stdio.h>

int main(){
	
	int m;
	int n;
	
	printf("Enter the first integer: \n");
	scanf("%d", &m);
	
	printf("Enter the second integer: \n");
	scanf("%d", &n);
	
	printf("The highest common factor of %d and %d ", m,n);
	
	while(n){
		int tmp = n;  
		n = m%n;
		m = tmp;
	}
	printf("is %d", m);
	
	return 0;
}

Do-While Loops

Syntax:

do
{
statement to be executed;
}
while (condition);

It works virtually the same way as the while loop except that the statement is executed before the condition is evaluated. This guarantees that the statement will be executed at least once even if the condition is false. For example:

#include <stdio.h>

int main(){
	
	int i = 10;
	
	do {
		printf("%d\n", i);
		i--;
	} while(i);
	
	return 0;
}

/** Output **
10
9
8
7
6
5
4
3
2
1
**/

As another example, lets us create a code that takes a non-negative integer value and prints it in reverse order.

#include <stdio.h>

int main(){
	
	int a = 78913032;
	
	do {
		printf("%d", a % 10);
		a /= 10;
		
	} while (a != 0);
	
	return 0;
}

The use of a do-while loop allows 0 to be printed without needing extra code.


For Loops

Syntax:

for (expr1; expr2; expr3){
statement to be executed;
}

The working of a for loop is equivalent to that of a while loop with the following arrangement:

expr1;
while (expr2) {
statement;
expr3;
}

For example:

#include <stdio.h>

int main(){
	
	printf("Output from a for loop: \n");
	for (int i = 2; i < 10; i++){
		printf("%d\n", i);
	}
	
	printf("\nOutput from an equivalent while loop: \n");
	int i = 2;
	while(i < 10){
		printf("%d\n", i);
		i++;
	}
	
	return 0;
}

/** Output **
Output from a for loop: 
2
3
4
5
6
7
8
9

Output from an equivalent while loop: 
2
3
4
5
6
7
8
9
**/

Break keyword in loops

Besides breaking out of a switch construct, the break keyword is also used to used to branch out of a while, do-while, or for loop. For example:

#include <stdio.h>

int main(){
	
	int i = 10;
	
	while(i){  // the loop continues until i = 0, because 0 evaluates to false
		
		printf("%d\n", i);
		i--;              // decrement i
		
		if(i == 5){
			break;
		}
		
	}
	
	return 0;
}

/** Output **
10
9
8
7
6
**/

In the example above, if the value of i reaches 5, the execution will branch out of the loop. The break statement is very important if the loop has a tendency of becoming infinity. For example:

#include <stdio.h>

int main(){
	
	int i = 10;
	
	while(1){  // an infinite loop because the condition will never be false
		
		printf("%d\n", i);
		i++;              // increment i
		
		if(i == 25){
			break;
		}
		
	}
	
	return 0;
}

/** Output **
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
**/

It is important to note that the break keyword will only branch out of the inner-most enclosing block, and transfers the execution to the first statement outside the block.

For example, in a nested while loop of syntax shown below:

while (expression) {
while (expression) {
if (expression)
break;
statements
}
statements
}

The break will terminate the inner while loop and proceed to execute the statements of the outer while loop.

Continue keyword in loops

The continue statement causes transfer of execution immediately to the conditional test. For example:

#include<stdio.h>

int main(){
	
    int i;
    for(i = 10; i < 20; i++){
    	if(i % 2 == 0)
    	continue;                 // if i % 2 == 0 skip to the next iteration
    	printf("%d\n",i);
    }
return 0;
    
}

/** Output **
11
13
15
17
19
**/

goto unconditional jump in C

goto is a very simple jump control keyword used in C programming language used to immediately and unconditionally jump to another line of code. The use of goto requires you to place a label at another point in your program where the goto jump will land. The label consists of a name followed by a colon (:) on a line by itself.

After placing the label, you can then type goto label; at the desired point for your jump. The code execution will then jump from the goto and continue executing beginning at label.

#include <stdio.h>

int main(){
	
	int response;
	
	printf("Welcome to Sytech Financial Institute. Pliz choose your desired service: \n");
	printf("1. Apply for a loan. \n");
	printf("2. Payback your loan. \n");
	printf("3. Check your balance. \n");
	printf("4. Exit. \n");
	
	scanf("%d", &response);
	
	if (response == 4) goto Exit; // jump to label Exit if response = 4
	
	if (response == 1) printf("Loan granted. \n");
	else if (response == 2) printf("Payment received. \n");
	else printf("Your balance is $1:00. \n"); 
	
	// label Exit 
	Exit:
	printf("Thank you for doing business with us and have a nice day.");
	
	return 0;
}

In the example above, if the input is 4, an unconditional jump is performed to label Exit.

However, excessive use of gotos can in not advisable because it creates unreadable, unmaintainable. There are rare cases where a goto statement is useful, for example when breaking out of a deeply nested loop. A break will not work in a nested loop because it can only escape one loop into an enclosing loop. A goto comes in handy here because of its ability to jump completely outside the loop.

Breaking out of deeply nested loops is possible without the use of goto but it often involves the creation of extra variables that may make the resulting code far less readable than it would be with goto.