Why does the for loop output this? - java

I am just very confused from this homework problem. I do not understand why the values of i and sum come out this way. I just do not understand the concept of the algorithm here, can someone please explain this?
int i = 0;
int sum = 0;
for(i=0; i < 5; i++)
{
sum += i;
}
System.out.println(i + "\n" + sum);
The output is:
5
10
----jGRASP: operation complete.

5 - because there are 5 iterations
10 - because the sum is 10 :)
Sum
Iteration 1: 0 + 0 = 0
Iteration 2: 0 + 1 = 1
Iteration 3: 1 + 2 = 3
Iteration 4: 3 + 3 = 6
Iteration 5: 6 + 4 = 10
Verification code
int i = 0;
int sum = 0;
for (i = 0; i < 5; i++) {
System.out.println(String.format(
"Iteration %s: %s + %s = %s", (i + 1), sum, i, (sum + i)));
sum += i;
}

This code :
int i = 0;
int sum = 0;
for(i=0; i < 5; i++)
{
sum += i;
}
System.out.println(i + "\n" + sum);
output in sum this : 0 + 1 + 2 + 3 + 4 which is equal to 10 and i the number of iterations = 5.

You have created a variable i with value of 0 and then incrementing it 5 times in for-loop. So you got i's value as 5.
Now the value of sum is 0+1+2+3+4 which is 10

Because you iterate through your loop, which makes i == 5, then print it,
Sum goes as below, you are adding i to the previously calculated sum
0 + 1 = 1
1 + 2 = 3
3 + 3 + 6
6 + 4 = 10
Try put your print command inside the loop, they you can see better what's going on.

The only non-obvious thing is (in my opinion): i will be 5, because you used i++, which also incremented i by 1 even though the body did not execute after the last iteration. Inside the body i only can be maximum 4.
int sum = 0; int i = 0;
for (i = 0; i < 5; i++)
{
sum += i;
if (i == 5)
System.out.println("never executed");
};
Other answers tell the other things.

Related

What is supposed to be the Time Complexity of this loop

What should be the time complexity of this code?
I am thinking (n^2 -n) as the loop will run n(n-1)/2 times.
for (int i = 0; i < n-1; i++) {
for (int j = i + 1; j < n; j++) {
System.out.println(i + "i " + j + " j");
}
}
i: outer loop runs n - 1 times
j: inner loop runs n - (i + 1) times
Analyze it with a small number, say n = 10.
The outer loop will run 9 times.
The inner loop will run as follows
i = 0: 9 times
i = 1: 8 times
i = 2: 7 times
...
i = 8: 1 time
Therefore
n * ( n - 1) = n ^ 2 - n
For very large values of n, n is insignificant when compared to n squared.
See also wikipedia asymtotic analysis.

Arithmetic Progression in java

i'm just started to learn java yesterday. But, now i met difficulty to show the arithmetic progression like the display below:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
From that example, i know that every odd numbers, the numbers increment. I've tried to make it, but the display just keep showing like this:
2 4 4 4 6 6 6 6 6 8 8 8 8 8 8 8 10 10 10 10 10 10 10 10 10
Here's my code:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print(i + " ");
}
}
}
And then, i want to take the last value of it. For example, if i have row = 3, it must be value = 2.
because :
row = 1 2 3 4 5 6 7 8 9 10
value = 1 2 2 2 3 3 3 3 3 4
Would you tell me, what line is exactly must be fix? Thank you
It's not about a line that is wrong, it's your approach that's a bit off. You could fix it in multiple ways. Easiest (but not most efficient) way is this:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print((i/2) + " ");
}
}
}
As you can see, only the output was changed and now it works. However, iterating over 11 numbers (0-10) when you only really care about 4-5 is not necessarily the best way to go here.
It also doesn't make your code easy to understand.
Here's an alternative.
int amount = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < amount; j++) {
System.out.print(i + " ");
}
amount = amount + 2;
}
Here you can see that the outer for has been changed to only take the numbers we actually care about, which means we can remove the if completely.
We just have to somehow decide how many times we want to execute the print call, which is done with the amount variable.
Try this.
for (int i = 1, r = 1; i <= 4; ++i, r += 2)
System.out.print((i + " ").repeat(r));
You can calculate value from row with this method.
static int value(int row) {
return (int)Math.ceil(Math.sqrt(row));
}
So you can also do like this.
for (int row = 1; row <= 16; ++row)
System.out.print(value(row) + " ");
result:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
Hey it's a representation of a sequence that grows by 2 every step.
i.e the first element is 1 which shows up one time.
the second element is 3 which shows up 3 times (2 2 2)
and so on and on..
so the code you need is:
int a = 1;
for(int i=1; i<=10;i++){
int j=1;
while(j<=a){
System.out.print(i);
j++;
}
a+=2;
}
printing the value in a wanted row:
Scanner in = new Scanner(System.in);
int rowU = in.nextInt(); // User inputs row
int row = 1; // a variable to keep track of the rows
int repeats = 1; // the number of times a value shoud appear
for(int value=1;value<=10;value++){
int j=1;
while(j<=repeats){
if(row==rowU) // if we got to the wanted row
System.out.println(value); // print the wanted value
j++;
row++;
}
repeats+=2;
}
There is a better, more efficient way to get the value of a wanted row:
int wanted_value = Math.ceil(Math.sqrt(wanted_row));
Thanks to #saka for bringing this one up!
Hope I helped :)
i % 2 == 0 means that the following code is only going to be executed, if i is even.
You could try removing the if, and change the second for to something like
int j = 0; j < 2 * i - 1; j++.
This code snippet will do the work
int n=4;
int printTimes=1;
for(int i=1;i<=n;i++)
{
for(int j=0;j<printTimes;j++)
System.out.print(i+" ");
printTimes+=2;
}
System.out.println();
Here is the example code.
int start = 1;
int end = 5;
int time = 1;
for (int i = start,j = time; i < end; i++,j+=2) {
for (int k = 0; k < j; k++) {
System.out.print(i+" ");
}
}

