Introduction
Loops help us repeat actions many times without writing the same code again and again.
Loops help us repeat actions many times without writing the same code again and again.
for (initialization; condition; update) { // code to repeat } while (condition) { // code to repeat } do { // code to repeat } while (condition);
The for loop is good when you know how many times to repeat.
The while loop repeats as long as the condition is true.
for loop.for (int i = 1; i <= 5; i++) { printf("%d\n", i); }
while loop.int i = 1; while (i <= 5) { printf("%d\n", i); i++; }
do-while loop, which runs the code at least once.int i = 1; do { printf("%d\n", i); i++; } while (i <= 5);
This program counts from 1 to 5 using a for loop and prints each number on a new line.
#include <stdio.h> int main() { printf("Counting from 1 to 5 using a for loop:\n"); for (int i = 1; i <= 5; i++) { printf("%d\n", i); } return 0; }
Loops save time and reduce mistakes by avoiding repeated code.
Always make sure your loop has a condition that will eventually stop it, or it will run forever.
Loops repeat code to do tasks many times easily.
Use loops when you want to repeat actions without writing the same code again.
int i;
for(i = 1; i <= 3; i++) {
printf("%d ", i);
}int i = 0;
for(i = 0; i < 5; i++)
printf("%d", i)
Pass the test and this pattern moves unknown