I need some help with this enhanced for loop. I want to understand the coding for a standard loop and while loop, please. Thanks.
public static int average(int...numbers) {
int total=0;
for(int x:numbers)
total+=x;
return total/numbers.length;
}
In your example int...numbers is the same as "int[] numbers"
So the for loop would have to iterate over that array.
for(int i=0; i < numbers.length ; i++)
{
int x=numbers[i]
...
}
Would be a direct replacement.
Your for loop is equivalent to:
for(int i=0;i<numbers.length;i++){
int x = numbers[i];
total+=x;
}
Each element is retrieved in order, and the code within the loop is executed for each element.
The first operation, int i=0; is executed upon entering the for loop, and only once.
The second operation, i<numbers.length is the condition which must be true for the for loop to continue. This can actually be any boolean expression. I do not advise making your boolean expression overly complicated, but be aware its possible. An example:
boolean continueSumming = true;
for(int i=0;i<numbers.length && continueSumming;i++){
if(i>9)
continueSumming=false;
}
This loop would only iterate for a maximum of 10 elements for example, as the continueSumming variable would be set to false at the 9th element (remember arrays are 0 indexed.)
The last operation, i++ is also executed each iteration. Here it increments i.
i could be called the sentinel variable here as it controls when the loops execution ends. More bonus trivia for you.
A while loop is simpler, it repeats until some condition is no longer true. This while loop is equivalent to your for loop.
int index = 0;
while(index < numbers.length) {
total += numbers[index];
index += 1;
}
Each element would be added to the total, and the loop would exit when index was greater than or equal to the length of the array. As each iteration of the while loop is incrementing the index by 1, it will be executed for each element.
While loops aren't normally used to iterate over arrays as for loop syntax is less verbose, and allows the sentinel variable i to fall out of scope, while the for loop syntax does not.
Assuming your question is "What would be the difference between using a for loop or a while loop to find the average of an array of numbers?", here you go.
for (x : y) is a loop which allows you to operate on every object in the array y by using the reference x.
In your example, int total=0; is the total for the average calculation.
for(int x:numbers) allows you to run code on every integer in numbers through the reference variable of x
total+=x; adds the current number the loop is processing to the total, as an average calculator should
total/numbers.length divides the total by the amount of numbers (objects in the array numbers) to be returned; gives the average.
A while loop loops through until a boolean value, statement, or condition is false.
William Morrison shows you how it's done, by using an integer to show which object the loop is processing, and making a condition which checks whether the next-to-be-processed object even exists - whether its index, or the integer, is out of bounds of numbers.length.
numbers[index] is the same as x in the for loop's case.
A standard loop would take the same sort of conditions the while loop does.
for (int index = 0; index < numbers.length; index = index + 1) {
total += x;
}
Hope this helps you understand looping more clearly!
Related
I have to write a method that returns/prints the odd numbers between 1 and 100, but I have to use another method, which checks whether a given integer is odd or not:
static boolean isOdd(int c) {
boolean d;
d = c % 2 != 0;
return d;
}
I'm guessing that I have to use either a for- or while-loop (probably can be done with both?), but I think what I'm really struggling with is "connecting" both methods. So the numbers actually run through isOdd() which determines whether they are odd.
I've tried these two options so far, but they're not working.
Option 1:
static void func1() {
int number = 1;
while (number < 100 && isOdd(number)) {
System.out.println(number);
number = number + 1;
}
}
Option 2:
static void func1() {
int i;
for (i = 1; i < 100; i++) {
isOdd(i);
}
System.out.println(i);
}
Your attempt #1 is closer to your goal ;)
you are right that you can use while and for (and probably other kinds of processing multiple numbers, but that just for the sake of completeness, forget it for now)
your println (or print) should be within the loop because you want to print more than just one number.
in you current attempt #1 you end your loop with the first odd number: 1 This doesn't count up very far ;)
So you have to use an if inside your loop where you check the result of isOdd(number) and only print if it's odd.
But the loop has only the upper bound limit as condition (number < 100) as you want to check all the numbers.
Smartass hint (try it only after your program works fine): if you count up by 2 instead by 1 (number = number + 2;), your program will only need half the time - and you could even skip the isOdd check ;-)
I'm guessing that I have to use either a for- or while-loop (probably can be done with both?)
Yes. for-loops are just syntactic sugar for special while-loops:
for (init_stmt; cond; incr_stmt) body_stmt;
is equivalent to
init_stmt;
while (cond) {
body_stmt;
incr_stmt;
}
Let's first write this using a for-loop.
for-loop
for (int i = 1; i < 100; i++)
if (isOdd(i))
System.out.println(i)
Note that we can (and should!) do the declaration of i as int in the for-loop initializer.
Now, we may translate this to an equivalent while-loop:
while-loop
int i = 1;
while (i < 100) {
if (isOdd(i))
System.out.println(i);
i++;
}
Mistakes in your attempts
Attempt 1
You've mistakenly included the check in the condition (rather than using it in an if inside the loop body); the first even number (2) will cause the loop to terminate.
Attempt 2
You're not even using the return value of isOdd here. You're unconditionally printing i after the loop has terminated, which will always be 100.
The ideal implementation
Ideally, you'd not be filtering the numbers; you'd directly be incrementing by 2 to get to the next number. The following loop does the job:
for (int i = 1; i < 100; i += 2)
System.out.println(i);
I have this for loop and I am preparing for an exam. I want to see how many times this loop executes.
without knowing the value of K and somevalue, how can we determine the number of times SMALL is printed. The book answer says it is K-1.
for(int i=2; i<= k; i++)
if(arr[i]< someValue)
System.out.println("SMALL");
If it were simply
for (int i = 0; i < k; i++) {
The loop would run k times since you are starting at 0 but not reaching k
So add 2 to the starting point you get k-2 times
add back in 1 because it is <= and you get k-1 times.
It tends to get a little less obvious when the increment isn't 1
Note: That is how many times the loop will execute. The number of times SMALL will print can't be determined without more information.
in this case somevalue doesn't matter, you can calculate the count of executed loop your self by using another variable, use this:
int count = 0;
for (int i = 2; i <= k; i++) {
if (arr[i] < someValue) {
System.out.println("SMALL");
}
count++;
}
System.out.println("this for loop executed: " + count + " times.");
The question needs more inputs because without the values of arr[] and somevalue, we cannot find the answer.
However, since the loop starts at 2 and runs till its equal to k, we can say that it will run till k times -1 (since loop starts 2 for a <= condition instead of the usual 1), which translates to k-1 executions of the loop.
Still it doesn't guarantee the number of times "SMALL" will be printed. That is only possible if all values in the array arr are less than somevalue
I want to make a for loop that adds by 1 every other iteration, as long as it doesn't reach a value higher than 5.
I've tried with nested forloops but it's still nothing like it.
E.g.
Given a value x=10 or x=3.
For i<x && i<=5; i++
and this is where i want a value y, to be added with +1 every other (2th) time it runs the loop.
Thanks in advance.
You can do this for example by adding a second variable s that is 0 on every first and 1 on every second iteration.
for(int i=0, s=0; i<5; i+=s, s=-s+1)
You can use the % (module) operator in a condition inside the loop with the index variable, like this:
// code where you initialize x and y variables
for (int i=0; i<x && i<=5; i++) {
if (i % 2 == 0) { // even values for i
y++;
}
}
In this case the loop increments y in the first, third, fifth (.. and so on) iterations. If you want to increment it on the second, fourth, sixth (... and so on), then invert the condition with i % 2 != 0
I had created a short algorithm to check for a value in an array and if it does not find the value, to output can't find value.
int [] array = {108, 10, 45, 67, 23, 29, 45, 48, 902, 2};
int in, out;
int index = 10;
for(out = 0; out < index; out++)
if(array[out] == 200)
break;
if(out == index)
System.out.println("Coudld not find value");
It worked, as I had to go one value beyond to verify that the value was not in the array, i realised that even though this for loop would output 0 - 9, it still worked for out == index (Which both have a value of 10). I realise that for loops, still increment to the value that terminates the loop, is this the reason this worked?
However I experimented with this and I got an array out of bounds error.
for(out = 0; out < index; out++)
if(out == index)
System.out.println(out);
Can you explain how this worked / how for loop works, if 10 is the value that terminates the loop, when loop is at 9 < index, it still increments to 10 then out = 10, so does out = 10?
for(out = 0;out < index;out++)
if(out == index)
System.out.println(out);
Is out of bounds because your array size is 10. That means it only has valid indices of 0 to 9. Your Index value is 10 in this case which is causing the out of bounds.
Try something like the following:
int index = 9;
for(int i = 0; i < array.Length; i++)
if(i == index)
System.out.println(array[i]);
This will ensure that you will never run into an OOB exception while looping through an array.
If you want to try and find something in your array:
int toFind = 123;
bool found = false;
for(int i = 0; i < array.Length; i++)
{
if (array[i] == toFind)
{
found = true;
break;
}
}
if (found)
sysout("Found");
else
sysout("Unable to find match");
It seems, your problem lies in realizing, that when you have a loop with a condition, that condition will always be false, when the loop ends normally, i.e. without a break and neither exceptionally.
But this is an intrinsic property of the loop, as the logic is continue as long as the condition is true. Thus, the loop won’t exit before the condition went false.
So when the condition is variable < limit and the loop hasn’t been stopped by a break, for subsequent statements after the loop, variable >= limit must be true (aside from floating point NaNs…). If variable <= limit was true to begin with and you’re incrementing the variable by at most one in each iteration, you can rely on variable == limit after the loop, unless it has terminated earlier, i.e. via break. This is what your first code example does.
Inside the loop’s body, the condition will always be true, assuming that you don’t modify the variables within the body. If you use the loop form for(init; condition; update) body, between two iterative executions of the body, the update action (the increment) gets executed, followed by a test of the condition. So, due to the evaluation of the update action, the condition might become false, the condition test will fail and the loop end.
The bottom line is, it’s not strange when the loop condition is false after the loop, it’s exactly what you asked for by specifying that the loop should keep running when the condition is true.
Psudocode will be as follows for your for loop
int index =10;
int out =0;
::loop condition( out< index)
{
if(out == index)
System.out.println(out);
++out;
}
So at end of the loop your out has value 10 and it is equal to index
I'm writing a for-loop for an assignment in school. The loop will write the min number, ex. 26 and will increase with 7 every turn in the loop until it reaches max, ex. 112.
Between every number, the will also be written a comma - ",". But not after the last number.
Right now my code looks like this:
int min=26;
int max=112;
for(int i=min; i<=max; i+=7)
{
if(i!=max)
{
System.out.print(i+", ");
}
else
{
System.out.print(i);
}
}
Right now the last number will have a comma... Where's my problem?
Others have explained that i may not ever be equal to max. For a case like this, it's easier to wait until the next loop iteration to print the comma:
for(int i=min; i<=max; i+=7)
{
if(i!=min)
{
System.out.print(", "+i);
}
else
{
System.out.print(i);
}
}
(Often I'll set up a separate boolean named first to see if I'm going through the first iteration; it's set to true before the loop and false at the end of the loop.)
P.S. There are other ways to solve the problem, such as changing the i==max condition or computing the actual maximum. However, the above approach can be applied in lots of cases that don't have anything to do with stepping by a fixed amount, and where it might not be as easy to figure out ahead of time when the loop will stop.
It never enters else loop, because in your code max = 112, but your for loop won't reach that value. (It reaches 110 after increments of 7). So it will only execute the `if' loop and print the strings with comma, and then exit.
Since 'i' will never be equal to 'max', the else clause is not executed.
If 'min' is always less than 'max', then you can also do:
int min=26;
int max=112;
System.out.print(min);
for(int i=min+7; i<=max; i+=7)
{
System.out.print("," + i);
}
After 12 loops: 26+7*12 = 110. It will exit the loop and the second condition will never be met.
int min=26;
int max=112;
for(int i=min; i<=max; i+=7) {
if(i <= max-7)
System.out.print(i+", ");
else
System.out.print(i);
}
Chances are that in the last iteration of the loop, i is not equal to max, given that your increment step y 7. Actually, your loop runs from 26 to 112, that's 86 which is not multiple of 7.
You should be fine if you calculate your max value based on min and step, something like.-
int step = 7;
int min = 26;
int max = min * step;
for(int i = min; i <= max; i += step)
Your max value is 112 and your min value is 26. You're incrementing 7 at each iteration. If you subtract 26 from 112, you will see that the result is not multiple of 7, which means your loop is not stopping when i is exactly 112. Rather, your loop ends before i reaches value 112. That's why you see a comma in the end of the printed string.