Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

for
loop
c

Using for loops in C

Educative Answers Team

The need for loops

While solving certain programming problems, some blocks of code need to be executed repeatedly. The repetition of the same code until a particular condition is met justifies the need of for loops as a whole.

Syntax of a for loop

The for loop is a special kind of loop that only repeats the block of code it contains for a specific number of times. The number of repetitions is defined by a conditional statement within the loop. Let’s look at the syntax for declaring a loop to better understand how this works.

  for(controlVariable; condition; changingControl){
    //body of for loop
  }

Now let’s look at each section of the for loop:

  • The controlVariable is the variable defined that will be used to initialize the loop counter i.e. the number of times the loop will run.

  • The condition is the statement on the basis of which the loop will be evaluated. Given that the statement returns false, the loop will no longer run.

  • The changingControl is the statement that will either increment, decrement or change the controlVariable for the next loop run.

  • The curly braces, {}, contain the code block that is to be executed.

How does a for loop work?

The illustration below shows the life cycle of the for loop and how it evaluates statements to run itself

Now that we know why we need a for loop and how it works, lets look at an example to re-inforce what we have learnt!

Applying theory to example

#include <stdio.h>

int main() {
  // your code goes here
  int sum =0;
  for(int a=0;a<10;a++){
    sum= sum+a;
    printf("%d\n",sum);
    

  }
}
Within the for loop declaration in ( ), each part is separated by a ;

In the code above, let’s see which part is what:

  • Here the controlVariable is the int a = 0 declaration which defines the initializer value for the for loop.
  • The condition in this case is the a < 10 statement; if a is less than 5 the loop will continue to run, otherwise it will terminate.
  • changingControl is the expression a++ indicating that before the next run of the loop, increase the value of a by 1.
  • The body of the loop to be executed each time is the block of code that adds a to sum and then prints the value of sum.
  • This entire process of checking the condition and subsequent actions is repeated once the code body executes.

RELATED TAGS

for
loop
c
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring