How many times could a variable be incremented in a single statement? - java

I am currently reading Barry Burd's Java For Dummies, and came upon this little exercise.
The exercise is regarding post and pre-increment. In the problem (please see the code) I was able to figure out the answers to all the lines(without the help of compiler) except for the last one. Which does not make sense according to my knowledge of post/pre-increment so far.
Please advise on how or why the result is not what I expected.
I tried initializing and declaring a new variable (int) with the value of "20" and then did "i = i++ + i++", but still received the same result (41).
Also tried doing out.println(i) twice, but it still printed 41.
import static java.lang.System.out;
public class Main
{
public static void main(String[] args) {
int i = 10;
out.println(i++); //10(post11)
out.println(--i); //10(pre11-1)
--i; //9(pre10-1)
i--; //9(post8)
out.println(i); //8
out.println(++i); //9(pre8+1)
out.println(i--); //9(post8)
out.println(i); //8
i++; //8(post9)
i = i++ + ++i; //i = 9(post10) + 10(pre9+1) = 19(post20)
out.println(i); //20
i = i++ + i++; //i = 20(post21) + 20(post21) = 40(post42)
out.println(i); //41 (result copied from compiler)
}
}
I expected the last line to print 42 rather than 41, since "20" gets added twice, and also gets incremented twice.

i = i++ + i++
This evaluates to (if i is 20):
i = 20 + 21
Since the first i++ is a post operator, and so doesn't affect it. However, it does affect the next usage of i.
I'll break it down step by step:
i =i+++ i++;, i == 20
i =20+ i++, i == 21
i = 20 +i++, i == 21
i = 20 +21, i == 22
i =41

When you use the assignment operator (=) it is done after the post increment operator. As such you get this:
int i = 10;
i = i++;
System.out.println(i); // print 10
When you are using the post increment twice in the same line, it is not increased after the line is completed, but after the instruction is completed (the instruction being i++). Thus, when doing i = i++ + i++; you are in fact doing this :
i = i++ + i++; // i=20 Original code
i = 20 + i++; // i=21 The first i++ return 20 then increment i to 21
i = 20 + 21; // i=22 The second i++ return 21 then increment i to 22
i = 41; // i=22 The addition is computed
41; // i=41 and assigne to i
It all as to do with operator precedence.

You can see what is happening by writing your own print routine.
int i = 9;
i = print(i++) + print(++i); // i = 9(post10) + 10(pre9+1) = 19(post20)
System.out.println("\n" + i); // 20
i = print(i++) + print(i++); // i = 20(post21) + 20(post21) = 40(post42)
System.out.println("\n" + i); // 41 (result copied from compiler)
public static int print(int i) {
System.out.print(" i = " + i + " ");
return i;
}

Related

Formatting returned Strings?

