For Loop in Programming
- The
for
loop is used when you know in advance how many times you want to execute the block of code. - It iterates over a sequence (e.g., a list, tuple, string, or range) and executes the block of code for each item in the sequence.
- The loop variable (
variable
) takes the value of each item in the sequence during each iteration.
Example:
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++)
cout << i << "\n";
return 0;
}
#include <stdio.h>
int main()
{
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
return 0;
}
public class Main {
public static void main(String[] args) {
// For loop to print numbers from 0 to 4
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
for i in range(5):
print(i)
// For loop to print numbers from 0 to 4
for (let i = 0; i < 5; i++) {
console.log(i);
}
Output
0 1 2 3 4
This prints the numbers 0 through 4.
Difference between For Loop and While Loop in Programming
Both for
loops and while
loops are control flow structures in programming that allow you to repeatedly execute a block of code. However, they differ in their syntax and use cases. It is important for a beginner to know the key differences between both of them.
Contact Us