Need explanation for the output of the following java code - java

public class Test {
public static void main (String args[]) {
int i = 0;
for (i = 0; i < 10; i++);
System.out.println(i + 4);
}
}
The output of the following code is 14.Why it is not 4?
And how can it be 14? Need some explanation
Thank you in advance...

for (i = 0; i < 10; i++);
This loop does nothing but incrementing i by one, 10 times .
Then
System.out.println(i + 4);
evaluates to
System.out.println(10 + 4);
// output
14
If you drop the semi colon at the end of for (i = 0; i < 10; i++);, you shall get
4
5
6
7
8
9
10
11
12
13
as an output.

Simple.
The loop increments i by 10 without doing anything else (notice the ; after the for loop definition)
The System.out statement prints i + 4 outside the loop (only once), i.e. 14

See description in comments:
// Declare variable 'i' of type int and initiate it to 0
// 'i' value at this point 0;
int i = 0;
// Take variable 'i' and while it's less then 10 increment it by 1
// 'i' value after this point 10;
for (i = 0; i < 10; i++);
// Output to console the result of the above computation
// 'i' value after this point 14;
System.out.println(i + 4);

System.out.println(i + 4); will get evaluated and executed after for (i = 0; i < 10; i++); statement is evaluated.
Result of for (i = 0; i < 10; i++); will be 10. The condition i < 10 will be true till i=9 which is the 10th iteration and in the 11th iteration i will be 10 as i++ will be computed and here the i<10 condition fails. Now final value of i will be 10.
The next statement System.out.println(i + 4); is evaluated which is i(=10)+4 = 14

Related

Why wont console print values of i under 2 in FOR loop if it can print values over 2?

Basically what my title says. Here's a piece of code
for (int i = 9; i >= 2; i--) {
system.out.println(i + " ");
}
this prints all values until 2, hence suggesting that starting from 9 and provided it doesn't go lower than 2, i should be printed. which it does.
now this one doesn't
for (int i = 9; i <= 2; i--) {
system.out.println(i + " ");
}
what i figure is it should count down to 2 without printing anything, then print 2 and 1, since the criteria is for all values equal or under 2, print i. However nothing shows on the console.
my understanding of the FOR loop might be wrong and i'm really trying to perfect my knowledge of basic concepts so id appreciate your help.
The basic concept is :
first loop => i=9, check if 9 >=2 = true , print 9 , i = i - 1
second loop => i=8, check if 8 >=2 = true , print 8 , i = i - 1
.
.
.
last loop=> i=1, check if 1 >=2 = false , end
in your second example
first loop => i=9, check if 9 <=2 = false , end
Hope i help you understand the for loop
Loop is only executed if the condition is true. If it is false, then loop will never be executed.
If you wanted to count down from 9 and only print 2 and 1, you'd have to write something like this:
for (int i = 9; i >= 1; --i) {
if (i <= 2) {
System.out.print(i + " ");
}
}
Of course, if all you wanted was to print 2 and 1, you'd normally just write:
for (int i = 2; i >= 2; --i) {
System.out.print(i + " ");
}
You wouldn't typically start the count at 9 unless you wanted to do something with the numbers 9 to 3 (other than ignore them, that is) as well as 2 and 1:
for (int i = 9; i >= 1; --i) {
if (i <= 2) {
System.out.print(i + " ");
} else {
System.out.println("We're not going to print " + i);
}
}

Sequence of loops making indefinite program

