Java do while loop increment - java

int i = 10;
int j = 0;
do {
j++;
System.out.println("loop:" + j);
while (i++ < 15) { //line6
i = i + 20;
System.out.println(i);
} ;
} while (i < 2);
System.out.println("i_final:" + i);
Output:
loop:1
31
i_final:32
Why the i_final is 32 and not 31? As we can see the do_while loop has executed only once, so line 8 should also have executed only once, hence incrementing the value of "i" by 1. When did 31 increment to 32?

While loop will be executed twice before its break.
while (i++ < 15) { //line6
i = i + 20;
System.out.println(i);
} ;
First it increment to 11 .
Check with 15. Returns true.
Now it increments to 31. (i = i + 20)
now again while loop .
it increments the value .

when you are doing a while loop as (i++ < 15) , it checks the condition and stop the loop if i++ is < 15 , But here when you do a do while loop j++ the loop goes 2 times and when it comes to while (i++ < 15) it increaments the value of i by 1 and stops... so in second loop the value of i increases by one but the function inside the while loop remains the same as it stops when i++ is > than 15
IF you do the following you will get 31
int i = 10;
int j = 0;
do {
j++;
System.out.println("loop:" + j);
while (i < 15) { //line6
i++
i = i + 20;
System.out.println(i);
} ;
} while (i < 2);
System.out.println("i_final:" + i);

First time when while loop condition is checked i=11, after that i is incremented by 20, so i=31. Then while condition is checked again, when found that 31 < 15 is false i is still incremented by 1. So i =32

Related

For loop java making the output into 2 columns

Hi I'm a beginner and I'm still learning and if someone could help me in this one thx in advance my code is:
for(int i = 0; i < 10; i++) {
System.out.println(i);
}
and the output should be like this:
0 1
2 3
4 5
6 7
8 9
Just use next line only for odd numbers:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0)
System.out.format("%2d", i);
else
System.out.format(" %2d\n", i);
}
Output:
0 1
2 3
4 5
6 7
8 9
P.S. For more general usage, I would extract it into separate method
public static void printTwoColumns(int min, int max) {
int width = String.valueOf(max).length();
for (int i = min; i < max; i++) {
String str = String.format("%" + width + 'd', i);
if (i % 2 == 0)
System.out.print(str);
else {
System.out.print(' ');
System.out.println(str);
}
}
}
You can do something like this:
for (int i = 0; i < 10; i++) {
System.out.print(i);
System.out.println(++i);
}
The first print uses the current i value and using System.out.print.
The second
print is using println so it goes one line down and also takes ++i so it will advance i by 1 and will also print the new value.
Each loop iteration is printing two values and advances i by total of 2.
To do what you want you can either do something like this:
for(int i = 0; i < 10; i ++){
if(i % 2 == 0){
System.out.print(i); //Only for evens
}else{
System.out.println(i); //Only for odds
}
}
Or you could simplify it even more with something like this:
for(int i = 0; i < 5; i += 2){
System.out.println(i + " " + (i + 1));
}

Printing rows of increasing amounts of even numbers

I'm trying to print the following:
2
2 4
2 4 6 ..etc
The code I have written (below) prints the following:
2
4 6
8 10 12 ...etc
Can anyone spot where I'm going wrong? The n variable comes from the main method which I am not including.
public static void printEvenTable(int n) {
int i;
int j;
int k = 0;
for (i = 1; i <= n; i++) {
for (j = 0; j < i; j++)
System.out.print(" " + (k += 2));
System.out.println(" ");
}
}
You need to prevent the variable k from using its old value by reassigning 0 to it right after the second for loop. Placing k = 0; before the second for loop makes redundant reassigning because it has already been assigned right before the loop. Ensure program optimization. If you are using a good editor, it show you some warning if placed before the second for loop.
for (i = 1; i <= n; i++) {
for (j = 0; j < i; j++) {
System.out.print(" " + (k += 2));
}
k=0;
System.out.println(" ");
}
Here, the inner loop is increasing the variable k by 2 in each steps after the first execution of the inner loop k becomes 2 from the initial value 0. In the second iteration of the outer loop k starts as 2. After k+=2, k becomes 4 so second line of output starts from 4. That's why we need to re-initialize k to 0 before each inner loop.
public static void printEvenTable(int n) {
int i;
int j;
int k = 0;
for (i = 1; i <= n; i++) {
k = 0;
for (j = 0; j < i; j++)
System.out.print(" " + (k += 2));
System.out.println(" ");
}
}

Multiplying odd numbers of 1-15

