Table of Contents
Loops is a technique to repeatedly perform the same set of instructions until a specific condition is satisfied. It makes the code less complex and more efficient.
C language has three looping statements, namely…
In the while statement, firs,t a counter is initialized which undergoes a test condition. If the condition evaluates to true, then the body of the loop gets executed. Hence, while loop runs until the condition becomes false.
Syntax:
Its syntax is-
initialize counter; while (test condition) { //Body of the loop }
Example:
Write a C Prgram to print all the first 10 multiples of three using while Loop.
#include<stdio.h> int main() { int i,m; i=1; printf("The first ten multiples of 3 are\n"); while(i<=10) { m=3*i; printf("%d\n",m) i++; } return 0; }
Output:
The first ten multiples of 3 are 3 6 9 12 15 18 21 24 27 30
In the do-while statement, first the instructions in the do block are executed and then the condition in the while block is tested. So, the do while statement will at least execute the code once, even if the condition is false at the very first time.
Syntax:
Its syntax is-
do { //body of the loop } while (test condition);
Example:
Write a C program to print the cube of the number first five natural numbers using while loop.
#include<stdio.h> int main() { printf("The cube of first 10 number are\n"); int i; do { printf("%d\n",i*i*i); i++; } while(i<=5); return 0; }
Output:
The cube of first 10 number are 1 8 27 64 125
The for loop is the most used repetition statement in almost all programming languages. The reason for its popularity is that it does three jobs at once.
It initializes the counter, tests the condition and increments/decrements the counter at the same time.
This is also the key difference which makes for loop more acceptable over the while and do while loop for most programmers.
Syntax:
Its syntax is-
for (initialize counter; test condition; increment/decrement counter;) { //body of for loop }
Example:
Write a C program to print the square of the first 10 natural number using for loop.
#include<stdio.h> int main() { int i; printf("The square of first 10 natural numbers are\n"); for(i=10; i>0; i--) { printf("%d\n",i*i); } return 0; }
Output:
The square of first 10 natural numbers are 1 4 9 16 25 36 49 64 81 100
What’s next?
Hope this tutorial has helped you to understand the main difference between while, do-while and for loop in C/C++ along with syntax and C programming example.
Now practise solving coding questions using different loops.
You can find more programming questions here for practice.
Happy Programming!