Why the following program printing "Hello" three time and not two? - java

I am learning java nowadays, and while going through loops in java, I am stuck here, I am unable to understand why the following program is printing "Hello" three times. can you please explain?
public class Helloworld {
public static void main(String[] args) {
for (int i =1; i<=2; i++ ) {
for (int j =1; j<=i ; j++) {
System.out.println("Hello");
}
}
}
}

for loop iterations:
i=1
j=1 — prints "Hello"
j=2 — breaks out of inner loop, `j <= i` is false.
i=2
j=1 — prints "Hello"
j=2 — prints "Hello"
j=3 — breaks out of inner loop, `j <= i` is false.
This is what happens when the above code is run.

To understand why, change
System.out.println("Hello");
to
System.out.println("Hello: i = " + i + ", j = " + j);
compile and run it again, and look carefully at the values of i and j printed out.
Basically, in the second iteration of the outer loop, the inner loop runs twice.
If you cannot compile and run the program, there is another way to understand the behavior. Hand execute it.
Get a pencil an piece of paper, draw a table with a column for each variable. Each time a variable is assigned to / modified (e.g. i = 0 or i++) add a new row to the table with the current values of all of the variables. When you have a test (e.g. i<=2) read the variable's value from the latest row in the table.
After some practice you will be able to do this in your head. After more practice you will be able to read the code (like you read English text, or mathematical notation) and reason about what the code does.
Or use a debugger :-)

Sometimes when learning loops, writing small loops on paper can help.
Here you habe a nested loop using variables i and j.
First, the inner loop, j=1, and 1 is less than or equal to 1(i), so it prints. Then j++.
j is now 2, which is not less than or equal to 1, ending inner loop cycle. Now back to outer loop, i++,
i is now 2.
Inside the inner loop- j=1, less than or equal to 2, so second print. Now j++. Condition still true, as j(as 2) is still less than or equal to 2, so third print.
Hope this debugging method helps you.

You have two loops. The outer i loop runs twice, but inner j loop depends on the value of i with the j<=i part. So for the first i loop, j runs once, and the second i loop j runs twice, so three times all up.

This has to do with the nested looping. There's (2) loops to pay attention to here. For each iteration of the outer loop (i), the inner loop (j) may run multiple times. If you change the output to output the iterators, it will give you some visibility into this property.
System.out.println("i:"+i+" j:"+j);
OUTPUT: $javac HelloWorld.java
i: 1 j:1
i: 2 j:1
i: 2 j:2
If you want to get a more detailed view on nested looping, here's a good video series I'd recommend: Nested Looping (The Coding Train)
Hope this helps!

Related

Is there a way to tell how many times a for loop will execute before running it?

I am taking an intro to java course and I am taking a practice quiz. These quizzes are not graded and do not count towards our grade so I thought I would post here.
Under normal circumstances, I would just copy the code and paste it into an IDE but I wanted to know if there is a way to think about this logically so I can figure out the answer. On real exams, we are not allowed to use eclipse or anything like that to figure out an answer and this question would take way too long to do it by hand and count how many times it goes through the for loop.
Here is the question:
How many times does the print statement in the for loop execute?
for(int i = 0; i <347589; i++) {
System.out.print("Give me coffee!");
}
You can basically just take the upper bound of the for loop as an answer, which is 347,589 in this case. To arrive at this answer, consider a for loop with a much smaller bound:
for (int i=0; i < 5; ++i) {
System.out.println("Give me coffee!");
}
By inspection, we can see that this loop will execute when:
i = 0
i = 1
i = 2
i = 3
i = 4
It won't execute when i = 5, because that fails the condition. So, it executes five times, which is the same as the upper bound of the for loop. We can extrapolate this to the loop in your problem to get 347,589 as the answer.
There is no general way to figure out how many times a while loop will execute before running it. This fact is known as the undecidability of the halting problem. For loops are just syntactic sugar for while loops, so this applies to for loops as well. The halting problem is the subject of a great many awesome books, among which Gödel, Escher and Bach by Douglas Hofstadter.
However, the for loop you give is extremely simple: it increases i until i no longer satisfies i < 347589. The variable i starts at 0 and increases one by one: i++ is equivalent to i = i + 1;. So i takes all the successive values: 0, 1, 2, 3, 4, ...,347588 and every time, the line System.out.println("Give me coffee!"); is executed.
Then i takes the value 347589 and no longer satisfies i < 347589, so the loop halts.
In total, "Give me coffee!" was printed 347589 times.
If you don't like the syntax for for loops, your code is equivalent to the following code using a while loop:
int i = 0;
while (i < 347589)
{
System.out.print("Give me coffee!");
i = i + 1;
}
As you have a simple for-loop that executes only one statement multiple times, you can simply count. You might know that the loop starts with i=0 with the first execution and adds 1 after each execution until the condition i<347589 is false. So:
i=0 -> once (1.)
i=1 -> twice (2.)
...
i=347588 -> 347589 times (347589.)
i=347589 -> loop stops.
so the print statement will be executed 347589 times.
In the course they might just want to check your knowledge towards the coding basics. In these type of problems you should notice most importantly 4-5 things.
1- Starting point of index.
2- Ending point of index, also check whether that value in included or not.
3- Increment/Decrement of index, whether index is increased/ decreased by 1 or some other value or pattern.
4- Is their any break statement inside the loop, which will also indicate that loop will run till specific condition.
In the example you gave starting point is 0 and end point is 347589 (excluded) with increment of 1, so loop will run. 347589 - 0 + 1( 0 based index) = 347589 times.
Obviously, FOR loop is not Java specific question.
To understand FOR loop properly let's take an easy example.
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
This code will print all number from 0 to 10 (Excluding).
So, the range 0-10 has 10 different values:
0
1
2
3
4
5
6
7
8
9
When i becomes 10 FOR loop statement (i<10) will not be satisfied and the loop will be broken.
So, in you case "Give me coffee!" will be printed 347589 times with the same logic.

