Code Point Blog
Iam presenting here ,all type of knowledge if you want to interest knowing about any topic then click below thumbnail view button and knowing.
Loop :In C programming, Loops are used to repeat the block of code without repeatation.it is used for code reusability.
C language provides three main types of loops:
1.do While loop
2.while loop
3.for Loop
4.Nexted for loop ( parts of for loop )
1.do-while loop :The do-while loop is similar to the while loop but ensures that the code block is executed at least once before checking the loop condition.
#include <stdio.h>
int main() {
int count = 1;
do {
printf("Iteration %d\n", count);
count++;
} while (count <= 5);
return 0;
}
2.while loop :The while loop continues executing a block of code as long as a specified condition is true.
#include <stdio.h>
int main() {
int count = 1;
while (count <= 5)
{ printf("Iteration %d\n", count);
count++;
} return 0;
}
3.for loop :The for loop is used to execute a block of code for a specified number of iterations.
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++)
{ printf("Iteration %d\n", i);
} return 0;
}
4. Nexted for loop :A nested for loop in the C programming language is a situation where one for loop is placed inside another for loop. This construct allows you to perform more complex iterations by iterating over multiple levels of data structures, such as arrays, matrices, or nested data collections. The syntax fora nested for loop is as follows:
for (initialization; condition; increment) {
(Outer loop code)
for (initialization; condition; increment) {
(Inner loop code)
}
( More code for the outer loop )
}
The nested for loop contains an outer loop and an inner loop. Each time the outer loop runs, the inner loop executes completely. The inner loop will execute all its iterations for each iteration of the outer loop.
Here's an example of a nested for loop to print a multiplication table from 1 to 5:
#include <stdio.h>
int main() {
int rows = 5;
int cols = 10;
for (int i = 1; i <= rows; i++){
for (int j=1; j <=cols; j++) {
printf("%4d", i * j);
}
printf("\n");
} return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 912 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
In this example, the outer loop iterates from 1 to 'rows' (5), and for each iteration of the outer loop, the inner loop iterates from 1 to 'cols' (10). The printf statement inside the inner loop prints the multiplication table for each value of 'i' and 'j'. Nested for loops are widely used in scenarios where you need to traverse or process multidimensional data structures, perform matrix operations, or implement complex algorithms that require multiple iterations. As a fundamental programming concept.