I've written the following code:
int oddProd = 1;
for(int count = 1; count >= 15; count++){
if (count % 2 != 0)
oddProd = oddProd * count;
}
System.out.println("Odd Product: " + oddProd);
Why doesn't this work? It outputs 1, and I checked, it doesn't even enter the for loop!
for(int count = 1; count >= 15; count++){
You have the expression written the wrong way around; it is now count >= 15 but it should be count <= 15.
The middle part of the for loop is the boolean check, and yours will always be false:
count >= 15;
This won't work since it won't be true in the beginning, and your loop won't start. Change the greter than operator to a less than one:
count <= 15;

How do I read a loop that has no braces?

I'm trying to read the output of this code, but it simply just doesn't make sense to me.
Even after learning that a loop without braces only loops through the first line, the output still makes no sense, at all. Some numbers do, but others just don't.
My code:
int n = 8;
int i = 1;
int j = 1;
j = n + 2;
System.out.println (n + " " + i + " " + j );
while (n > 1)
{
n = n/2;
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
j++;
}
System.out.println (n + " " + i + " " + j );
And it outputs:
8 1 10
4 2 10
4 4 10
2 2 11
1 2 13
I get the 8-1-10
and the 4-2-10
but anything after that, I'm stumped, I don't get how the computer calculates the rest.
Would someone mind going through the rest of the output with me, step by step?
Thank's in advance.
No braces means that the loop affects only the next statement that follows the loop.
So
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
is equivalent to
for (i = 2; i <= n; i = i+2)
{
System.out.println (n + " " + i + " " + j );
}
Usually, indentation is used in those cases to make the code more comprehensible, like this:
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
EDIT: Now, this is the actual answer to the question. It all depends on the different iterations the loop does and how do the variables get incremented.
int n = 8;
int i = 1;
int j = 1;
j = n + 2; //This means that j takes the value 10.
System.out.println (n + " " + i + " " + j ); // 8 1 10 So far, so good.
Now, on with the iteration:
while (n > 1)
{
n = n/2;
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
j++;
}
For the first iteration, we have n=8 i=1 j=10, so since n > 0 is true the loop takes place.
n = n / 2; //n = 4
Then, the for (note that it just assigns the value 2 to i):
for (i = 2; i <= 4; i = i+2) //Since n = 4
Since n = 4, the only values that i can take are 2 and 4, then the prints are:
4 2 10
4 4 10
After that, j is incremented by one, making it j = 11. The condition for the while is met again because n = 4. n = n/2 makes n take the value 2, so it enters the while again. Let's take a look at the for again:
for (i = 2; i <= 2; i = i+2) //Since n = 2
This time, the only value that i can take is 2 (note that the value of i is reset again to 2 while starting the iteration), and that's the print you get.
2 2 11
Before iterating again, j++ makes j have the value 12.
On the final iteration, n = n/2 results in n = 1 since n is an int but this is done inside the while, so it enters again. Now that n = 1 the loop looks like this:
for (i = 2; i <= 1; i = i+2) //Since n = 1
i is set to 2 and the condition for the for is not met (2 <= 1 is false). Then there is no print this time, yet j is incremented to 13 at the end of the while.
In the next iteration you have n = 1, that means that the while's condition is not met so the iteration breaks. Finally you have n = 1, i = 2 and j = 13. That's the last print you get.
You start the while loop with n = 8, i = 1 and j = 10.
start while: (n=8 > 1) is true
n = 4
i = 2 (i <= 4, so do for loop, then change i to i+2=4)
print 4,2,10
i = 4 (i <= 4, so do for loop again, then i = i+2 = 6
print 4,4,10
i = 6 (i <= 4 is false, so exit for)
j++ so j becomes 11
next while:
n = n/2 = 2
i = 2 (i <= 2, so do for loop, then change i to i+2=4)
print 2,2,11
i = 4 (i <= 2 is false, so exit for)
j++ -> j = 12
next while:
n = n/2 = 1
i = 2 (i <= 1 is false, so exit loop)
j++ -> j = 13
exit while.
Final print= n = 1, i = 2 (value assigned in last for loop, loop doesn't get executed so i doesnt get incremented by 2), and j = 13
Hope this helps :)

Print an array elements with 10 elements on each line

I just created an array with 100 initialized values and I want to print out 10 elements on each line so it would be somthing like this
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16
...26
this is the code I used and I managed to do it for the first 10 elements but I couldn't figure out how to do it for the rest
public static void main(String[] args) {
int[] numbers = { 0,1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};
int i, count = 0;
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 9)
for (i = 9; i < numbers.length; i++)
System.out.println(numbers[i] + " ");
}
}
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
if (i % 10 == 0 && i > 0) {
System.out.println();
}
System.out.print(numbers[i] + " ");
}
This prints a newline before printing numbers[i] where i % 10 == 0 and i > 0. % is the mod operator; it returns the remainder if i / 10. So i % 10 == 0 when i = 0, 10, 20, ....
As for your original code, you can make it work with a little modification as follows:
int count = 0;
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
Basically, count is how many numbers you've printed in this line. Once it reaches 10, you print the newline, and then reset it back to 0, because you're starting a new line, and for that line, you haven't printed any numbers (yet).
Note that in above two solutions, an extra space is printed at the end of each line. Here's a more flexible implementation that only uses separators (horizontal and vertical) when necessary. It's only slightly more complicated.
static void print(int[] arr, int W, String hSep, String vSep) {
for (int i = 0; i < arr.length; i++) {
String sep =
(i % W != 0) ? hSep :
(i > 0) ? vSep :
"";
System.out.print(sep + arr[i]);
}
System.out.println(vSep);
}
If you call this say, as print(new int[25], 5, ",", ".\n");, then it will print 25 zeroes, 5 on each line. There's a period (.) at the end of each line, and a comma (,) between zeroes on a line.
Why do you use 2 nested loops where you only need to remember at which places you need to output a linebreak? Also using the same variable i for both loops will not do what you expect.
How about:
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10)
System.out.print("\n");
count = 0;
}
}
All you are going to have to do is to print out a newline after every ten numbers.
for (i = 0; i < numbers.length; ++i)
{
System.out.print(number[i]);
if (i % 10 == 9)
{
System.out.println();
}
else
{
System.out.print(" ");
}
}
I know this is an old question, but I just wanted to answer. In java 8 you can do this in one line. Arrays.stream(arr).forEach(s->System.out.print(s%10 > 0 ? s+" ":"\n"));

Categories

Resources