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
Related
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'm currently struggling understanding this loop:
class Test{
public static void main(String args[]){
int i=0, j=0;
X1: for(i = 0; i < 3; i++){
X2: for(j = 3; j > 0; j--){
if(i < j) continue X1;
else break X2;
}
}
System.out.println(i+" "+j);
}
}
So far I know that the values of the variable will be:
0 3
1 3
2 3
and finally will print 3 3.
After the third iteration the condition on X1 will be false resulting in an interruption of the loop statement. While it's clear to me why the value of i is equal to 3, I do not understand why the value of j is 3 as well. Initially the value of j is 0, when we enter in the loop is 3, but in the last iteration we do not enter really in the X2 loop, since i<3 evaluate false. So the question is why the compiler "save" the value of k ? And even if the compiler save the value of j from the previous iteration should be 2 ...
j-- is dead code here and will never be reached. Think about how the code works for a moment here:
X2: for(j = 3; j > 0; j--){
if(i < j) continue X1;
else break X2;
}
If one situation you continue to the outer loop, in the other situation you break out of this loop. This loop actually never even goes past a single iteration so you might as well just write this like this:
int i=0, j=0;
X1: for(i = 0; i < 3; i++){
j = 3;
if(i < j) continue X1; //This line does nothing at this point as well since the loop will iterate anyway
}
This is exactly the same as your current code, which clearly shows j will stay at 3.
for(j = 3; j > 0; j--)
You are setting j=3. j-- is not run until the next j loop, that never occurs, so it cannot be 2.
else break X2;
and
j--
are never being reached.
'i' can never be 3 within the loop since the outer loop's condition is i < 3, and therefor the inner loop can only perform
if(i < j) continue X1;
since 'j' always starts at 3 and i <= 2. is always true. So 'j' never changes value, and the outer loop breaks when i = 3, resulting in, "3 3".
i j
0 3
1 3
2 3
break occurs;
print i + j;
Initially the value of j is 0, when we enter in the loop is 3, but in the last iteration we do not enter really in the X2 loop, since i<3 evaluate false. So the question is why the compiler "save" the value of k ?
j is declared at the first line in main. This means that it will remain in scope and retain any modifications until main ends and the variable is destroyed.
And even if the compiler save the value of j from the previous iteration should be 2.
As you said above, the value of j from the last iteration of the loop was 3 not 2. When you continue X1 the j-- was never executed.
It is because of the dead code as others mentioned. You should debug your program by going step by step I don't know which IDE you are using but it probably provides this feature.
However, I want to advice you to not use continue and break statements. It is highly discouraged by the instructors. They cause spaghetti programming and confusions like you have.
Code snippet:
int i=0;
for(int i=0;i<1;i++){
i=--i-i--;
System.out.println("for loop i= "+i);
}
System.out.println("i value outside for loop= "+i);
output:
for loop i= 0
i value outside for loop= 1
The value of i inside for loop is zero and outside for loop i is 1. Could you please help me understand it?
i=--i-i--; changes the value of i to -1 and then back to 0, because it assigns to it -1-(-1), which is 0. The reason for this result is that pre-decrement operator - --i - returns the decremented value -1 while post-decrement operator - i-- - returns the value prior to decrementing it (therefore it returns -1 instead of -2).
However, the loop's i++ clause increments i to 1, which causes the loop to terminate. Therefore the value of i is 1 after the loop.
Note that you have a typo in your question. You are declaring i twice in the same scope. In order for the code to pass compilation (and display the output you claim you got), you should change it to:
int i=0;
for (i = 0; i < 1; i++) {
i = --i-i--;
System.out.println("for loop i= "+i);
}
System.out.println("i value outside for loop= "+i);
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.
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!