Tech With Tim Logo
Go back

For Loops

For Loops

In programming we have something called a loop. A loop will continue to run (or loop) while a certain condition is satisfied. We can use a for loop when we want to loop (or repeat something) a known amount of times.

When we set up a for loop it looks something like this:

for (int x = 0; x < 5; x++){
    System.out.println(x);
}

//This will print
0
1
2
3
4

We can see that when we define our loop we need to include 3 pieces of information in the brackets.

  1. Declare a counter (x = 0), this is what will be changing each run of the loop.
  2. A condition (x < 5), the loop will only run while this condition is true.
  3. An increment or decrement (x++). This is how much our counter will change by each loop.

In the example above our counter variable is x and it starts at a value of 0. Our condition is x < 5, meaning that the loop will continue to run while x is less than 5. Our increment is x++ which means x will increase by one each loop. Stepping through our loop we can see that once our loop has ran 5 times our x value is = to 5 meaning that we will not print 5 because x is not less than it.

Using For Loops on Arrays

Some of you may have noticed that running the following code does not produce the expected output.

int[] x = {1,5,6};
System.out.println(x);

We probably expect to see some kind output telling us the elements (1,5,6) of the array. But instead we see the following. kuva_2023-05-01_184114532.png This is actually the memory address of the array and it most likely means nothing to us.

To print all of the elements of an array to the screen we can use a for loop!

int[] x = {1,5,6};

for(int i = 0; i < x.length; i++){
    System.out.println(x[i]);
}

// We are looping through each index of x [0,2] and printing it to the screen

//Now we get
1
5
6

Examples

Here is a few examples to help you understand for loops.

String[] strs = {"hello", "my", "name", "is"};

for (int i = 0; i < 3; i++){
	if (strs[i].equals("my")){
        System.out.println("I found the string at index " + i);  // This will tell us what index "my" is at, in this case 1
	}
}

//OUTPUT
I found the string at index 1
for (int i = -5; i <= 35; i+=5){
	System.out.println(i);
}

// OUTPUT
-5
0
5
10
15
20
25
30
35
for (int x = 10; x > 0; x--){
	System.out.println(x);
}

// Output
10
9
8
7
6
5
4
3
2
1
Design & Development by Ibezio Logo