For Loops In C.
Hello guys, today we're going to go through for loops in c.
They do seem confusing when you first see them but they can be effortless to use when you understand how to use them. Since we already introduced C in the past articles, you can check them out here.
Now below is a standard structure for the for-loop code in C.
#include<stdio.h>
int main(void) {
for(int i = 0; i < 5; i++){
printf("\n%d\n",i);
}
return 0;
}
Don't worry if you had difficulties trying to figure out what it does. Here's how it works.
int i = 0;
Basically, what this does is, it creates a variable called "i", and assigns it to "0".
i < 5;
This is the condition that needs to be fulfilled in order for the loop to continue. For example, the condition above is that "i" should be less than 5 before the loop can execute. That is, when "i" is greater than or equal to "5", the code inside of the loop will not execute.
i++ or ++i;
This is where we increment(increase) the value of "i" until the condition is false. Consider it as an updating function that the for loop must pass through.
Now, for all the times that the condition will be true, the code inside the for-loop will run, like the above code, the code will run 5 times because the condition will be true five times.
I don't want to use to many complex examples here but for the sake of practice, let's write a program adds numbers from 1 to n(where n is a number given by the user).
As always, I will explain what I'm doing with the comments in the code.
#include<stdio.h>
int main(void) {
int n = 0;
int sum = 0;
printf("Enter a number: ");
scanf("%d",&n);
for(int i = 0; i <= n; i++){
sum = sum + i; //this basically takes the old value of the sum and adds it to the new value of 'i'.
printf("\n %d \n",sum);
}
return 0;
}
//Now if the user were to enter 10 as n, you would get ten outputs and so on
And that's how the code is to look for the program to work. And to finally explain how the C for-loop works(stage to stage), see the image below.
![Stage By Stage Execution Of A For Loop](https://cdn.hashnode.com/res/hashnode/image/upload/v1670433101912/e2nZlYcJa.png align="middle")
So with that done, until next time.
Peace.
Subscribe to my newsletter
Read articles from Tifu Kelison directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Tifu Kelison
Tifu Kelison
I am a Graphic Designer and Front-end developer and UI Designer(still in process) from Cameroon. I am the founder and CEO of the Design Archive. I love to write and as it turns out, hashnode is just the community I needed to start doing that. I at the time of writing this bio, I'm in my first year of university that's why you see writing articles about C. If you ever what to chat, feel free to hit me up on any social media platform.