Loops with no body,i got the code from a book but i dont understand the math in the code

public class Main {
public static void main(String[] args) throws IOException {
int i;
int sum=0;
for(i=1;i<=5;sum+=i++)
System.out.println(sum);
}
...
}
Actual Output:15
I don't know how it did the math?
The syntax for the for loop is:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
and is basically equivalent with the following while loop:
[ForInit]
while (Expression) {
Statement
[ForUpdate]
}
That mean that all the following are the same:
for(i=1;i<=5;sum+=i++);
i = 1;
while (i <= 5) {
sum += i++;
}
i = 1;
while (i <= 5) {
sum += i;
i++;
}
for (i = 1; i <= 5; i++)
sum += i;
So it is calculating 1 + 2 + 3 + 4 + 5 = 15
What confuses you is the part
sum += i++
In this statement, first sum=sum+i gets calculated. Once sum has been calculated, value of i is incremented by 1.
Since the loop runs five times, previous value of sum gets added to current value of i, which keeps increases by 1.
Try printing out each iteration through the loop to help you visualise what is going on. Swap your for loop for this.
for(i=1;i<=5;sum+=i++)
{
System.out.println("sum = " + sum);
System.out.println("i = " + i);
}
In this code, the statement sum+ = i++ means sum = sum + i++ In this statement, every sum printed in the loop adds to one increment of i and when the loop ends it will display 15.
So it is calculating 0 + 1 + 2 + 3 + 4 + 5 = 15

find if 3 numbers in an array add up to a sum

I have a method written to determine if a sum exists in an array. So the rule is there must exist 3 numbers in the array such that adding them all together equals to a given sum. So in the array {1,2,3,14,12} if i was searching for a sum of 6 then 2+3+1 would be the numbers that give me 6. From researching online this can be done with a set so i have the following function which works but im having a hard time understanding the logic:
public void existsSum(int[] numbers,int sum){
Set<Integer> set = new HashSet();
for(int i=0;i<numbers.length;i++){
int s1=sum - numbers[i];
for(int j=0;j<numbers.length;j++){
int s2=s1-numbers[j];
if(set.contains(s2)) {
System.out.format("sum of %d + %d + %d gives %d \n", numbers[i], numbers[j],s2, sum);
assert(numbers[i]+numbers[j]+s2==10);
}
}
set.add(numbers[i]);
}
}
I dont understand what is the significance of s1 and s2 ? can someone explain to me the logic. The method itself works fine and if i run it with the following it yields the correct results:
int[] integers = {1,2,3,4,5,6,7,8,9};
existsSum(integers,10);
sum of 2 + 7 + 1 gives 10
sum of 3 + 5 + 2 gives 10
sum of 3 + 6 + 1 gives 10
sum of 4 + 3 + 3 gives 10
sum of 4 + 4 + 2 gives 10
sum of 4 + 5 + 1 gives 10
sum of 5 + 1 + 4 gives 10
sum of 5 + 2 + 3 gives 10
sum of 5 + 3 + 2 gives 10
sum of 5 + 4 + 1 gives 10
sum of 6 + 1 + 3 gives 10
sum of 6 + 2 + 2 gives 10
sum of 6 + 3 + 1 gives 10
sum of 7 + 1 + 2 gives 10
sum of 7 + 2 + 1 gives 10
sum of 8 + 1 + 1 gives 10
Your code doesn't work, because i and j may point to the same number.
Also, the assert hardcodes the sum to find as 10.
Anyway, the main logic without set is 3 nested loops:
Loop 1: Loop thru all numbers.
Loop 2: Loop thru all numbers following current number from loop 1.
Loop 3: Loop thru all numbers following current number from loop 2.
If sum of the 3 current numbers is correct, print it.
for (int i = 0; i < numbers.length; i++)
for (int j = i + 1; j < numbers.length; j++)
for (int k = j + 1; k < numbers.length; k++)
if (numbers[i] + numbers[j] + numbers[k] == sum)
System.out.println("sum of %d + %d + %d gives %d\n",
numbers[i], numbers[j], numbers[k], sum);
For performance improvement, the innermost loop can be optimized, by instead calculating the 3rd number as num3 = sum - num1 - num2, then see if it is in the list of numbers.
To prevent using the same number more than once, the logic of the 3rd check is reversed to check against all numbers preceding the current number from loop 1, and to build the set of such numbers as the first list is iterated.
Pseudo-code:
set = new set()
for (int i = 0; i < numbers.length; i++)
for (int j = i + 1; j < numbers.length; j++) {
num3 = sum - numbers[i] - numbers[j]
if (num3 in set)
print("sum of %d + %d + %d gives %d\n",
num3, numbers[i], numbers[j], sum);
}
add numbers[i] to set
}
The function is simply trying to find the number s2 in the set where s2=sum-first_number-second_number. The two loops help you to iterate over all numbers in the list as first_number and last_number.
Finally searching for s2 in the set tells you that s2+first_number+last_number is equal to the sum.