I am trying to make a program that takes all the combinations of a dice (got that part done) but now I am trying to take all the combinations and put them in an array by there total ( (1,1) = 2, (2,4) = 6 ) and I will eventually implement it into a game. But when trying to organize them I created an infinite loop that does not seem like it should be running infinitely.
for (int dice1 = 1; dice1 < 7; dice1++)
for (int dice2 = 1; dice2 < 7; dice2++)
for (int j = 0; j < 6;)
{
msg = "";
msg = "(" +dice1 + ", " + dice2 + ")";
arrayDice[dice1 - 1][dice2 - 1] = msg;
add = dice1 + dice2 - 2;
arrayAdd[add][j] = msg;
if (add == 10 - j)
j = j + 1;
}
the arrayDice is just the array of all combinations while the arrayAdd is all the added combinations. I really can't find where the problem is coming from.
Third for loop in your program is the one that is running infinitely. In the third loop, you are not incrementing the counter 'j' within the for statement but you increment it within the body of the loop. However, the only place in the body of the third loop where the counter 'j' is increasing is within an if statement - if (add == 10 - j). Since you start this loop with j=0, the expression 10 - 0 = 10 for the first iteration while the variable 'add' is 1 + 1 -2 = 0. So this expression if (add == 10 - j) evaluates to false. So j never gets incremented. The only other variable in this expression is 'add' which doesn't get changed until you come out of the third loop. So in short the expression if (add == 10 - j) never evaluates to true and hence j is never incremented resulting in the third loop running infinitely.

Array value post-increment

I've been working on a few array examples. with some success along alone the way. I've been working on this code for the pass few days and just cant understand the purpose of this increment in the loop body. it usually makes since when it is isolated but this time i have no idea what it does.
Count the occurrences of integers between 1 and 10
Scanner input = new Scanner(System.in);
int[] count = new int[10];
System.out.println("Enter the integers between 1 and 10: ");
// Read all numbers
// 2 5 6 5 4 3 9 7 2 0
for (int i = 0; i < count.length; i++)
{
int number = input.nextInt();
count[number]++; //this is the one that perplexes me the most
}
//Display result
for (int i = 0; i < 10; i++)
{
if (count[i] > 0)
{
System.out.println(i + " occurs " + count[i]
+ ((count[i] == 1) ? " time" : " times"));
}
}
count[number]++; //this is the one that perplexes me the most
It increments the value in the array count at index number. Perhaps, splitting it may help understand:
int tmp = count[number];
tmp = tmp + 1;
count[number] = tmp;
i.e. The value of count[number] will be incremented after the execution of the the statement count[number]++;.
Also a note on how post-increment works.
If it were used as:
int value = count[number]++;
then value will have the old value at count[number] and the increment will be done after the execution of the statement.

I don't understand why this is doing this action? I just need it explained

I just need something explained to me. When we declare ints It was my notion that it doesn't matter where you declare it as long as its in the beginning so I made this little bit of code to print out a multiplication table.
import java.util.Scanner;
public class Learn {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int last = 5;
int i = 1;
while (i <= last){
int j = 1;
while (j <= last) {
System.out.print(i*j);
System.out.print(" " );
j = j + 1;
}
System.out.println();
i = i + 1;
}
}
}
This prints out.
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
but If I take the int j = 1; and I put it outside of the while loop above it it only prints out 1 2 3 4 5. Why does this happen?
If j = 1 is inside the loop, then it will be reset every-time that the outer loop loops.
If not it will not be reset and the condition of j <= last will not be true on subsequent loops.
When you put j outside the while loop, it's value will be initially 1 and will continue accumulating/increasing
but if j will be inside the first while loop, j will be initially 1 until 5 only. It is because it is always set to 1 every time 1 loop is executed.
To correct your notion:
You had also initialize the variable j aside from declaring it.
Declaring:
int j;
Initializing:
int i;
Initializing and Declaring:
int j=1;
:)

Sequence For Loop

I'm trying to create a for loop to sequentially add 4 to a random value (r) as many times as the value of (n).
I came up with this:
for (int counter = 1; counter <=n; counter++){
System.out.println(a = a + 4);
}
The thing is if the random value were to be 10 for example, it will start counting from 14, 18, 22.
I want it to start counting at the number itself so the results are 10, 14, 18 not to start +4 from the random number selected.
Change your loop body to:
System.println(a);
a += 4;
Or the whole loop to
for (int counter = 1; counter <=n; counter++, a += 4){
System.out.println(a);
}
Then do not increase a before printing it.
a = a + 4 will first increment a by 4 store the result in a and only then print it.
What you need is :
for (int counter = 1; counter <=n; counter++){
System.out.println(a);
a += 4;
}
Print the current number before adding 4 to it, then.
System.out.println(a); // print the number
a = a + 4; // THEN add 4
for (int counter = 1; counter <=n; counter++){
System.out.println(a+4*(counter-1));
}

Categories

Resources