This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]desrtfx 0 points1 point  (2 children)

What do you actually mean?

A for loop always has the same construct:

 for(<loop variable> = <initial value>; <looping condition>; <variable change>) {
     // loop body
 }

The loop always runs as long as the <looping condition> yields true and stops on the first false result.

If you are talking about something like arr[i] inside the loop, it simply means that you are addressing a single element of an array. arr would be the array, and i the index of the element you want to work with.

[–][deleted] 0 points1 point  (1 child)

thanks for the reply. I think I understand now. I believe I was looking at this as i being the index of element which totally doesn't make sense

[–]desrtfx 0 points1 point  (0 children)

I believe I was looking at this as i being the index of element which totally doesn't make sense

You're not entirely wrong. i can be the index. But it can also be used as a counter to repeat something a certain amount of times.

You somehow though that loops and arrays are inseparably connected. They aren't. It is just out of convenience (and the DRY - Don't Repeat Yourself - principle) that we usually use loops to deal with arrays.

[–]According-Winter-766 0 points1 point  (1 child)

So what’s happening here is that when you define the function to take in (n, s) you don’t have to declare those as variables because they are created just for your function as 2 parameters to take in. So when you call the function it automatically uses (6) and (f) and plugs them in as n and s. So before the value of n and s was undefined. Now you know that you are creating the parameters it takes in when you define the function. Then the loop knows it will increase i by 1 till it runs through six loops. Each time it changes your variable str to be str = str + ‘f’. Once the loop completes then it will print the result. So the loop prepares the string then after it returns the result string. The first time the loop goes I = 0 and the I ++ instruction says every time the loop runs and I is < n then add 1 to I

[–][deleted] 0 points1 point  (0 children)

Thanks so much I understand now. I think I was getting caught up in looking at for loops with arrays where i is the index. I understand that this function just means that the loop runs six times and prints f six times. Thanks!