Pre- and postincrement in Java

I just wanted to create a little Java-Puzzle, but I puzzled myself. One part of the puzzle is:
What does the following piece of code do:
public class test {
public static void main(String[] args) {
int i = 1;
i += ++i + i++ + ++i;
System.out.println("i = " + i);
}
}
It outputs 9.
My (at least partly) wrong explanation:
I'm not quite sure, but I think the term after i += gets evaluated like this:
So
int i = 1;
i += ++i + i++ + ++i;
is the same as
int i = 1;
i += ((++i) + (i++)) + (++i);
This gets evaluated from left to right (See Pre and postincrement java evaluation).
The first ++i increments i to 2 and returns 2. So you have:
i = 2;
i += (2 + (i++)) + (++i);
The i++ returns 2, as it is the new value of i, and increments i to 3:
i = 3;
i += (2 + 2) + ++i;
The second ++i increments i to 4 and returns 4:
i = 4;
i += (2 + 2) + 4;
So you end up with 12, not 9.
Where is the error in my explanation? What would be a correct explanation?
i += ++i + i++ + ++i; is the same as i = i + ++i + i++ + ++i;
The right-hand side is calculated from left-to-right, yielding i = 1 + 2 + 2 + 4; (which yields i = 9).
The output is 9 (try it)
int i = 1;
i += ++i + i++ + ++i;
becomes
i = 1 + 2 + 2 + 4
You're right regarding the right part evaluation, but you're missing a detail regarding the assignment.
Run this :
i = i++;
or this :
i += i++;
After both operations, i still has its original value.
That's because i is evaluated on the left before the right part of the assignment.
So in your case, you're adding 8 to 1, not to 4.
it's very easy to understand how it works if you imagine it how java stores values in registers! he puts 1 in the first register, and than goes through = sign, and increments the i(++i), so now in i you have 2, and in the second register you have 2, but the first register is not updated, in the third register you'll have 2 and then i is incremented, and then i is incremented and in the last register you'll have 4. So you'll have something like this
1 = 2 + 2 + 4 == 9
The code
int i = 1;
i += ++i + i++ + ++i
is equivalent to
int tmp1 = i // 1, +=
i ++; // 2
int tmp2 = i; // 2
int tmp3 = i; // 2
i ++; // 3
i ++; // 4
int tmp4 = i; // 4
i = tmp1 + tmp2 + tmp3 + tmp4; // 9
i += ++i + i++ + ++i;
i=1 at start
i += X -> i = i + X -> i = 1 + X (so lets count X)
++i will be incremented to 2 and return 2
i++ will return 2 and then be incremented to 3
++i will be incremented from 3 to 4 and return 4
X = 2 + 2 + 4 = 8
So i = 1 + 8 -> i=9
You would get 12 if your code would be something like this
int i = 1;
int tmp = ++i + i++ + ++i;
i += tmp;
because then your code would be i=1, and after calculating tmp i would be i=4, then i+=tmp -> i=4+8=12

Categories