This is the class whose behaviour I am unable to understand.
class loop1 {
public static void main(String args[]) {
int i = 10;
do
while(i++ < 15) {
System.out.println(i);
i = i + 20;
System.out.println(i);
}
while(i<2);
System.out.println(i);
}
}
I expected it to print
11
31
31
But it prints
11
31
32
I am not able to understand why this "32" has come up in the output.
This is my understanding of the flow
i = 10
In the while loop because of unary incremental, it becomes 11 so this explains the first output
11 gets incremented to 31 by (+20)
Then 31 < 15 should fail (during the next iteration) so it should proceed to the last print statement and print 31, but it instead it is printing 32.
Can someone tell me what I am missing ?
During the final evaluation of the first while loop i++ still increments i even though the loop does not execute because the condition fails.
class loop1 {
public static void main(String args[]) {
//1. i = 10
int i = 10;
do
// 2. while loop condition = (10 < 15), i = 11
// 6. while loop condition = (31 < 15), i = 32
while(i++ < 15) {
System.out.println(i); //3. prints 11
i = i + 20; //4. i = 31
System.out.println(i); //5. prints 31
}
while(i<2); //this really has no effect on the codes execution, given i values
System.out.println(i); //7. Prints 32
}
}
i++
You're increasing the value by 1. The value, when you increase it after the first iteration is 31. 31 + 1 is, surprisingly, 32. And you print out the value directly after incrementing it.
In 2nd iteration when condition of while loop is check
while(i++<15)
at that time i is 31 so condition fail but i++ change the value of i 31 -> 32
while(i++ < 15) compare the value of i with and after that increment i by 1
My guess is:
while(i++ < 15)
The i++ increments the value from 31 to 32 on the second loop.
Note, the ++ will be executed even if the condition fails - which in your case, the 31 is greater than 15 (condition fails), however because of the ++ the value is incremented to 32, which is being printed out by the System.out at the end.
In the program :
while(i++<15)
above statement is condition checking in this statement
you are post increment i therefor 31+1=32 is comming
Related
Output that I want: 10 20 30 40 50..............
Output that I get: 0
public class HelloWorld
{
public static void main(String[] args)
{
final int n = 50;
int i= 0;
while(i <= n && i % 10 == 0 )
{
System.out.println(i);
i++;
}
}
}
while(i <= n && i % 10 == 0 )
This is the continuation condition which is two expressions connected by logical-and &&.
That means both must be true for the whole thing to be true.
Now work out the two sub-expressions for when i becomes 1. The first will be true but not so the second (1 is not a multiple of 10), meaning the loop will exit at that point. That explains why you're only seeing 0.
To fix it, you need to separate the two sub-expressions since the loop control depends only on the first. However, you still only want printing to happen for multiples of ten (the second).
So, assuming as per your desired output 10 20 30 40 50, you don't want 0 as one of the outputs (despite it being, after all, a multiple of 10), the following pseudo-code will do the trick:
set n to 50, i to 1
while i is less than or equal to n:
if the remainder when i is divided by 10 is 0:
output i
increment i
If you do want 0 included in the output, simply set i to 0 initially, and you'll see 0 10 20 30 40 50.
I've left the code above as pseudo-code on the assumption this is classwork of some description - it should be relatively easy to turn that into any procedural language.
i % 10 == 0
This will evaluate to false on the second loop so the while wont continue. I think you want this...
final int n = 50;
int i= 0;
while(i <= n)
{
if (i % 10 == 0) {
System.out.println(i);
}
i++;
}
This allows i to increment all the way up to n, but it will only print results when i % 10 == 0
You are trying to use the while and both a while and an if. Try
public class HelloWorld {
public static void main(String[] args) {
final int n = 50;
int i = 0;
while (i <= n) {
if (i % 10 == 0) {
System.out.println(i);
}
i++;
}
}
}
Loop run for once only for i=0. That's it.
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
I was attempting to solve Puzzle A14 found at http://chortle.ccsu.edu/CPuzzles/PartA/CpuzzlesAsection11.html, using Java (with Eclipse), when I came across some unexpected results.
The puzzle requires that on each line k, print all of the integers that are multiples of 23 in the range of 100 * k to 100 * k + 99 (where k is some limit, such as 11).
The Nested For Loop that I eventually used to solve the problem was:
for(i = 0; i <= k; i++){
for(j = 0; j <= 99; j++){
if((100 * i + j) % 23 == 0)
System.out.print(100 * i + j + " ");
}
System.out.println();
}
However, in my first attempt, I did not put parentheses around 100 * i + j before using modulo division in the If Statement and it produced only one line of results: "0 23 46 69 92" (as compared to the correct solution, which gave me 11 lines of results: "0 23 46 69 92" in the first line, "115 138 161 184" in the second line, etc.).
I was trying to figured out the reason behind this. Even without the parentheses, I would assume the If Statement was using modular division on j, before combining it with 100 * i. However, if that was the case, wouldn't it produce 11 lines (if k = 11) of "0 23 46 69 92" instead of just a single line?
This is due to operator precedence. The modulo (%) operator as higher precedence over the plus and minus operators. See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html.
Take, for example, the case where i = 1 and j = 38. In this case,
(100 * i + j) % 23 evaluates to zero and hence the condition is true. On the other hand, 100 * i + j % 23 evaluates to 115 and the condition is false.
The reason why only one line is printed when removing the parentheses is that when i > 0 (starting from the second line), the expression 100 * i + j % 23 will always be greater than 100, and therefore the condition of being equal to zero will always be false. Therefore, nothing will be printed starting at the second iteration of the outer for loop.
Because, for example, (100*1 + 15)%23 == 0 but 100*1 + 15%23 == 100*1 + (15%23) == 115.
I've been scratching my head over why Java will go beyond a specified condition in some loops, while seemingly adhering to the condition in other loops. I know it's a lack of understanding on my part, but I'm confused as to when I should go over or adhere to the condition when I'm manually calculating code.
As an example, I've put in a short for loop which has an end result of 15 in iTotal, and 0 in iNumber. When I originally did the calculation on paper step by step, I ended up with the answers of 14 in iTotal, and 1 in iNumber. I assumed that the code would not go below one, as the condition was greater than zero, not equal to or greater than zero.
My original attempt -
iTotal
0
5
9
12
14
iNumber
5 4 3 2 1
int iTotal = 0;
for (int iNumber = 5; iNumber > 0; iNumber--)
iTotal = iTotal + iNumber;
In comparison, the below code snippet will at 19 with a condition of less than 20, with the last statement being value of x : 19. I calculated that correctly, but I'm not sure why the above code ignores the condition and goes to zero, while the below code adheres to the condition and stops at 19.
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
Could anyone clarify how java interprets when to go over or stop at specified conditions?
In comparison, the below code snippet will at 19 with a condition of
less than 20, with the last statement being value of x : 19. I
calculated that correctly, but I'm not sure why the above code ignores
the condition and goes to zero, while the below code adheres to the
condition and stops at 19.
What you said is incorrect. The last statement printed is 19 but the last value of x is 20. This loop that you have given does in fact execute 20 times. A for loop in Java like the one you given has 3 components an integer to use as a count, a condition to test, and how to transform the count variable. In a general form it looks like this:
for(count variable, condition, transformation){
//Code goes here
//End loop
}
This for loops executes until the condition is no longer true, which is caused by applying a transformation of some sort the count variable.
Using the for loop you gave as an example:
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
}
We create the count variable (int x) and set it equal to 10.
We check the count variable (int x) against the condition ( x<20 ) and evaluate the result, x < 20 == true so the code within the loop is run. At the end of the code, which I have marked "End Loop" above the transformation (x + 1) is applied to the count variable before the condition is tested again to see if the loop should proceed.
x = 11 now because x was equal to 10 but we added one as specified at the end of last loop. x < 20 == true is still true so the code within the loop will be executed again. This is continued in this way until the last number.
When x = 19 we test against the condition as we have been doing and see if x < 20 == true is still true, which it is so the code is executed. When the code execution ends, the count variable is again incremented, so x = 20.
With x = 20we once again test against x < 20. This time x < 20 == false so the code inside the loop is not executed nor is another transformation applied to the variable. At this point, when the condition becomes false the loop ends. So because we said x < 20 and not x <= 20 on the 20th loop, when x = 20, this code:
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
will not run. This means that the final output of the program would occur when x = 19 not when x=20 although if you were still able to access the count variable after the loop ends (which I believe you can do with a debugger) you would see x=20
The first loop does this:
iTotal = 0
iTotal = 5
iTotal = 9
iTotal = 12
iTotal = 14
iTotal = 15
Loop end
also as the first loops transformation is written as x-- instead of x - 1 the second loop can be rewritten as:
for(int x = 10; x < 20; x++) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
}
in Java the ++ operator increments by 1, it is the same as x+1.
Your first loop
for (int iNumber = 5; iNumber > 0; iNumber--)
iTotal = iTotal + iNumber;
is 5+4+3+2+1 = 15 (you must have printed iTotal before you added the first iNumber). Your second loop is similar the loop body isn't entered when the condition evaluates to false.
int x = 10;
for(; x < 20; x = x+1) {
System.out.print(x + " ");
}
System.out.println(x); // x is 20
as 10,11,12,13,14,15,16,17,18,19,20 but at twenty the loop terminates.
The condition is checked before each loop, not after. So in your first example, the logic would go:
iNumber = 5
first loop iteration
check iNumber > 0. 5 > 0, so continue the loop
add 5 to iTotal (iTotal=5 after this)
decrement iNumber
second loop iteration
check iNumber > 0. 4 > 0, so continue the loop
add 4 to iTotal (iTotal=9 after this)
decrement iNumber
...
fifth loop iteration
check iNumber > 0. 1 > 0, so continue the loop
add 1 to iTotal (iTotal=15 after this)
decrement iNumber
sixth loop iteration
check iNumber > 0. 0 > 0 is false, so break out of the loop
A similar process happens with the second loop.
Here is all the code I think anyone would need to be able to asses my problem
1 import.java.util.Scanner
2 public class ccattano_Sieve{
3 private boolean [] primes = new boolean [50001];
4 private int upper;
5 private int lower;
6
7 public ccattano_Sieve(){
8 upper = 50000;
9 lower = 1;
10 for (int i = 2; i < primes.length; i++){
11 primes[i] = true;
12 }
13 primes[0] = false;
14 primes[1] = false;
15 }
16
17 public void processSieve(){
18 for (int i = 2; i < Math.round(Math.sqrt(50000)); i++){
19 if (primes[i] == true){
20 for (int c = 2; c < (primes.length - 1); i++){
21 if (c % i == 0){
22 primes[c] = false;
23 }
24 else{
25 primes[c] = true;
26 }
27 }
28 }
29 }
30 }
I'm pretty sure my else statement on lines 24 - 26 aren't needed I added it when trying to trouble shoot. But on line 21 when trying to run the code I receive a divide by zero error. The exact error is as follows.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ccattano_Sieve.processSieve(ccattano_Sieve.java:21)
at ccattano_SieveTest.main(ccattano_SieveTest.java:7)
This line "at ccattano_SieveTest.main(ccattano_SieveTest.java:7)" calls the code I pasted so it can be ignored. So line 21 is the main issue and I can't find a solution.
The modulus operator is the "rest of the division" meaning that it involves a division.
I believe you have a bug on line 20 where you are incrementing i instead of c.
This means the i variable will overflow (reach so high that it will turn negative) and eventually will turn into 0.
You never update the value of c in your inner loop; instead you increase i by the length of your array minus 1 every time up till the square root of 50,000. I'd suspect this is an error and not what you want to do, but I await a comment to the contrary.