do while loop syntax
The structure of the C programming language do-while loop is illustrated below:
do{
//code to be executed
}while(condition);
The components are divided into the following:
- The do keyword marks the beginning of the Loop.
- The code block within curly braces {} is the body of the loop, which contains the code you want to repeat.
- The while keyword is followed by a condition enclosed in parentheses . After the code block has been run, this condition is verified. If the condition is true , the loop continues else, the loop ends .
Working of do while Loop in C
Let's consider an illustration of the functioning of a do-while loop in the C programming language. In this instance, we shall develop a basic program that prompts the user to enter a password and continues to prompt until the correct password is entered.
Example
#include <stdio.h>
#include <string.h>
int main() {
char password[] = "secret";
char input[20];
do {
printf("Enter the password: ");
scanf("%s", input);
} while (strcmp(input, password) != 0);
printf("Access granted!\n");
return 0;
}
The program runs as follows:
- The following header files are included: <stdio.h> for standard input and output routines and <string.h> for string manipulation functions .
- The correct password is defined as a character array (char password) with the value "secret"
- After that, we define another character array input to store the user's input.
- The do keyword indicates that the code block included within the loop will be performed at least once.
- Using the printf function , we display a prompt requesting the user to input their password inside the Loop.
- Next, we read the user's input using the scanf function and store it in the input array .
- After reading the input , we use the strcmp function to compare the input with the correct password. If the strings are equal, the strcmp function returns 0. So, we continue looping as long as the input and the password are not equal.
- Once the correct password is entered, the loop terminates, and we print "Access granted!" using the printf function .
- After that, the program returns 0 to indicate successful execution.
Output:
Let us walk through a possible scenario:
Enter the password: 123
Enter the password: abc
Enter the password: secret
Access Granted!
Explanation:
In this scenario, the user first inputs incorrect passwords, such as "123" and "abc". The iteration continues to request user input until the accurate password "secret" is supplied. Upon successful entry of the correct password, the loop concludes, and the message "Access granted!" is shown.
Example of do while loop in C:
Example 1:
Here is a basic illustration of a "do-while" loop in C programming language that displays numbers ranging from 1 to 5:
Example
#include <stdio.h>
int main() {
inti = 1;
do {
printf("%d\n", i);
i++;
} while (i<= 5);
return 0;
}
Output:
1
2
3
4
5
Explanation:
In this instance, the code segment enclosed within the do loop will run a minimum of once, displaying integers ranging from 1 to 5. Following each iteration, the value of i is incremented, and the condition i<= 5 is assessed. If this condition remains true, the loop will persist; otherwise, it will cease execution.
Example 2:
Create a program that displays a multiplication table for a specified number using a do-while loop. The table should include multiples of the number up to a certain limit.
Example
#include<stdio.h>
intmain(){
inti=1,number=0;
printf("Enter a number: ");
scanf("%d",&number);
do{
printf("%d \n",(number*i));
i++;
}while(i<=10);
return 0;
}
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
Example 3:
Let's consider a program that displays the multiplication table of a specified number N utilizing a do...while Loop:
Example
#include <stdio.h>
int main() {
int N;
printf("Enter a number to generate its multiplication table: ");
scanf("%d", &N);
inti = 1;
do {
printf("%d x %d = %d\n", N, i, N * i);
i++;
} while (i<= 10);
return 0;
}
Output:
Let us say you enter the number 7 as input:
Please enter a number to generate its multiplication table: 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
The software computes and displays the multiplication chart for the number 7 spanning from 1 to 10.
Infinite do while loop
An infinite loop is a looping structure that continues endlessly due to a condition that always evaluates to true or because it lacks a stopping criterion. Below is an illustration of an infinite do...while loop in the C programming language:
Example
#include <stdio.h>
int main() {
inti = 1;
do {
printf("Iteration %d\n", i);
i++;
} while (1); // Condition is always true
return 0;
}
In this instance, the loop will continue to run endlessly as condition 1 always evaluates to true.
Output:
When the program is executed, you will observe a continuous output of "Iteration x", where x represents the sequential number of the iteration without halting.
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
... (and so on)
To halt a never-ending loop, typically you would employ a break statement inside the loop or an external condition that you can manage, like triggering a predefined key combination. In many desktop environments, pressing Ctrl+C can terminate the loop.
Nested do while loop in C
In the C programming language, let's consider a scenario involving a nested do...while loop. In this instance, we will develop a code that employs nested do...while loops to generate a numerical pattern.
Example
#include <stdio.h>
int main() {
int rows, i = 1;
printf("Enter the number of rows: ");
scanf("%d", &rows);
do {
int j = 1;
do {
printf("%d ", j);
j++;
} while (j <= i);
printf("\n");
i++;
} while (i<= rows);
return 0;
}
In this particular code, nested do...while loops are employed to produce a numerical pattern. The outer loop manages the row count, while the inner loop is responsible for generating the numbers within each row.
Output:
Let us say you input five as the number of rows:
Enter the number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Explanation:
In this instance, the software produces a numerical pattern arranged in a triangular format. The external loop goes through each row, while the internal loop goes through each row individually, displaying numbers starting from 1 up to the current row's number.
Difference between while and do while Loop
Here is a table illustrating the distinctions between the while loop and the do-while loop in C programming:
| Aspect | while loop | do-while loop |
|---|---|---|
| Syntax | while (condition) { ... } | do { ... } while (condition); |
| Loop Body Execution | Condition is checked before execution. | The body is executed before the condition. |
| First Execution | The condition must be true initially. | The body is executed at least once. |
| Loop Execution | May execute zero or more times. | Will execute at least once. |
| Example | while (i< 5) { printf("%d\n", i); i++; } | do { printf("%d\n", i); i++; } while (i< 5); |
| Common Use Cases | When the loop may not run at all. | When you want the loop to run at least once. |
While Loop: The loop body is executed before the condition is checked. If the condition is initially false , the loop may not execute.
The do-while loop ensures that the loop body runs at least once before evaluating the condition, thus ensuring the execution of a minimum of one iteration.
When a loop needs to iterate depending on a condition that might be false initially, the while loop is employed. Conversely, if a loop must execute at least once irrespective of the initial condition, the do-while loop is utilized.
Features of do while loop
The do-while loop in C has several fundamental characteristics that make it an effective programming technique in certain situations. The following are the significant characteristics of the do-while loop:
- Guaranteed Execution: Unlike other loop structures , the do-while oop ensures that the loop body is executed at least once. Because the condition is assessed after the loop body, the code within the loop is performed before the condition is verified.
- Loop after testing: The do-while loop is a post-tested loop which implies that the loop condition is assessed after the loop body has been executed. If the condition is true, the loop body is run once again. This behavior allows you to verify the condition for repetition before ensuring that a given activity is completed.
- Conditionally Controlled: The loop continues to execute as long as the condition specified after the while keyword remains true . When the condition evaluates to false , the loop is terminated, and control shifts to the sentence after the loop.
- Flexibility: The do-while loop may be utilized in several contexts. It is typically used in cases where a piece of code must be executed at least once, such as menu-driven programs, input validation, or repetitive computations .
- Nesting Capability: Similar to other loop constructs , the do-while loop can be nested inside other loops or control structures to create more complex control flow patterns. It allows for the creation of nested loops and the implementation of intricate repetitive tasks.
- Break and Continue: The break statement can be used within a do-while loop to terminate the loop execution and exit the loop prematurely. The continue statement can skip the remaining code in the current iteration and jump to the next iteration of the loop.
- Local Scope: Variables declared inside the do-while loop body have local scope and are accessible only within the loop block. They cannot be accessed outside the loop or by other loops or control structures.
- Infinite Loop Control: It is crucial to ensure that the loop's condition is eventually modified within the loop body . This modification is necessary to prevent infinite loops where the condition continually evaluates to true. Modifying the condition ensures that the loop terminates at some point.