What is Loop explain its type with example
In computer programming, a loop is a programming construct that allows you to execute a block of code repeatedly until a certain condition is met. There are several types of loops, each with its own specific use case.
Types of loops:-
While loop: This loop executes a block of code as long as the condition specified in the loop header is true.
Here's an example of a while loop:
while (x < 10) {
// code to be executed
x++;
}
This loop will continue to execute the code within the curly braces until the value of x is no longer less than 10. In this example, the loop increments the value of x by 1 each time it runs.
For loop: A for loop is used to execute a block of code a specific number of times.
Here's an example:
for (int i = 0; i < 10; i++) {
// code to be executed
}
This loop will execute the code within the curly braces 10 times. The variable i is initialized to 0, and the loop will continue to run as long as i is less than 10. Each time the loop runs, the value of i is incremented by 1.
Do-while loop: This loop is similar to the while loop, but it executes the code within the curly braces at least once, even if the condition specified in the loop header is false.
Here's an example:
do {
// code to be executed
} while (x < 10);
This loop will execute the code within the curly braces at least once, and will continue to execute as long as the value of x is less than 10.
These are the three most commonly used types of loops in programming. Each type of loop has its own specific use case, and choosing the right one for the task at hand is an important part of writing efficient, effective code.
0 Comments