how many loops is this running? - java coding - java

I have been given "10 broken loops" to solve. I need to comment what was changed to make them correct.
I have
public class BrokenLoops {
//loop 5 times
public static void loop1() {
for (int i = 1; i != 10 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
I know what the problem is, it will never be 10. 1 then 3 then 7 then 9 then 11 etc.
What I don't know is how many loops will be run if I type either !=9 or !=11
Would the code run as
If the code has !=11, would it run as
i = 1 "in loop"
1 = 3 "in loop"
i = 5 "in loop"
i = 7 "in loop"
i = 9 "in loop"
i = 11 "out of loop"
and so, there are 6 loops? The correct answer for 5 loops would be !=9?
Thanks in advance

This loop have condition to run when i is not equal 10. Because i starts at 1 and increases by 2 on every iteration, i will be always odd number and therefore can newer equal 10. So condition for loop will be always true. Simply put: your loop will go indefinitely.
About for statement from
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
The initialization expression initializes the loop; it's executed once, as the loop begins.
The termination expression is invoked before each iteration. When it evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
More info about for statement: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
//edit
Correct code for 5 loops if you have to use '!=' comparison would be:
for(int i = 1; i != 11; i += 2)
// i==1 PASS
// i==3 PASS
// i==5 PASS
// i==7 PASS
// i==9 PASS
// i==11 FAILED, Loop ends here
although it's better to use
for(int i = 1; i < 10; i += 2)
//or
for(int i = 1; i < 11; i += 2)
this way, your loop will end after 5 loops and safer for many reasons

The loop as you have posted will run continuously as i will never get the value 10.
if you make the termination condition i != 9 then the loop will run for 4 times.
if you make the termination condition i != 11 then the loop will run for 5 times.
if you make the termination condition i <= 10 then the loop will run for 4 times.
to get it to run 10 times, change the for loop to this:
for (int i = 1; i <= 10; i++){
//Your code
}
EDIT:
Code:
for (int i = 1; i != 11; i += 2)
{
Console.WriteLine("In loop {0}", i);
}
Console.WriteLine("Out loop");
Console.ReadLine();
Output:

There are a few possible ways to solve your question.
Example 1
If you only need to get in the loop 5 times you can simple change your code to:
//loop 5 times
public static void loop1() {
for (int i = 0; i < 5 ; i++) {
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
This will print something like:
In loop 0
In loop 1
In loop 2
In loop 3
In loop 4
Out of loop
Example 2
Another option would be to change your termination value to !=11(Just don't forget, that if you increment would become i += 3 for example, this will become an infinite loop again):
public static void loop1() {
for (int i = 1; i != 11 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
This will terminate the loop once i will be equal to 11, so the output would be:
In loop 1
In loop 3
In loop 5
In loop 7
In loop 9
Out of loop
Example 3
You can also change termination to i < 10(or <=9 or <=10 or <11):
public static void loop1() {
for (int i = 1; i < 10 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
The output will be same as in Example 2.
Example 4
You can also add a check inside your loop to stop it after something evaluates to true:
public static void loop1() {
int checkInt = 0;
for (int i = 1; i != 10 ; i += 2) { //final statement i += 2 means i+2
if (checkInt == 5) break;
System.out.println("In loop "+i);
checkInt++;
}
System.out.println("Out of loop");
}
So when checkInt will be equal to 5(loop was made 5 times), the loop will just stop. Output is the same as in Example 2 and Example 3

If the code has i !=11, would it run as
You just have to use i<10 to get the desired result

Related

Nested for loop output printing and formatting incorrect table, it's all funky

So the goal was to use a nested for loop to output 6 rows and 10 columns. The thing was though that the inner for loop was supposed to check to see whether the number was even or odd as, if it was even, we would add 2 to it and then print out that number 10 times before moving onto the next output. So this is what were were supposed to get
1 1 1 1 1 1 1 1 1 1
4 4 4 4 4 4 4 4 4 4
3 3 3 3 3 3 3 3 3 3
6 6 6 6 6 6 6 6 6 6
5 5 5 5 5 5 5 5 5 5
8 8 8 8 8 8 8 8 8 8
I thought I was on the right track but my output is a complete mess, here's what I have. Thank you to anyone willing to help.
for (int numberE = 1; numberE <= 6; numberE++)
{
for (int nestedE = 1; nestedE < 10; nestedE++)
{
if (numberE%2 == 0)
{
numberE += 2;
System.out.printf("%2d", numberE);
} else {
System.out.printf("%2d", numberE);
}
}
System.out.printf("%2d\n", numberE);
}
well to start with your inner loop will only iterate nine times. second you don't need a nested loop, you need one loop and a guard determining when to print.
Don't modify numberE inside the loops. Instead just print numberE + 2.
Also, if your inner loop runs from 0 to <10 you will get 10 iterations and you don't need to print the number again - just a newline.
for (int numberE = 1; numberE <= 6; numberE++)
{
for (int nestedE = 0; nestedE < 10; nestedE++) // <-- start at 0 and end <10 for 10 iterations
{
if (numberE%2 == 0)
{
System.out.printf("%2d", numberE + 2); // <-- print the number + 2
} else {
System.out.printf("%2d", numberE);
}
}
System.out.println(); // <-- don't print the value again here
}
I would do it this way. Gives the required result.
public class NestedForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 6; i++)
{
int temp = i;
if(temp%2 == 0) {
temp +=2;
}
for(int j=1;j<=10;j++) {
System.out.print(temp+" ");
}
System.out.println();
}
}
}
A brief description of what is happening here:
So, since we need 6 rows, we use the value of 6 as a row counter. The variable i takes care of keeping a count of the rows. Here since the target is 6, we start from row number 1 and go until row no 6. Inside each value of the loop, we save the value of i to temp because we don't want the value of i to change before incrementing in the main for loop. We then check if this temp value is even by doing a modulo division by 2. If it is even, we increment the temp value by 2.
Then, we run a loop from 1 to 10 since we need 10 columns to print the value temp(either the original i or incremented because it was even). After exiting the loop, finally to move to the next row, we do a System.out.println().
I would suggest using a temporary variable to store the current intended value.
The issue with your solution was that you were modifying the value of numberE by using numberE += 2; inside the second for loop, this changes the value globally.
Moving the final column in to the nested for loops also makes it easier as you wouldn't need to define the temporary variable outside of the loop. Using this also meant changing the <10 to <=10.
for (int numberE = 1; numberE <= 6; numberE++) {
for (int nestedE = 1; nestedE <= 10; nestedE++) {
int current = (numberE % 2 == 0) ? numberE + 2 : numberE;
System.out.printf("%2d", current);
}
System.out.printf("\n");
}
You were pretty close though, with practise you'll get better.

Syntax and Variable Declaration in Nested Loops: How Does an Inner Declaration take Precedence?

I was following an example of how to produce a script in java that computes and prints the powers of 2 (2, 4, 8, 16...) and the script looks like this:
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i = 1; i < 10; i++) {
result = 1; //why doesn't this reset result to 1 for every iteration?
e = i;
while(e > 0) {
result *= 2;
e --;
}
System.out.println("2 to the " + i + " power is " + result);
//I would expect printing "result" here would result in 2 every time...
}
}
}
The output is:
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 128
2 to the 8 power is 256
2 to the 9 power is 512
My question is that if the result variable is declared as 1 within the initial for loop but outside the inner while loop, how come its value doesn't reset to 1 every time the for loop runs? It's clear to me that the for loop begins running before the while loop takes over, because the System.out.println() command is run every time. What is it about Java's structure that allows this?
You are absolutely right about result being reset to 1 in each iteration of the for loop. It does get reset.
"But why doesn't printing result give me 2 every time" you ask.
After result is being set to 1, and before that iteration of the for loop ends, the while loop runs. How many times does the while loop runs? It depends on i. In the first iteration of the for loop, the while loop loops once, in the second iteration of the for loop, the while loop loops twice, in the third iteration of the for loop, the while loop loops three times, and so on.
At the end of each iteration of the for loop, result will contain the value of 2 to the power <however many times the while loop looped for>. So at the end of the first iteration of the for loop, result is 2 because the while loop looped only once. At the end of the second iteration, result is 4 because the while loop ran twice and so result *= 2 is ran twice.
If result isn't reset, it would have become 8 by the end of the second iteration of the for loop: it got multiplied once in the first iteration, and twice in the second iteration.
please check below inline explanations
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i = 1; i < 10; i++) {
result = 1; //why doesn't this reset result to 1 for every iteration?
// Yes , result will be 1 always here, you can print the result variable before while as below
// System.out.println("Result : " + result);
e = i;
while(e > 0) {
result *= 2;
e --;
}
System.out.println("2 to the " + i + " power is " + result);
//I would expect printing "result" here would result in 2 every time...
// here the value of result will be decided based on e, here we are multiplying result with 2 , "e" no.of times
}
}
}

Finding Prime Numbers between 1 and 100 using nested Loops [duplicate]

This question already has answers here:
How to find prime numbers between 0 - 100?
(40 answers)
Closed 6 years ago.
I am trying to find the Prime Numbers between 1 and 100 using nested Loops but I am getting weird results.
I think I have a problem with my code but I can't figure out where exactly, can someone help me ?
The first loop that I made will count the numbers from 2 to 100 (i)
the second one will count the numbers from 2 to i-1 (j)
so when you divide i%j != 0 it should give you the Prime numbers am I right ?
thanks a lot for your help
public static void main (String []args){
for(int i = 2; i<=100 ; i++)
{
for(int j = 2 ; j < i-1 ; j++ )
{
if (i%j != 0)
{
System.out.println(i );
}
}
}
}
This tests if it's not prime:
if (i%j == 0)
In which case, abort further tests and try the next number, which can be implemented a few ways, but the minimal change to your code is:
outer:
for (int i = 2; i<=100 ; i++) {
for (int j = 2 ; j < i-1 ; j++ ) {
if (i%j == 0) {
continue outer;
}
}
System.out.println(i);
}
The code outer: is a label (it can be any name, eg foo:), and continue outer; means commence the next iteration of the loop with that label.
so when you divide i%j != 0 it should gives you the Prime numbers am i right ?
No. Only if this condition is true for all j, the number is prime.
the problem is this
if (i%j != 0){
System.out.println(i );
}
}
You are saying, for each value of j, test against, i and if modulus remainder is *not 0, print. However you must check for all iterations of j in the loop before deciding the candidate (i) is prime. *all values of j that must be checked before you can conclude the prime.
Set a boolean flag false (not prime), update the flag to true if (i%j != 0) else false
then after your nested for, print against an if with the flag

