Real examples of using for loops

Hi!

In order to gain a greater understanding, I’d like to ask if someone could present me some real exampels of when a for loop is used?
Because right now I know how to compose one and I understand what the loop itself is doing in terms of executing code, but when is it actually useful?

Thank you in advance!

Looping is a fundamental component of program logic. There have been looping algorithms since the advent of computers, and more so, since the advance of mathematics and calculus.

Yes, in Maths…

arithmetic_series_sigma_notation
image found in Google search

That is the language of looping in math, in particular the summation of a series of repeated operations where k changes in each one, and k makes a sequence that starts with 0 and progresses thru to 199.

How do we replicate that with a for loop?

We will need an accumulator so define a variable and give it an initial value of 0.

let s = 0

The k variable will be defined in the loop’s parameters.

for (let k = 0; ;) {}

Above we initialize it to zero, as the illustration shows.

We know from above that the upper limit of k is 199, so our continuation condition will control that…

for (let k = 0; k < 200; ) {}

Finally we need to increment k on each iteration so, like the above, it is always different and follows a sequence.

for (let k = 0; k < 200; k++) {

}

We’ve set the stage for our loop; all it needs now is a code body, the steps that will be carried out with each iteration. In this case the step is simple… Add 7 + 2 * k to s.

for (let k = 0; k < 200; k++) {
    s += 7 + 2 * k;
}

The final summation will be referenced by s.

console.log(s)    //  41200
1 Like

You can also use it if you want to find people in a database that meets x requirements. Instead of needing to import everybody data into the program manually the loop can do it for you.

1 Like

A bit like, “tomorrow’s use of it”, wouldn’t you say? Let’s not get ahead of ourselves, if we really wish to benefit the learner.

1 Like

You can use loops in all sorts of scenarios.
Some examples might be;
searching through a chunk of data
sorting a chunk of data
testing items in a chunk of data
performing some mathematical function on a selection of numbers (say you needed to add 10% to the prices in your inventory or you’re looking to test which numbers in a list are prime)
you can even use them to control program flow. e,g. you could set up a loop around a password input to give the user so many attempts at getting it right.
and,
many,
many
more.

Don’t worry, you’ll soon be using them plenty enough in one form or another.

1 Like

Ah, okay, I see! Thank you very much for your help!

Thank you for your explanation!

I understand how the loop works, I think it was very well taught in the course (Learn JavaScript).
But what I’d like to know is in what situations += 7 + 2 * k; needs to run from k = 0 to k = 199.

As in, what is a very common example when you need to use a for loop.

I suspect it may be painfully obvious and that I need to learn more about it.

Here’s a similar example:

Let’s say you want to write a script to add a discount to items in a store. The prices of items might be in an array:

var prices = [
  12.99,
  35.85,
  17.99,
  28.33,
];

You can use a for loop to multiply each item by a discount:

// multiplying by 0.75 makes a 25% discount
var discount = 0.75;

// prices.length is equal to 4,
// because there are 4 items in the array.
// however, indices of an array are zero-indexed,
// so be careful.
for(let i = 0; i < prices.length; i++) {

  // multiplies the original price by 'discount' to
  prices[i] *= discount;

}

You could also print the new values to the console, with a dollar sign for each one:

for(let i = 0; i < prices.length; i++) {
  console.log("$" + prices[I]);
}
1 Like

Loops are so ubiquitous it’s hard to imagine any use cases that are not common. Without them a few thousand lines of code would quickly become a few million and we would be writing spaghetti code into perpetuity. Nothing would ever get done.

Simple use cases might be iterating over a string, character by character, or over a sentence, word by word, or a number, digit by digit.

const num = 123456789

What is the sum of the digits? For this we can use a simple loop and iterate over the string representation the number.

const nums = num.toString(10)
let s = 0
for (const n of nums) {
  s += n
}
console.log(s)    //  45

Throughout your learning you will be exposed to all manner of use cases. We don’t have to catalog those uses. They become self-evident in nearly every problem we attempt to solve.

In short, the for loop is particularly useful when we know the lower and upper bound. This would be a definitive use case since we can iterate from lower to upper (or upper to lower). It is not that well suited to indefinite cases where the bounds are not known. We can make an infinite loop with for but our teachers might ask us, ‘why?’

for day of week

for month of year

for student in students

&c.
1 Like

Thank you!! This was the kind of example that I was looking for!

This is what I suspected as well, but it’s nice to have some examples just to go through from time to time.
Thank you for your help!

1 Like

you’re welcome! Glad to help :smiley: