Explain 'for loop' with suitable example.

 

A 'for loop' is a control flow statement in C that allows you to execute a block of code repeatedly based on a certain condition. The basic syntax of a 'for loop' in C is as follows:

css
for (initialization; condition; increment/decrement) { // code to be executed }

Here, initialization sets the initial value of the loop variable, condition specifies the condition for continuing the loop, and increment/decrement updates the value of the loop variable on each iteration.

For example, let's say you want to print the numbers from 1 to 10 using a 'for loop'. The C code for this would be:

arduino
#include <stdio.h> int main() { int i; for (i = 1; i <= 10; i++) { printf("%d\n", i); } return 0; }

In this code, we initialize the loop variable i to 1. The loop will continue as long as i is less than or equal to 10. On each iteration, i is incremented by 1 using the i++ statement. Inside the loop, we use the printf() function to print the current value of i on a new line.

When you run this program, you will get the following output:

1 2 3 4 5 6 7 8 9 10

So, this is an example of a 'for loop' in C that prints the numbers from 1 to 10.

Post a Comment

Previous Post Next Post