I'm really new to coding and just got assigned my first coding homework involving methods and returns. I managed to struggle through and end up with this, which I'm pretty proud of, but I'm not quite sure it's right. Along with that, my return statements are all on the same lines instead of formatted how my teacher says they should be ("n is a perfect number", then the line below says "factors: x y z", repeated for each perfect number. Below are the exact instructions plus what it outputs. Anything will help!
Write a method (also known as functions in C++) named isPerfect that takes in one parameter named number, and return a String containing the factors for the number that totals up to the number if the number is a perfect number. If the number is not a perfect number, have the method return a null string (do this with a simple: return null; statement).
Utilize this isPerfect method in a program that prompts the user for a maximum integer, so the program can display all perfect numbers from 2 to the maximum integer
286 is perfect.Factors: 1 2 3 1 2 4 7 14
It should be
6 is perfect
Factors: 1 2 3
28 is perfect
Factors: 1 2 4 7 14
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in) ;
System.out.print("Enter max number: ") ;
int max = input.nextInt() ;
String result = isPerfect(max) ;
System.out.print(result) ;
}
public static String isPerfect(int number) {
String factors = "Factors: " ;
String perfect = " is perfect." ;
for (int test = 1; number >= test; test++) {
int sum = 0 ;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
sum += counter ;
}
}
if (sum == test) {
perfect = test + perfect ;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
factors += counter + " " ;
}
}
}
}
return perfect + factors ;
}
}
Couple of things you could do:
Firstly, you do not need two loops to do this. You can run one loop till number and keep checking if it's divisible by the iterating variable. If it is, then add it to a variable called sum.
Example:
.
factors = []; //this can be a new array or string, choice is yours
sum=0;
for(int i=1; i<number; i++){
if(number % i == 0){
sum += i;
add the value i to factors variable.
}
}
after this loop completes, check if sum == number, the if block to return the output with factors, and else block to return the output without factors or factors = null(like in the problem statement)
In your return answer add a newline character between perfect and the factors to make it look like the teacher's output.
You can try the solution below:
public String isPerfect(int number) {
StringBuilder factors = new StringBuilder("Factors: ");
StringBuilder perfect = new StringBuilder(" is perfect.");
int sum = 0;
for (int i = 1; i < number; i++) {
if (number % i == 0) {
sum += i;
factors.append(" " + i);
}
}
if (sum == number) {
return number + "" + perfect.append(" \n" + factors);
}
return number + " is not perfect";
}
Keep separate variables for your template bits for the output and the actual output that you are constructing. So I suggest that you don’t alter factors and perfect and instead declare one more variable:
String result = "";
Now when you’ve found a perfect number, add to the result like this:
result += test + perfect + '\n' + factors;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
result += counter + " ";
}
}
result += '\n';
I have also inserted some line breaks, '\n'. Then of course return the result from your method:
return result;
With these changes your method returns:
6 is perfect.
Factors: 1 2 3
28 is perfect.
Factors: 1 2 4 7 14
Other tips
While your program gives the correct output, your method doesn’t follow the specs in the assignment. It was supposed to check only one number for perfectness. Only your main program should iterate over numbers to find all perfect numbers up to the max.
You’ve got your condition turned in an unusual way here, which makes it hard for me to read:
for (int test = 1; number >= test; test++) {
Prefer
for (int test = 1; test <= number; test++) {
For building strings piecewise learn to use a StringBuffer or StringBuilder.
Link
Java StringBuilder class on Javapoint Tutorials, with examples.

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

For Loop, the program will not follow my for loop

For Loop, I am trying to understand why the loop will not run. Does anyone have any loop examples I can see?
import java.util.Scanner;
public class Conversion
for (t = ttt; t >= ttt + 36; t +=5) //counter = counter + 5
{
}
System.out.println ("t \t ttt");
System.out.println(j + "\t\t " + i);
//Show result
Unless it overflows, i will never be greater or equal to i+36. You should use a different variable for your loop:
for (double j = i; j >= i + 36; j+=6)
First, i = i is redundant. If you already defined the variables, you can leave it empty.
Second, you are always asking if i is greater or equal to itself plus 36, in which is ALWAYS false. Try to pre calculate it.
double limit = i + 36;
for (; i >= limit ; i +=6) //counter = counter + 6
{ }
And by the way, be careful with iterating with double variables, you can have wrong outputs in Java, due to the way it treats the decimals. You could have an extra loop.
I hope I have helped.
Have a nice day :)
Your for loop has no body, and therefore it isn't doing what you want it to do. If you want to print out the conversion of inches to centimeters for every 6 inches between i and i+36 your for loop should be
System.out.println("Inches\tCentimeters");
for(double j = i; j <= i + 36; j += 6) {
System.out.printf("%f\t%f\n", j, inchesToCM(j));
}

Writing a For loop that prints 1 2 ... userNum?

I am not sure what I am doing wrong here. Here is the original prompt:
"Write a for-loop that prints: 1 2 .. userNum. Print a space after each number, including after the last number. Ex: userNum = 4 prints:
1 2 3 4"
Here is my code:
import java.util.Scanner;
public class CountToNum {
public static void main (String [] args) {
int userNum = 0;
int i = 0;
userNum = 4;
for (userNum = 1; userNum <= 4; ++userNum) {
System.out.print(userNum + " ");
}
System.out.println("");
return;
}
}
Your for-loop needs to use two different variables, one for checking against, and one for incrementing. You're also incrementing your variable before running the loop (++userNum), which means that you're counting from 2 to 4 instead of 1 to 4 like you meant to.
So, in your case, you would do the following:
for (i = 1; i <= userNum; i++) {
System.out.print(i + " ");
}
for (i = 1; i <= userNum; i++) {
System.out.print(i + " ");
}
What else did you declare i for?
You should use it when you declare it ;)
To print a range of numbers using a for-loop from 1 to a provided ending point, use this:
for (int x = 0; x <= end; x++) {
System.out.println(x + " ");
}
I believe that the problem with the code that you presented is that you're mixing up the ending point (where you call it userNum) and the temporary variable with which you iterate (which I call x, though different conventions may use i).

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