Introduction
In programming, loops are used to execute a set of instructions repeatedly as long as the given condition is true. The Do-While loop is used when we need to execute the block of code at least once, and then check the loop condition.
In this lab, we will create a Do-While Loop program in C that prints the numbers from 10 to 1 in descending order.
Create a new C file
Create a new file in the ~/project/ directory and name it main.c. We will write all our code in this file.
Include the necessary header files
In C programming language, we need to include the necessary header files for our program to work. In the first line of our main.c file, include the header file stdio.h which provides input/ output functions.
#include <stdio.h>
Write the main function
Next, we will write the main() function. The main() function is the entry point of our program.
int main()
{
// our code goes here
return 0;
}
Initialize the variable
Initialize the variable i to value 10 before we start the loop.
int i = 10;
Write the Do-While Loop
In this step, we will write the Do-While loop to print the values of i from 10 to 1.
do {
printf("i = %d\n", i);
i--; // decrement i by 1 at each iteration
} while (i >= 1);
The loop will execute the code block once before checking the loop condition. The loop will continue to execute as long as i is greater than or equal to 1.
Compile and run the Program
Save the program and open the terminal, navigate to the directory where your main.c file is located. Use the following command to compile the program:
gcc main.c -o program
This will create the executable file program in the same directory. Run the program using the following command:
./program
Verify the Output
On running the program, the output should be as follows:
i = 10
i = 9
i = 8
i = 7
i = 6
i = 5
i = 4
i = 3
i = 2
i = 1
Full Code
#include<stdio.h>
int main()
{
int i = 10;
do {
printf("i = %d\n", i);
i--; // decrement i by 1 at each iteration
} while (i >= 1);
return 0;
}
Summary
In this lab, we learned how to create a Do-While Loop program in C. A Do-While Loop is used when we want to execute the code block at least once before checking the loop condition. We also learned how to initialize a variable, write a Do-While loop and compile/run a C program in the terminal.