Best way to learn recursive statements and understand them?

I am having such a tough time reading and understanding recursive statements in java.
if my professor shows us code and asks what does this do? what does it return?...I find myself staring at the code as if its going to eventually make sense...but it NEVER does.
examples like---
public static Int mystery(int[][] a, int b) {
int x = 0;
for (int i = 0; i < a.length; i++){
for (int j = 0; j < a.length; i++){
x += (a([i][j] == b) ? 1 : 0;
}
}
return x:
}
what does mystery (a, 8) return where a =
{{6, 4, 5, 8},{4, 6, 4, 8,}, {7, 3, 6, 4,}, {1, 5, 7, 8}}
can someone please explain? thanks!
Hi welcome to the world of programming
This is not recursive programming. Recursive is when a function calling itself.
For example, delete files() -> which will call itself again when there is folder, and you want to delete files under it again and again.
Your example is called a 'Nested Loops' -> Loops of Loops, and the condition 'a.length' being used in both i and j is wrong.
You are trying to loop arrays of arrays, a 3d table. It should be something like this.
int x = 0;
for (int i = 0; i < a.length; ++i){
for (int j = 0; j < a[i].length; ++j){
if (a[i][j] == b) {
++x;
}
}
return x;
Changes:
Try not to use 'ternary operator' ?: as this might confuse you as a beginner.
the max length of inner loop should be a[i]'s length
using ++i is better than i++ if you are not using the value directly.
Imagine
[[1,1,1],
[2,2]]
in your first loop, a[0].length will be 3.
in your second loop, a[1].length will be 2.
as for ++i vs i++:
++i is modifying i directly, making the value +1 instantly
i++ means var b = i; i = b + 1;
it is creating a new temporary variable to hold the original i value.
example:
int i = 0, j = 0;
System.out.println(i++); // will print 0, but i will be 1 moving forward
System.out.println(++j); // will print 1, and j will be 1 moving forward
you will learn more on this in future.
Firstly, if you don't understand something, don't just keep staring at it expecting it to suddenly make sense, as that's likely to just be frustrating. Instead, try to break it down into smaller parts, and work from what you know and expand from that, piece by piece.
That's easier said than done, though. How do you split it up? Here are two approaches: you'll need both.
Low level
One way is to ‘dry run’ the code, instruction by instruction, as if you were the computer. This is slow and tedious, but it gives you the best insight into what the computer is actually doing.
Take a piece of paper, or the virtual equivalent such as a spreadsheet. Make a column for each variable in the method: a, b, x, i, j. (Make the one for a extra wide.)
The method starts with parameters being set, so write the array under a and 8 under b. Next, x is set to 0, so write that under x. Then i is set to 0, and compared to a.length. The array a has four items, the inner arrays, so the length is 4 and the current value of i, 0, is less than that, so the condition is true and we enter the body of the outer loop.
The body of the outer loop contains only the inner loop, which sets j to 0 and compares it to a.length. It's less, so enter the body of the inner loop.
The inner loop body does a few things starting on the right of the =, first working out what a[i] means. Currently i is 0, so that's a[0], which is the first sub array. Then work out a[0][j], which is a[0][0], which is 6. That's not equal to b, so the condition is false: take 0 and add it to the
number under x, 0, and write the result under x to replace the current value. (Replacing 0 with 0? Yes, this doesn't actually change anything.)
Now that you've finished this iteration of the inner loop body, do the i++ (which should probably be j++) by replacing i's 0 with 1. Then do the test again: j is still less than 4, so do the inner loop body again, this time with a[1][0].
I'm going to stop here because it really is tedious, but hopefully you can see the process. The inner loop continues until its condition becomes false, then the outer loop increments i, starting the inner loop again but this time looking at a[1][0], a[1][1], and so on. That continues until the outer loop also makes its condition true. Finally, the last value of x is returned, and if you go through all the steps you'll get the same result the computer would. (Try it: once you get the hang of it, it'll be quicker than reading through the above, thank goodness.)
Okay, so that gives you the same sequence of steps the computer takes, and sometimes that level of detail is invaluable, especially when you have a bug such as assigning to the wrong variable name. But you may still end up not knowing why those particular operations, not seeing the wood for the trees. How can you work out what the purpose of the algorithm is?
High level
Another way we can look at the method is to work out what each statement does, and what the possible cumulative effect could be. For instance, the outer loop steps through each of the nested arrays, and the inner loop steps through each number within a nested array: so in combination, they step through every number within the array a. So something is happening with all the numbers.
Also, x is set to 0 at the start, and within the loops it sometimes has 0 added and sometimes 1. That tells us it's a counter, and by the end it'll tell us how often the condition was true: that is, how many of the numbers within a are equal to b. And so that's what the method returns: how many times b appears in a.
We can also tell the minimum value returned (0, when none of the numbers match), and the maximum (the total count of numbers, because at most 1 is added for each of them).
This is much more useful: we know what the method can be used for, and we can work out what the worst cases are: if we give it more than four billion numbers, a 32-bit int for the result wouldn't be enough, for instance; but it won't run forever (assuming j++) because the array has a fixed size, and it won't run out of memory because it doesn't allocate any other than for the variables.
But you need to be careful with this approach, because it's easy to make assumptions and miss details that change the outcome significantly: use the wrong kind of comparison or the wrong variable, or forget to clear a total, say, and you can end up with code that doesn't do what you think it does.
That can result in some of the most annoying bugs, when you stare at your code and you're sure it's right but somehow it still gives you the wrong answer. When that happens to you, switch to dry-running, re-examine your assumptions, or show your code to someone else: without your high-level knowledge of what the code should do, they can spot what it actually does.
Ultimately this is all a skill that you'll learn with practice, so keep writing and reading code.

Why are these printing different outputs?

I just want to understand the difference between for(int i =1;i<4;i++)
and for(int i =1;i++<4;)
The first one prints 123
The second one prints 234
for(int i =1;i<4;i++)
System.out.print(i);
for (int i =1;i++<4;)
System.out.print(i);
I do not understand why are the results different, I expect 123 from both of them.
This loop:
for (int i =1;i++<4;)
increments i before System.out.print(i), which means the first printed value of i will be 2.
In the standard for loop, i is incremented after the loop iteration. From the Java Tutorials:
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
In the second example, it is incremented in the expression where it is evaluated, but because the post increment operator is used, the value evaluated is the old value. This means that by the time it is printed, it has already been incremented.
To explain I've refactored the statements only by using curly braces...
for(int i =1;i<4;i++) {
System.out.print(i);
}
System.out.println();
for (int i =1;i++<4;) {
System.out.print(i);
}
System.out.println();
Inside the first 'for' statement - the third clause with "i++" doesn't happen until the contents of the loop is executed.
Next consider the second 'for' statement, the comparison clause (the 2nd clause). that will be completely evaluated before the contents of the loop is started. So going into the first iteration, "i++" gets evaluated as "1" for the purpose of the comparison, but immediately gets incremented after the boolean clause is evaluated.
So when it hits the print statement it's already equal to 2. (and so on)
I hope that helps!

How do I have an array in a for loop that actually changes the size of the for loop at each run?

I want my for loop to have the length a changing number. Can i do that?
I havent really tried anything
for (int i=0; i < colsAdd[i] ; i++){
System.out.print(" 0.0");
}
Actually the colsAdd[0] is the only size.
I'm not sure if I understand exactly what you're asking, but it seems like you're wondering what you are allowed to put into the different parts of a for loop, and the order that they run in.
If we change the code you pasted above to match the diagram below, the rules will become apparent.
for (initialization; condition; updateCounter){
codeInsideLoop
}
Any code can go into those portions of a for loop, they can even be left blank! For instance, the following code is equivalent to a while(true) loop.
for (;true;){
System.out.print("This will run forever!");
}
Or this for loop increments inside of the loop.
for (int i=0; i < 10;){
System.out.print("This will print 10 times");
i++;
}
More in line with your question, this code calls a function each iteration to see if it should continue looping. This function could use any logic to return a boolean value. It will execute at the end of every singe loop regardless.
for (int i=0; keepLooping(i); i++){
System.out.print("This will print 10 times");
i++;
}
Now, just because you can do these things does not mean you should! Generally you want to keep the structure of your loops simple so everyone can understand what your goal is.

forToWhile on Practice-It

I'm currently a beginner in java and while practicing I came across this practice site, and I can't quite seem to get part c. I'm supposed to convert the given for loop code into a while loop code, and I'm not sure why my code doesn't print out the exact same thing as the for loop. Any help would really be appreciated!
You need to move
int j = 1; to inside the first loop, below while (i <= 2) {
int k = 1; to inside the second loop, below while (j <= 3) {
If you don't do that, then neither of the inner loops will run after the first iteration of the outer loop, because their exit conditions have already been met. But resetting the index variables to 1 in both cases allows the inner loops to re-run.

Categories

Resources