FAQ: Learn Java: Loops - Iterating Over Arrays and ArrayLists

This community-built FAQ covers the “Iterating Over Arrays and ArrayLists” exercise from the lesson “Learn Java: Loops”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Java

FAQs on the exercise Iterating Over Arrays and ArrayLists

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in Language Help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

Looking for motivation to keep learning? Join our wider discussions in Community

Learn more about how to use this guide.

Found a bug? Report it online, or post in Bug Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

import java.util.ArrayList;

class CalculateTotal {
  
  public static void main(String[] args) {
    
    ArrayList<Double> expenses = new ArrayList<Double>();
    expenses.add(74.46);
    expenses.add(63.99);
    expenses.add(10.57);
    expenses.add(81.37);
    
    double total = 0;
    
    // Iterate over expenses
    for(int i = 0; i < expenses.size(); i++) {
      total = total + expenses.get(i);
    }
    
    System.out.println(total);
    
  }
  
}

The output is:
230.39

I have verified the total by hand and with a calculator as well

4 Likes
import java.util.ArrayList;

class CalculateTotal {
  
  public static void main(String[] args) {
    
    ArrayList<Double> expenses = new ArrayList<Double>();
    expenses.add(74.46); // [0]
    expenses.add(63.99); // [1]
    expenses.add(10.57); // [2]
    expenses.add(81.37); // [3]
    
    double total = 0;
    
    // Iterate over expenses
    for (int i = 0; i < expenses.size(); i++) {
        total += expenses.get(i);
    }
    
    System.out.println(total);
    
  }
  
}

Hello,

Can anyone explain the second instruction (2. Inside the for loop, add the item’s value to total.) and how they knew to use a compound assignment operator or the syntax " total = total + expenses.get(i); " I see that others have figured this out but I want to know the reasoning behind it because I don’t think I’m understanding what instruction 2 is asking for. Check out my code below and if someone could break this down to me it would be greatly appreciated.

import java.util.ArrayList;

class CalculateTotal {

public static void main(String args) {

ArrayList<Double> expenses = new ArrayList<Double>();

expenses.add(74.46);

expenses.add(63.99);

expenses.add(10.57);

expenses.add(81.37);



double total = 0;



// Iterate over expenses

for (int i = 0; i < expenses.size(); i++){

 total = expenses.get(i); 

 expenses.set(i, total + 1);

    

System.out.println(total);

}

}

}

The output is the list of arrays and the lesson is asking, Did you add the current item to total ?

2 Likes

Hi there,
I have the same doubt!

1 Like

alright,so where you are going wrong is when you are trying to set the total value you have got during each loops added with 1 to the i’th index of the arraylist i,e at this line expenses.set(i, total+1). therefore for that line of code total value+1 is being assigned to the new value for the i’th index of the list.

As of for how what its asking is the total sum of all expenses. And for that total = total + expenses.get(i) does the work. how? initially total is assigned to 0.0, so during the first loop - total = 0.0 + 74.46 happens and total takes the value 74.46. In 2nd loop - total = 74.46 (from previous loop) + 63.99 happens. similarly at 3rd loop - total = 138.45 (74.46+63.99) + 10.57 is whats happening. finally at 4th loop - total = 149.02 + 81.37. during the next loop, it breaks cause i(=4) isnot < expenses.size() and you get your final value for total (230.39)

hope this makes sense

2 Likes

Hello everyone. This is my code. I hope this code can be useful for any of you guys who find trouble to do the given task. Also, I wanna thank @runtimeterror because of the explanation for the second instruction! :grinning:

import java.util.ArrayList;

import java.text.DecimalFormat; //placing 2DP

class CalculateTotal {

public static void main(String args) {

DecimalFormat df = new DecimalFormat("###.###"); 



ArrayList<Double> expenses = new ArrayList<Double>();

expenses.add(74.46);

expenses.add(63.99);

expenses.add(10.57);

expenses.add(81.37);



double total = 0;

for(int i = 0; i < expenses.size(); i++){

  total += expenses.get(i);

   System.out.println("Sum for each i : " +df.format(total)); //df.format for placing 2 DP.


}

System.out.println("\n So, the total is : " + total);

}

}

The output will be:

Sum for each i: 74.46 //0+74.46 = 74.46
Sum for each i: 138.45 //74.46 +63.99 = 138.45
Sum for each i: 149.02
Sum for each i: 230.39

So, the total is: 230.39

I believe the fourth block of code in the instructions has a mistake:

int i = 0; // initialize counter
 
while (i < secretCode.size()) {
  int num = secretCode.get(i);
  secretCode.set(i, num + i);
  i++; // increment the while loop
}

Shouldn’t this read as follows?

int i = 0; // initialize counter
 
while (i < secretCode.size()) {
  int num = secretCode.get(i);
  secretCode.set(i, num + 1);
  i++; // increment the while loop
}
1 Like

Thought I would point out a typo.

Traversing through an ArrayList with a while loop would look like this:

int i = 0; 
// initialize counter 
while (i < secretCode.size()) { 
    int num = secretCode.get(i);  
    secretCode.set(i, num + i);  
    // should be 'secretCode.set(i, num + 1);'
    i++; 
    // increment the while loop
}

Heyy so my doubt is fairly basic I cant seem to figure out.
for (int i = 0; i < secretCode.length; i++) {
** // Increase value of element value by 1**
** secretCode[i] += 1;**
}
This was the cde given as the example.
Why is it necessary to the secretcode[i]+=1 incrementation since we are already incrementing by 1 in the for loop. It is redundant and if its not, like someone help me figure out the specific tasks of both the incrementation?
Thanks in advance. :grinning_face_with_smiling_eyes: :grin:

1 Like

what is the total += expenses.get(i) doing exactly.

I have a similar question, basically this example is not clear to me, I tried executing it and it throws an error.
What else is missing?

public class Main {
public static void main(String args) {

for (int i = 0; i < secretCode.length; i++) {

// Increase value of element value by 1
secretCode[i] += 1;
}
}
}

Main.java:4: error: cannot find symbol
for (int i = 0; i < secretCode.length; i++) {
^
symbol: variable secretCode
location: class Main
Main.java:6: error: cannot find symbol
secretCode[i] += 1;
^
symbol: variable secretCode
location: class Main
2 errors

#get-help

Hello,

Struggling to understand the for loop example for ArrayList:

for (int i = 0; i < expenses.size(); i++) {
int num = secretCode.get(i);
secretCode.set(i, num + 1);
}

Why do you have to initialise a variable inside of the for loop for ArrayLists?

For those of you who are curious, I found a workaround. Initialising a ‘num’ inside of the for loop confuses me, although apparently using it makes the code more readable.

Instead you can simplify the code, see here:

for (int i = 0; i < expenses.size(); i++) {
secretCode.set(i, secretCode.get(i) + 1);
}