What is a foreach loop used for in java? I get that it is used for iteration in arrays...whatever that means... Can it be used for finding the sum? Finding the largest element? Finding the smallest element? Finding out the average?
@TuringTest
I don't think I have a good understanding of this. I would assume it is like foreach in javascript and php, and you should be able to find the sum, largest and smallest element, and average with it. I'm not 100% though, so you best wait for someone more knowledgeable. The reason I could answer your other question is that the answer was the same for all programming languages. Here I'm not so sure.
You know when people say they're smiling online, and they're not really smiling?...well I'm still sitting here smiling.
I'm glad for that :)
you don't need for loop for any of those
In short, the answer to ALL of those questions is \(\color{green}{yes}\), if the data that you want to look through is in an array or Iterable object, I'm pretty sure. But lets just think about arrays at first. \(\huge\color{red}{\text{for loops}}\) I'm going to guess that you know what a for loop is. But, we can review briefly. You have a number, you test to see if the loop body is going to happen or not, and then you change that number. One of the simplest for loops just increments (by 1) from \(0\) until reaching the number just before, say 10. The loop will change the value like this: \(0\rightarrow1\rightarrow2\rightarrow3\rightarrow4\rightarrow5\rightarrow6\rightarrow7\rightarrow8\rightarrow9\) (but not (10) This is often done because arrays start at \(0\). The syntax: ``` for ( int i = 0; i < 10; ++i ) { // put the good stuff here } // for loop is finished ``` Tracing through it will help you understand. Do this: 1. Look at the assignment first (left statement in the parentheses). 2. Then look at the test (middle). \(\qquad\)If it's true, like \(0<10\), go to step 3. \(\qquad\)If it's false, go to step 6. 3. Execute the loop body. 4. Go to the update statement (right). 5. Repeat step 2. 6. Go to the end of the for loop, and start from there. Next, what is iterating?
Iterating through an array is actually really simple, and I won't spend as much time on it. \(\huge\color{red}{\text{Arrays}}\) And array is a whole bunch of elements, and their order is kept track of. An element might just be a number, like an `int`. But it could also be an object, in an array of objects. If you don't get that, don't worry. You're probably just not there yet. That might be a little ways off! But you can refer to the element at a specific spot with "subscript notation" in Java. Just know that the spots for elements start at 0. The numbers that refer to these spots should be called "indices," the plural form of "index" (like at the end of a book). So, for an array of three elements, you have \(\bbox[5pt, white, border:2pt solid black]{\text{element}\ 0} \bbox[5pt, white, border:2pt solid black]{\text{element}\ 1} \bbox[5pt, white, border:2pt solid black]{\text{element}\ 2}\) \(\uparrow\text{index is 0} ~~\uparrow\text{index is 1} ~~\uparrow\text{index is 2}\) And to get to an index, you use the array's name and the index. To get to element 0 of an array named "arr," you would use ``` arr [0]; // first element of "arr" ``` Now, a for loop can start from zero, and go through each next element by incrementing the number for the loop. But iterating is just the process of going to the next element. It's much simpler than modifying a number and using it to gain access! So!
\(\huge\color{red}{\text{for each}}\) Now you have a new, but similar loop. It iterates, going to the next element, and then the next. It's simple. First, you need the array name. We'll use "arr" again. Next, you need some name to refer to the element in that array within the for each loop. We'll call it "elem". And the whole thing looks like this: ``` for ( elem : arr ) { // some stuff } ``` There it is! It looks at "arr" from beginning to end - iterating. The element we're looking at through an iteration (the one time of these many times) is captured by "elem." \(\huge\color{green}{\text{Your Question}}\) Now, it's not too much of a stretch to be able to do all of those things you mentioned. Those are algorithms that you might like to think of! If you need a hand, let me know. Hopefully I'll be around.
Or to short form all that, "for each" is just the start of "For each element in the array." If you can remember that then there is a good chance you can remember how the(other)Eric has described it.
:) One more thing!! Umm..... \(\huge\color{red}{\text{for each: Correction}}\) The correct syntax is this: First, you need the array name. We'll use "arr" again. Next, you need some name to refer to the element in that array within the for each loop. We'll call it "elem". \(\large\color{red}{---------------------------}\) We also need the type of the element. I suppose that's so the iterator knows what it's doing. Let's say that the type of "elem" is "Element". \(\large\color{red}{---------------------------}\) And the whole thing looks like this: ``` for ( Element elem : arr ) { // some stuff } ```
ooh, I missed you forgot to type it.
I heard a great description of typing recently. It was in an Android class. It went something like this: Humans use types all the time. Imagine this story: The thing went into the thing and sat on the thing and it broke! It does not mean much because we have not been told the types. On the other hand, take this version: The man went into the room and sat on the chair and it broke! Makes much more sense! To this, I would add a little more. The types are generic. Man is a sub-type of person, where person is the generic type. A chair is pretty generic and could be all sorts of different chairs. Same with room. The computer, just like you, needs to know the type. If it does not, it gets confused.
Nice anecdote, @e.mccormick ! `The man went into the room and sat on the chair and it broke!` Now, can you tell me why the room broke?
Because it was not coded properly.
Obvoiusly!
Should've known.
Lol! You guys are funny. That is an excellent description @e.mccormick. So from what I've understood, any time we have arrays you can use the foreach loop. Right? @theEric But I still can't quite answer the question: It says: Identify and name which methods could be amended to work perfectly just by changing the for loop to a syntactically correct for-each loop From all the options there are only 4 that deal with arrays and they are: public static void loop7() { int[] numbers = {2,3,4,5,6,7,8,9,10}; int sum = 0; for (int i = 0; i < numbers.length; ++i) { sum = sum + numbers[i]; } System.out.println("The sum of the array is " + sum); } public static void loop8() { int[] numbers = {2,3,4,5,6,7,8,9,10,1}; int largest = 0; for(int i = 0; i < numbers.length; ++i) { if (numbers[i] > largest) largest = numbers[i]; } System.out.println("The largest element in the array is " + largest); } public static void loop9() { int[] numbers = {2,3,4,5,6,7,8,9,10,1}; int smallest = numbers[0]; for(int i = 1; i < numbers.length; ++i) { if (smallest > numbers[i]) smallest = numbers[i]; } System.out.println("The smallest element in the array is " + smallest); } public static void loop10() { int[] numbers = {10,10,10,10,20,5,5}; int average = 0; int total = 0; for(int i = 0; i < numbers.length; ++i) { total += numbers[i]; } average = total / numbers.length; System.out.println("The average of the values in the array is " + average); }
At first I was going to say all of the ones above...but that didn't really make sense...it felt wrong?
Okay! Well, in an intro class, I think you only need to worry about arrays. So here's what the for each loop does: 1. Start at the beginning 2. If you're not at the end of the array, go to the next element. If you are at the end of the array, go to step 4. 3. Repeat 2. 4. End the loop; you're done. I believe that only three of the four follow this process. So, which do you think they are? Look at what the for each loop does, and look at what the for loops are doing.
so would loop8 and loop9, be one of them? since we're trying to find the largest or smallest?
I wouldn't look at what the for loops are for, but I would look at how the for loops are set up!
Want another hint?
Yes Plzz
Alright, look at the two functions you mentioned. They're very similar in what they have to do. But they start out differently. Only one can use the for each loop without some further modification.
Hint: \(\it beginning\ to\ end\)
(of array)
I think it would be loop9, because in loop8 'int largest' has a fixed value of 0 at the start. Does that make any sense?
What is that first "it" that you mention? Is loop 9 okay to be a for each, or not?
(I think I know what you mean, I just want to be sure)
Sorry, my bad, I mean loop9 can be used as a foreach loop
Other one!
See, "loop8 ()" starts with a fixed 0, that's fine! However, "loop9 ()" looks into an index to start. That's the difference. The problem is the for loop of course. That's all the question really cared about. The for loop starts iterating from \(\it 1\)! That's the issue. The element at index \(1\) is not the beginning of the array. The for each loop would start at the beginning of the array.
I read somewhere that you can not use a foreach loop when comparing two arrays, in loop9, are we comparing the array with itself, which is also an array?
Well, you can use a for each loop, limitedly. I'll point out that it's sort of pointless, so that's a good thing you thought! The for each will only repeat as many times as there are elements in the array you iterate on. And you still have to create a variable to index into the second array, so it's pointless to use a for each loop instead of a for loop as far as I can think. But that isn't the issue with "loop9 ()". It's issues is that you have the for loop ``` for(int i = 1; i < numbers.length; ++i) ``` Where a for each loop would start from ` int i=0 `, the beginning. Like, ``` for(int i = 0; i < numbers.length; ++i) ```
Ooooh! I think I'm beginning to understand, since the for-each loop has to iterate for each element in the array, and in loop9 we aren't iterating all the elements (we're skipping out 0) it won't work. Did I get it? or am I still failing miserably at it? At this point plz note that I AM trying really hard to get it :/
Haha, no! That was spot on! And I think you might have said it better than I could! About all the elements and all :) Maybe I'll take a long time typing to scare you.... Nah, I'm glad you're putting forth an effort! And I'm glad it worked out!
PHEW! The "no!" really scared me. Thankyou so so much I reeeeaaally appreciate your patience
Oh! Haha! That was unintentional. You're very welcome! I think you're understanding for each loops fairly well, now. :) Exercises are helpful like that.
Or they should be! :P
true! true! Thankyou again. and now that the serious issues are finally resolved... Can I ask you a silly question, oh wait I just did. What's that grey boxy thing you put in your replies? it's so cool (Kindly overlook my highly childish tone)
Haha, no, that's cool! Are you talking about the ``` // boxes that highlight your code? // Liiiiike: int i = 5 - 2; // And allow for looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong lines? ``` Then you use three ` characters alone on a line above the code, and three on a line below. The character is that which shares a key with the tilde, "~", on many keyboards. ``` stuff ```
Copying from them works better than copying from a post otherwise, with the browser I'm using now.
Got it, thankyou you can ignore what comes next it'll just be me testing it out ```Hello```
Hey, wait, it didn't work!
Right! They need lines by themselves!
Funny thing is, I used them, forgot about them, and then tried ```this``` over and over!! Then I emailed a friendly guy and he helped.
``` stuff ```
``` stuff ``` I mean...
That would work, except that I put a space on the lines with the ``` .
``` Like this? ```
`a single one of those accent things will do inline boxing, but no highlighting`.... Example: ` int i = 5; `
``` // Bravo!! ```
What's the highlighting for?
`this sentence`
The highlighting just makes it easier to read sometimes. I don't know why it decides to highlight what it does. It's a syntactic highlighter, so it will highlight text based on syntax. ``` // Here, you see primitive data types highlighted int i; char c; boolean b; // Here, you see some variables among numbers i = ( 200 + i ) - 3 + x + y +10; // It just makes it a little easier to read ```
Sorry, it's a semantic highlighter!
But it's not tailored to only one language. ``` // C++ has the data type "bool", as its "boolean" bool b; // I don't know why it highlights string.... string; // And, if it's a keyword in some language, but you want to use it in Java String string = ""; // It still highlights it, even though it has no special meaning in Java. ```
I'm sure the other guys on here know more about it than I do!
thanks again, now I really must be going :)
Okay, take care!
The code quoting system also makes it as preformated text so spaces and returns do not get played with by the browser. This makes it able to be copied and pasted better as well as making sure that it does not line wrap the code at a time that is incorrect.
Cool, thanks!
I agree with all of your interesting explanations :)
If that was directed towards me, thank you @ElleCullen ! If not, then I agree! Those guys are cool :)
Join our real-time social learning platform and learn together with your friends!