Converting a for-loop with continue statement to while-loop

I am working on an exercise where a small piece of code based on a for-loop is converted to preform the same operation with a while loop. The conversion is wrong by purpose, and looks like this:
int sum = 0;
for (int i = 0; i < 4; i++) {
if (i % 3 == 0) continue;
sum += i;
}
System.out.println(sum); // prints 3
This is converted into:
int i = 0, sum = 0;
while (i < 4) {
if (i % 3 == 0) continue;
sum += i;
i++;
}
System.out.println(sum); // will not print
In the exercise, I am asked to explain why the conversion is wrong and then fix it. My thoughts are:
With the initial value of i = 0, this will trigger continue instantly after entering the will loop, since (0 % 3 == 0) will make the if-statement true. As long as the initial value is 0, this will execute the loop, for so to skip it an endless amount of times. I tried changing the initial value of i = 1, but noe sum is printed. Then I tried to increment i before executing the if-statement, and the program now prints the sum 7. The question here is; why won't the program print if i incremented after the if statement, even if the initial value of i = 1 suggests (in my head) that program should run properly?
I made a table for each program to compare the summing.
The for-loop version:
i = 0, sum += i not preformed (continue), i++
i = 1, sum = 1, i++
i = 2, sum = 3, i++
i = 3, sum += i not preformed (continue), i++
i = 4, i < 4 false, loop stopped
The while-loop version:
i = 0, i++, sum = 1
i = 1, i++, sum = 3
i = 2, i++, sum += i not preformed (continue)
i = 3, i++, sum = 7
i = 4, i < 4 false, loop stopped
In the while-loop, sum += i is preformed once more than in the for-loop. Is this the right way to convert the for-loop into a while-loop?
int i = 0, sum = 0;
while (i < 3) {
i++;
if (i % 3 == 0) continue;
sum += i;
}
System.out.println(sum);
Your 1 is focussing on it being the initial value, but that's not the point. The point is that i is never incremented when i % 3 == 0 is true, not that 0 is the initial value. So the while loop loops forever.
Your 2 doesn't make any sense: The while version will loop forever, never summing anything.
Is this the right way to convert the for-loop into a while-loop?
No, you're incrementing i at the wrong time.
Think bout how a for loop works:
Initialization - First it sets the variables to the values in the first expression.
Test - Then it tests the values using the second expression.
Execute - If the value is true, it executes the loop body.
Increment - When the loop body is complete, it executes the third (increment) expression. Note that this is after the loop body.
Make your while loop do what the for loop is doing. (I'm intentionally not doing that for you; this is a learning exercise. I'll note that the best way to convert that for loop will not use continue, however. "Best," of course, is subjective.)
In the exercise, I am asked to explain why the conversion is wrong and then fix it
The conversion is wrong simply because when you will reach a i value that modulo 3 equals 0 (the first iteration in that case), you will skip to the next iteration and re-validate. However, since you skipped directly without incrementing i , you will re-validate the same condition and re-validate ad-infinitum.
You could fix it easily by getting rid of the continue and negating the condition :
while (i < 4) {
if (i % 3 != 0)
sum += i;
i++;
}
The for-loop given by the question if converted to plain English, it means sum up from 0 to 3 and exclude all multiples of 3. (0+1+2=3)
for (int i = 0; i < 4; i++) {
if (i % 3 == 0) continue;
sum += i;
}
So now, we ask ourselves, how do we sum up 0 to x and exclude all multiples of 3 using a while-loop. We will do this without looking at the original for-loop. (Sometimes it is easier to do it this way since we already know the intention of the for-loop)
To sum up a number from 0 to 3:
int i = 0;
while(i < 4){
sum += i;
i++;
}
To sum a number from 0 to 3, excluding multiples of 3:
int i = 0;
while(i < 4){
if(i % 3 != 0)
sum += i;
i++;
}
To sum a number from 0 to 3, excluding multiples of 3 (using continue):
int i = 0;
while(i < 4){
if(i % 3 == 0){
i++; //Remember to increase i before continue
continue;
}
else
sum += i;
i++;
}
Since after the continue, all statements below it will be skipped, you have to remember to do an increment i++ before calling continue. There will be another i++ since you branch out into 2 conditions now.
According to the while loop logic, increment of variable i is conditional where as for for-loop it is unconditional. To make the increment logic uniform, you should increment in both cases.
I think the proper converting would be -
int i = 0, sum = 0;
while (i < 4) {
if (i % 3 == 0) {i++;continue;}
sum += i;
i++;
}
System.out.println(sum);
Normally the increment would be on the last line of a while loop. However, in this "disaster waiting to happen" code, there is a condition to skip to the end of the while block without incrementing i. If you are relying on i to increment, make sure it is always executed on any iteration. And also, at the end, because you want it to iterate the first time.
while (i < 4) {
if (i % 3 == 0) {
// skip!
} else {
sum += i;
}
i++;
}

Why does this while loop act this way?

int i = 1;
int j = 1;
while (i < 4) {
j += i;
i++;
}
System.out.println("i = " + i);
System.out.println("j = " + j);
I have the following above and I am trying to figure out how it works. I am new to java so I do not know how to debug my code yet. The output of this program says that i = 4 and j = 7. However the condition of the while loop should only execute when i < 4. Why does it execute when i = 4? I tried changing the condition to i <= 4 and it outputs i = 5. What am I missing here?
The loop counter will be incremented for every iteration through the loop. When the counter has been incremented past 3 (when it's equal to 4) the loop will stop. The loop won't run when the counter is 4, but the counter was still incremented to 4
i = 1
is 1 less than 4? Yes, so loop.
add one to i so now i = 2.
is 2 less than 4? Yes, so loop.
add one to i so now i = 3.
is 3 less than 4? Yes, so loop.
add one to i so now i = 4.
is 4 less than 4? No, leave the loop.
Print the value of i which is 4.
You enter the loop when i=3. Inside the loop, you increment i by 1 (i++). At the end of that iteration, you check if i<4, which it is not, because i=4.

Categories