Java Incremental operator query (++i and i++) [duplicate] - java

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Java is NEVER pass-by-reference, right?...right? [duplicate]
(6 answers)
Closed 8 years ago.
I have the following code:
public class Book {
private static int sample1(int i) {
return i++;
}
private static int sample2(int j) {
return ++j;
}
public static void main(String[] arguments){
int i = 0;
int j = 0;
System.out.println(sample1(i++)); //0
System.out.println(sample1(++i)); //1
System.out.println(sample2(j++));//1
System.out.println(sample2(++j));//2
System.out.println(i);//2
System.out.println(j);//2
}
}
My expected output is in comments. The actual output is below:
0
2
1
3
2
2
I'm getting confused with the function calls and incemental operator. Can someone kindly explain the actual result?

Since sample1 and sample2 are just modifying their own local variables i and j (not those of the calling method), it's clearer if we rewrite them without those modifications:
private static int sample1(int i) {
return i; // was 'i++', which evaluates to the old i
}
private static int sample2(int j) {
return j + 1; // was '++j', which evaluates to j after incrementing
}
At which point it's straightforward to just substitute them in place — sample1(...) becomes ..., and sample2(...) becomes ... + 1:
int i = 0;
int j = 0;
System.out.println(i++);
System.out.println(++i);
System.out.println((j++) + 1);
System.out.println((++j) + 1);
System.out.println(i);
System.out.println(j);
We can make this a bit clearer by separating the incrementations into their own commands. i++ evaluates to the original value of i, so it's like incrementing i after running the surrounding command; ++i, by contrast, is like incrementing i before running the surrounding command. So we get:
int i = 0;
int j = 0;
System.out.println(i);
i++;
++i;
System.out.println(i);
System.out.println(j + 1);
j++;
++j;
System.out.println(j + 1);
System.out.println(i);
System.out.println(j);
. . . at which point it should be straightforward to trace through and see what it will output.
Does that all make sense?

First of all you need to know the difference between x++ and ++X;
In case of x++ :
First the current value will be used and it will be incremented next.
That means you will get the present value of x for the operation and if you
use x next time will get the incremented value;
In case of ++x :
First the current value will be incremented and it will be used (the incremented value) next, that means you will get the incremented value
at this operation and for other after this operation.
Now lets split the code and discuss them separately
method: sample1() :
private static int sample1(int i) {
return i++;
}
This method will take a int and return it first and then try to increment but as after returning the variable i will go out of scope so it will never be
incremented at all. exp in: 10-> out 10
method: sample2() :
private static int sample2(int j) {
return ++j;
}
This method will take a int and increment it first and then return it. exp in: 10-> out 11
In both case only the variables will change locally, that means if you call from main method the variables of main method will remain unaffected by the change
(as the sample1() and sample2() are making copy of the variables)
Now for the code of the main method
System.out.println(sample1(i++)); // it's giving sample1() `i=0` then making `i=1`
// so sample1() will return 0 too;
System.out.println(sample1(++i)); // it's making `i=2` and then giving sample1() `i=2`
// so sample1() will return 2;
System.out.println(sample2(j++)); // it's giving sample2() `j=0` then making `j=1`
// so sample2() will return 1;
System.out.println(sample2(++j)); // it's making `j=2` giving sample2() `j=2` then
// so sample2() will return 3;

You're experiencing the fun of prefix and postfix operators.
The prefix operator, ++i increments the variable i by one before using it in the expression, where the postfix operator (i++) uses i in the expression before incrementing it.
This means that your method sample1 doesn't do anything; it evaluates the expression containing i, but because that expression is a return statement, the local variable i goes out of scope, and we can't modify it anymore.
sample2, by contrast, increments the local copy of j before returning it, which is why you print higher values of j than you expect.

Easy:
1) First call:
a) Provide i (==0) to sample1(), which returns 0 (then increments the argument i, and that gets discarded).
b) increments i because of i++. i is now 1.
c) Prints the function result: 0.
2) Second call:
a) Increments i because of ++i. i is now 2.
b) Provide i (==2) to sample1(), which returns 2 (then increments the argument i, and that gets discarded)
c) Prints the function result: 2.
3) Third call:
a) Provide j (==0) to sample2(), which increments the argument, and therefore returns 1.
b) increments j because of j++. j is now 1.
c) Prints the function result: 1.
4) Fourth call:
a) Increments j because of ++j. j is now 2.
b) Provide j (==2) to sample2(), which increments the argument, and therefore returns 3.
c) Prints the function result: 3.
5 & 6) Fifth and Sixth call:
a) Prints the value of j: 2.
The key to remember here is that i++ increments the variable after passing it as an argument, whereas ++i increments the variable before passing it as an argument.
Hope this helps

1st print
before call: i = 0
increment after call
sample1 is called with a value of 0
sample 1 returns 0, the increment is discarded
after call: i = 1
2nd print
before call: i = 1
increment before call
sample1 is called with a value of 2
sample1 returns 2, the increment is discarded
after call: i = 2
3rd print
before call: j = 0
increment after call
sample2 is called with a value of 0
sample2 the increments 0 to 1, returns it
1 is printed
increment j to 1
after call: j = 1
4th print
before call: j = 1
increment before call
increment j to 2
sample2 is called with a value of 2
sample2 the increments 2 to 3, returns it
3 is printed
after call: j = 2
5th print
prints i
2 is printed
6th print
prints j
2 is printed

Both of them increase the variable i by one like i = i + 1;
The difference is that :
++i increments the value first and then return it
i++ return the value first and then increments it
This behavior difference doesn’t matter in a for loop.
If you want to know the difference try this :
int x = 0;
int y = x++;
int x = 0;
int y = ++x;
Here x++ returns the value then increments it but ++x first increments the value then returns that value

Form your example,
private static int sample1(int i) {
return i++;
}
private static int sample2(int j) {
return ++j;
}
public static void main(String[] arguments)
{
int i = 0;
int j = 0;
System.out.println(sample1(i++)); //0
System.out.println(sample1(++i)); //1
System.out.println(sample2(j++));//1
System.out.println(sample2(++j));//2
System.out.println(j);//2
System.out.println(j);//2
}
i = 0; sample1(i++) -> it pass '0'->in sample1 return i++ so, 0(++)
Here it returns 0 but incremented to 1 , so println is = 0 but finally i takes 1
i = 1; sample1(++i) -> it pass '2'-> in sample1 return i++ so, 2(++)
Here it returns 2, so println is = 2
j = 0; sample2(j++) -> it pass '0'-> in sample2 return ++j so, (++)0
Here it returns 1, so println is = 1.
j = 1; sample2(++j) -> it pass ++1 => 2, in sample2 return ++j so, (++)2
Here it returns 3, so println is = 3. But increment is ended with in sample2, not in
main so j still holds 2.
j = 2
j = 2

Related

putting a formula into a for loop

I'm trying to put this formula into a loop
The function to put inside the loop
I've used if statements to give me a specific result if the input is zero, but if the input is one or higher, the for loop should run.
I was given a question regards recursion and supposed to execute it 3 different ways one of them using a loop that I've already made and runs but gives unexpected results.
public class Assignment5Recursion {
public static int puzzleLoop(int n) {
int v=0;
if(n>=1) {
for(int i=1; i<=n+1; i++) {
v = (2*i-1);
}
return ((2*n+1)+2*v);
}
else {
return 1;
}}}
if n is 1, the result should be 5, if n is 2, the result should be 13, if n is 3, the result should be 25, if n is 7, the result should be 113, but for some reason, I'm getting different outputs, so I'm assuming that I've set the loop wrong.
You need to make 2 changes.
1)The loop will run from i=1 to i=n+1 whereas you only require it to run till i=n.
So the for loop exit condition should either be i<n+1 or i<=n
2)The variable v is going to be replaced every run of the loop as it is getting assigned a new value every time.
So the value for v will always be v=2*(n+1)-1 according to your code.
You need to make this v += (2*i-1) so that the new value of v gets added to the old value to get sigma(sum).
Replacing your for loop as below will solve your problem.
for(int i=1; i<n+1; i++) {
v += (2*i-1);
}
or
for(int i=1; i<=n; i++) {
v = v+(2*i-1);
}
You have made two mistake, instead of adding to v you are updating on every iteration, so total values doesn't get summed up. And since you are using <= you don't need to iterate upto n+1. So here is a revised puzzleLoop method for you
public static int puzzleLoop(int n) {
int v = 0;
if (n >= 1) {
for (int i = 1; i <= n; i++) {
v += (2 * i - 1);
}
return ((2 * n + 1) + 2 * v);
}
return 1;
}
You also don't need the else part statement since if it is not in the if block you can always safely return 1.
Σ(2*i-1), sum should be carried over the loop
change the statement in loop to v = v+(2*i-1) and condition to i<=n

adding 1 to an integer within println statement in Java [duplicate]

Is there a difference in ++i and i++ in a for loop? Is it simply a syntax thing?
a++ is known as postfix.
add 1 to a, returns the old value.
++a is known as prefix.
add 1 to a, returns the new value.
C#:
string[] items = {"a","b","c","d"};
int i = 0;
foreach (string item in items)
{
Console.WriteLine(++i);
}
Console.WriteLine("");
i = 0;
foreach (string item in items)
{
Console.WriteLine(i++);
}
Output:
1
2
3
4
0
1
2
3
foreach and while loops depend on which increment type you use. With for loops like below it makes no difference as you're not using the return value of i:
for (int i = 0; i < 5; i++) { Console.Write(i);}
Console.WriteLine("");
for (int i = 0; i < 5; ++i) { Console.Write(i); }
0 1 2 3 4
0 1 2 3 4
If the value as evaluated is used then the type of increment becomes significant:
int n = 0;
for (int i = 0; n < 5; n = i++) { }
Pre-increment ++i increments the value of i and evaluates to the new incremented value.
int i = 3;
int preIncrementResult = ++i;
Assert( preIncrementResult == 4 );
Assert( i == 4 );
Post-increment i++ increments the value of i and evaluates to the original non-incremented value.
int i = 3;
int postIncrementResult = i++;
Assert( postIncrementtResult == 3 );
Assert( i == 4 );
In C++, the pre-increment is usually preferred where you can use either.
This is because if you use post-increment, it can require the compiler to have to generate code that creates an extra temporary variable. This is because both the previous and new values of the variable being incremented need to be held somewhere because they may be needed elsewhere in the expression being evaluated.
So, in C++ at least, there can be a performance difference which guides your choice of which to use.
This is mainly only a problem when the variable being incremented is a user defined type with an overridden ++ operator. For primitive types (int, etc) there's no performance difference. But, it's worth sticking to the pre-increment operator as a guideline unless the post-increment operator is definitely what's required.
There's some more discussion here.
In C++ if you're using STL, then you may be using for loops with iterators. These mainly have overridden ++ operators, so sticking to pre-increment is a good idea. Compilers get smarter all the time though, and newer ones may be able to perform optimizations that mean there's no performance difference - especially if the type being incremented is defined inline in header file (as STL implementations often are) so that the compiler can see how the method is implemented and can then know what optimizations are safe to perform. Even so, it's probably still worth sticking to pre-increment because loops get executed lots of times and this means a small performance penalty could soon get amplified.
In other languages such as C# where the ++ operator can't be overloaded there is no performance difference. Used in a loop to advance the loop variable, the pre and post increment operators are equivalent.
Correction: overloading ++ in C# is allowed. It seems though, that compared to C++, in C# you cannot overload the pre and post versions independently. So, I would assume that if the result of calling ++ in C# is not assigned to a variable or used as part of a complex expression, then the compiler would reduce the pre and post versions of ++ down to code that performs equivalently.
In C# there is no difference when used in a for loop.
for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
outputs the same thing as
for (int i = 0; i < 10; ++i) { Console.WriteLine(i); }
As others have pointed out, when used in general i++ and ++i have a subtle yet significant difference:
int i = 0;
Console.WriteLine(i++); // Prints 0
int j = 0;
Console.WriteLine(++j); // Prints 1
i++ reads the value of i then increments it.
++i increments the value of i then reads it.
The question is:
Is there a difference in ++i and i++ in a for loop?
The answer is: No.
Why does each and every other answer have to go into detailed explanations about pre and post incrementing when this is not even asked?
This for-loop:
for (int i = 0; // Initialization
i < 5; // Condition
i++) // Increment
{
Output(i);
}
Would translate to this code without using loops:
int i = 0; // Initialization
loopStart:
if (i < 5) // Condition
{
Output(i);
i++ or ++i; // Increment
goto loopStart;
}
Now does it matter if you put i++ or ++i as increment here? No it does not as the return value of the increment operation is insignificant. i will be incremented AFTER the code's execution that is inside the for loop body.
Since you ask about the difference in a loop, i guess you mean
for(int i=0; i<10; i++)
...;
In that case, you have no difference in most languages: The loop behaves the same regardless of whether you write i++ and ++i. In C++, you can write your own versions of the ++ operators, and you can define separate meanings for them, if the i is of a user defined type (your own class, for example).
The reason why it doesn't matter above is because you don't use the value of i++. Another thing is when you do
for(int i=0, a = 0; i<10; a = i++)
...;
Now, there is a difference, because as others point out, i++ means increment, but evaluate to the previous value, but ++i means increment, but evaluate to i (thus it would evaluate to the new value). In the above case, a is assigned the previous value of i, while i is incremented.
One (++i) is preincrement, one (i++) is postincrement. The difference is in what value is immediately returned from the expression.
// Psuedocode
int i = 0;
print i++; // Prints 0
print i; // Prints 1
int j = 0;
print ++j; // Prints 1
print j; // Prints 1
Edit: Woops, entirely ignored the loop side of things. There's no actual difference in for loops when it's the 'step' portion (for(...; ...; )), but it can come into play in other cases.
As this code shows (see the dissambled MSIL in the comments), the C# 3 compiler makes no distinction between i++ and ++i in a for loop. If the value of i++ or ++i were being taken, there would definitely be a difference (this was compiled in Visutal Studio 2008 / Release Build):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PreOrPostIncrement
{
class Program
{
static int SomethingToIncrement;
static void Main(string[] args)
{
PreIncrement(1000);
PostIncrement(1000);
Console.WriteLine("SomethingToIncrement={0}", SomethingToIncrement);
}
static void PreIncrement(int count)
{
/*
.method private hidebysig static void PreIncrement(int32 count) cil managed
{
// Code size 25 (0x19)
.maxstack 2
.locals init ([0] int32 i)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: br.s IL_0014
IL_0004: ldsfld int32 PreOrPostIncrement.Program::SomethingToIncrement
IL_0009: ldc.i4.1
IL_000a: add
IL_000b: stsfld int32 PreOrPostIncrement.Program::SomethingToIncrement
IL_0010: ldloc.0
IL_0011: ldc.i4.1
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldarg.0
IL_0016: blt.s IL_0004
IL_0018: ret
} // end of method Program::PreIncrement
*/
for (int i = 0; i < count; ++i)
{
++SomethingToIncrement;
}
}
static void PostIncrement(int count)
{
/*
.method private hidebysig static void PostIncrement(int32 count) cil managed
{
// Code size 25 (0x19)
.maxstack 2
.locals init ([0] int32 i)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: br.s IL_0014
IL_0004: ldsfld int32 PreOrPostIncrement.Program::SomethingToIncrement
IL_0009: ldc.i4.1
IL_000a: add
IL_000b: stsfld int32 PreOrPostIncrement.Program::SomethingToIncrement
IL_0010: ldloc.0
IL_0011: ldc.i4.1
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldarg.0
IL_0016: blt.s IL_0004
IL_0018: ret
} // end of method Program::PostIncrement
*/
for (int i = 0; i < count; i++)
{
SomethingToIncrement++;
}
}
}
}
Here is a Java-Sample and the Byte-Code, post- and preIncrement show no difference in Bytecode:
public class PreOrPostIncrement {
static int somethingToIncrement = 0;
public static void main(String[] args) {
final int rounds = 1000;
postIncrement(rounds);
preIncrement(rounds);
}
private static void postIncrement(final int rounds) {
for (int i = 0; i < rounds; i++) {
somethingToIncrement++;
}
}
private static void preIncrement(final int rounds) {
for (int i = 0; i < rounds; ++i) {
++somethingToIncrement;
}
}
}
And now for the byte-code (javap -private -c PreOrPostIncrement):
public class PreOrPostIncrement extends java.lang.Object{
static int somethingToIncrement;
static {};
Code:
0: iconst_0
1: putstatic #10; //Field somethingToIncrement:I
4: return
public PreOrPostIncrement();
Code:
0: aload_0
1: invokespecial #15; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: sipush 1000
3: istore_1
4: sipush 1000
7: invokestatic #21; //Method postIncrement:(I)V
10: sipush 1000
13: invokestatic #25; //Method preIncrement:(I)V
16: return
private static void postIncrement(int);
Code:
0: iconst_0
1: istore_1
2: goto 16
5: getstatic #10; //Field somethingToIncrement:I
8: iconst_1
9: iadd
10: putstatic #10; //Field somethingToIncrement:I
13: iinc 1, 1
16: iload_1
17: iload_0
18: if_icmplt 5
21: return
private static void preIncrement(int);
Code:
0: iconst_0
1: istore_1
2: goto 16
5: getstatic #10; //Field somethingToIncrement:I
8: iconst_1
9: iadd
10: putstatic #10; //Field somethingToIncrement:I
13: iinc 1, 1
16: iload_1
17: iload_0
18: if_icmplt 5
21: return
}
There is no difference if you are not using the value after increment in the loop.
for (int i = 0; i < 4; ++i){
cout<<i;
}
for (int i = 0; i < 4; i++){
cout<<i;
}
Both the loops will print 0123.
But the difference comes when you uses the value after increment/decrement in your loop as below:
Pre Increment Loop:
for (int i = 0,k=0; i < 4; k=++i){
cout<<i<<" ";
cout<<k<<" ";
}
Output:
0 0
1 1
2 2
3 3
Post Increment Loop:
for (int i = 0, k=0; i < 4; k=i++){
cout<<i<<" ";
cout<<k<<" ";
}
Output:
0 0
1 0
2 1
3 2
I hope the difference is clear by comparing the output. Point to note here is the increment/decrement is always performed at the end of the for loop and hence the results can be explained.
Yes, there is. The difference is in the return value. The return value of "++i" will be the value after incrementing i. The return of "i++" will be the value before incrementing. This means that code that looks like the following:
int a = 0;
int b = ++a; // a is incremented and the result after incrementing is saved to b.
int c = a++; // a is incremented again and the result before incremening is saved to c.
Therefore, a would be 2, and b and c would each be 1.
I could rewrite the code like this:
int a = 0;
// ++a;
a = a + 1; // incrementing first.
b = a; // setting second.
// a++;
c = a; // setting first.
a = a + 1; // incrementing second.
There is no actual difference in both cases 'i' will be incremented by 1.
But there is a difference when you use it in an expression, for example:
int i = 1;
int a = ++i;
// i is incremented by one and then assigned to a.
// Both i and a are now 2.
int b = i++;
// i is assigned to b and then incremented by one.
// b is now 2, and i is now 3
There is more to ++i and i++ than loops and performance differences. ++i returns a l-value and i++ returns an r-value. Based on this, there are many things you can do to ( ++i ) but not to ( i++ ).
1- It is illegal to take the address of post increment result. Compiler won't even allow you.
2- Only constant references to post increment can exist, i.e., of the form const T&.
3- You cannot apply another post increment or decrement to the result of i++, i.e., there is no such thing as I++++. This would be parsed as ( i ++ ) ++ which is illegal.
4- When overloading pre-/post-increment and decrement operators, programmers are encouraged to define post- increment/decrement operators like:
T& operator ++ ( )
{
// logical increment
return *this;
}
const T operator ++ ( int )
{
T temp( *this );
++*this;
return temp;
}
It boggles my mind why so may people write the increment expression in for-loop as i++.
In a for-loop, when the 3rd component is a simple increment statement, as in
for (i=0; i<x; i++)
or
for (i=0; i<x; ++i)
there is no difference in the resulting executions.
As #Jon B says, there is no difference in a for loop.
But in a while or do...while loop, you could find some differences if you are making a comparison with the ++i or i++
while(i++ < 10) { ... } //compare then increment
while(++i < 10) { ... } //increment then compare
In javascript due to the following i++ may be better to use:
var i=1;
alert(i++); // before, 1. current, 1. after, 2.
alert(i); // before, 2. current, 2. after, 2.
alert(++i); // before, 2. current, 3 after, 3.
While arrays (I think all) and some other functions and calls use 0 as a starting point you would have to set i to -1 to make the loop work with the array when using ++i.
When using i++ the following value will use the increased value. You could say i++ is the way humans count, cause you can start with a 0.
To understand what a FOR loop does
The image above shows that FOR can be converted to WHILE, as they eventually have totally the same assembly code (at least in gcc). So we can break down FOR into a couple of pieces, to undertand what it does.
for (i = 0; i < 5; ++i) {
DoSomethingA();
DoSomethingB();
}
is equal to the WHILE version
i = 0; //first argument (a statement) of for
while (i < 5 /*second argument (a condition) of for*/) {
DoSomethingA();
DoSomethingB();
++i; //third argument (another statement) of for
}
It means that you can use FOR as a simple version of WHILE:
The first argument of FOR (int i) is executed, outside, before the loop.
The third argument of FOR (i++ or ++i) is executed, inside, in the last line of the loop.
TL:DR: no matter whether i++ or ++i, we know that when they are standalone, they make no difference but +1 on themselves.
In school, they usually teach the i++ way, but there are also lots of people prefer the ++i way due to several reasons.
NOTE: In the past, i++ has very little impact on the performance, as it does not only plus one by itself, but also keeps the original value in the register. But for now, it makes no difference as the compiler makes the plus one part the same.
There can be a difference for loops. This is the practical application of post/pre-increment.
int i = 0;
while(i++ <= 10) {
Console.Write(i);
}
Console.Write(System.Environment.NewLine);
i = 0;
while(++i <= 10) {
Console.Write(i);
}
Console.ReadLine();
While the first one counts to 11 and loops 11 times, the second does not.
Mostly this is rather used in a simple while(x-- > 0 ) ; - - Loop to iterate for example all elements of an array (exempting foreach-constructs here).
Yes, there is a difference between ++i and i++ in a for loop, though in unusual use cases; when a loop variable with increment/decrement operator is used in the for block or within the loop test expression, or with one of the loop variables. No it is not simply a syntax thing.
As i in a code means evaluate the expression i and the operator does not mean an evaluation but just an operation;
++i means increment value of i by 1 and later evaluate i,
i++ means evaluate i and later increment value of i by 1.
So, what are obtained from each two expressions differ because what is evaluated differs in each. All same for --i and i--
For example;
let i = 0
i++ // evaluates to value of i, means evaluates to 0, later increments i by 1, i is now 1
0
i
1
++i // increments i by 1, i is now 2, later evaluates to value of i, means evaluates to 2
2
i
2
In unusual use cases, however next example sounds useful or not does not matter, it shows a difference
for(i=0, j=i; i<10; j=++i){
console.log(j, i)
}
for(i=0, j=i; i<10; j=i++){
console.log(j, i)
}
In certain situations ++i and i+1 might give different results, same goes for --i, i - 1 etc.
This is not because there is a flaw in how increment and decrement operators work but because of a little fact sometimes overlooked by new programmers.
As a rule of thumb do not use inc/dec inside array's square brackets. For example, I won't do something like arr[++i] in place of arr[i + 1]. Though both would get us the same value of i, there is something that we overlooked here.
If a loop condition is based on i's value for execution then replacing arr[i + 1] with arr[++i] would result in error. Why?
Let say i = 5, then arr[i + 1] would mean arr[6] and arr[++i] although would mean arr[6] but would also change the value of i to 6 and this might not be something that we want to do. We might not want to change the value of i but due to a simple ++/-- operator, we changed the value.
So be careful when using ++/-- operators.
I hope, I was able to make my point easy for understanding.
For i's of user-defined types, these operators could (but should not) have meaningfully different sematics in the context of a loop index, and this could (but should not) affect the behavior of the loop described.
Also, in c++ it is generally safest to use the pre-increment form (++i) because it is more easily optimized. (Scott Langham beat me to this tidbit. Curse you, Scott)
I dont know for the other languages but in Java ++i is a prefix increment which means: increase i by 1 and then use the new value of i in the expression in which i resides, and i++ is a postfix increment which means the following: use the current value of i in the expression and then increase it by 1.
Example:
public static void main(String [] args){
int a = 3;
int b = 5;
System.out.println(++a);
System.out.println(b++);
System.out.println(b);
}
and the output is:
4
5
6
i++ ; ++i ; both are similar as they are not used in an expression.
class A {
public static void main (String []args) {
int j = 0 ;
int k = 0 ;
++j;
k++;
System.out.println(k+" "+j);
}}
prints out : 1 1

Recursion java - differently for loop does not understand how to work

I understand the principle of recursion and code but do not understand the loop for,Why variables are in the same line, we can explain how the loop works?
this line:
for (int i = digit, j = 1; i >= 1; i--, j++)
The code:
public static boolean hasSubSeries(int[] arr, int digit) {
return hasSubSeriesHelper(arr, arr.length, digit);
}
public static boolean hasSubSeriesHelper(int[] arr, int size, int digit) {
if (size == 0)
return false;
for (int i = digit, j = 1; i >= 1; i--, j++) {
if (arr[size - j] != i)
return hasSubSeriesHelper(arr, size - 1, digit);
}
return true;
}
thank's
The structure of the for loop is as follows:
for( starting conditions; verification at each loop; action at end of loop)
In your specific case:
for (int i = digit, j = 1; i >= 1; i--, j++)
Starting conditions:
A variable i which is equal to the value contained in the variable digits that is given at the start of the function hasSubSeriesHelper(int[] arr, int size, int digit).
A variable j which starts at 1.
Verification at each loop:
Once each loop is completed we will check this, if it is True, we keep on looping, if not we exit the loop.
We check to see if i declared at the start is greater than or equal to 1, if it is we keep on looping, if not we stop.
Action at end of loop:
We do two actions i-- which decreases the value of i by 1 and j++ which increases the value of j by 1.
To summarise you could translate it to a while loop if you prefer:
int i = digit;
int j = 1;
while ( i >= 1 ) {
// the code inside the for loop goes here
i--;
j++;
}
Note that the actions at the end happen inside the loop whilst the starting condditions go before the loop.
That should also clarify why you can have various declarations in the same line as long as they are of the same type.
You have three parts in a for loop
N°1 : Initialization of variable(s)
N°2 : Boolean expression evaluated to continue/stop looping
N°3 : Changes operated on variables
1
You may have multiple initialization in the first part, as long as the type stay the same, the following is entirely possible :
We declare and instantiate three variables within the first part of our for declaration.
for(int i = 2, j = 2*i, k = 4*j ; i < 3 ; i++) {
System.out.println(i + " " + j + " " + k); // 2 4 16
}

Converting an Iterative Method to a Recursive one (Java)

For my discrete structures class at uni, I need to write a method that solves the formulas below:
 
s[0] = 1
s[n-1] = s[n-2] + n for all n >= 2
Unfortunately, I've not implemented many recursive methods before, so I don't really know what I'm doing. Things just aren't "clicking" for me like they normally do.
I'd appreciate help in any way possible, but I'd rather fully understand this, rather than just copypaste someone else's work.
A basic example for what this method should accomplish if n = 8...
1 + 2 = 3,
3 + 3 = 6,
6 + 4 = 10,
10 + 5 = 15,
15 + 6 = 21,
21 + 7 = 28,
28 + 8 = 36, our answer.
I've written a method to solve this NON-recursively (shown below), so I do understand the math behind it.
public static int sequenceNonRecursive(int n){
int[] s = new int[n];
s[0] = 1;
if(n >= 2){
for(int i = 1; i < n; i++){
s[i] = s[i-1] + i + 1;
}
}
return s[n-1];
}
EDIT: I solved it. Thanks for your help, everyone! Look below for my answer.
The recurrence is defined a little oddly. I would rewrite it:
S0 = 1
Si = Si-1 + i + 1 — ∀ i > 0
The routine can be simplified to not use an array:
public static int sequenceNonRecursive (int n) {
int S_0 = 1; // 0th term is 1
int S_i = S_0; // S_i starts at S_0
for(int i = 1; i <= n; i++) {
int S_i_minus_1 = S_i; // use previous result to calculate next
S_i = S_i_minus_1 + i + 1; // next is previous added with index plus 1
}
return S_i;
}
Any loop can be converted into an equivalent recursive routine. The trick is that local variables turn into function parameters for the recursive routine and the loop control turns into an if. If the condition is false, the function returns with the result. Otherwise, the function does the computation as if it is the loop body, and then uses recursion to iterate.
As an illustration, given the function:
public static int someFunction (int n) {
int result = DEFAULT_RESULT;
for (int i = 0; i < n; ++i) {
result = UPDATE_RESULT(i, n, result);
}
return result;
}
Then, the body of this function can be changed to call a recursive function instead:
public static int someFunction (int n) {
return someFunctionWithRecursion(n, 0, DEFAULT_RESULT);
}
Notice how the initial values of local variables have been converted into parameters to the recursive routine. So, the recursive routine itself may look like:
public static int someFunctionWithRecursion (int n, int i, int result) {
if (! (i < n)) {
return result;
}
result = UPDATE_RESULT(i, n, result);
return someFunctionWithRecursion(n, i+1, result);
}
Notice that in the recursive call, the result has been updated, and the control variable i has been incremented, just as an iteration would have done in the original for() loop version of the code.
As an aside: The recurrence you are working on actually has a closed form:
Sn = (½)(n+1)(n+2)
It's actually easier. Imagine that your method works for all n's and that unless n is zero (the base case) you use
sequenceRecursive(n-1)
to get the value of the previous number and just expect it to work. (and it will)
Under the hood it will recurse down to the base case and build up the value as the calls return.
Recursion is like breaking down the original problem into sub problems and trying to solve them. To start with you need to figure out the base case(which in your case is n=0). Now you can move ahead and see how you can handle cases where n > 0 by breaking it down to the base case. Creating the sequence for n then n-1 then n-2 and so on till you reach the base case is the key to solve this problem recursively.
Structure your code something like this (just giving hints, leaving you to figure out the rest of the problem):
public static int sequenceRecursive(int n){
if( n == 0 )
//return something....
else
//return something else, which recursively relies on previous values of sequenceRecursive()
}
Let's first add 1 to all n's in your second equation: (if we increase them, we need to decrease the range, seeing that it's correct should be trivial)
s[0] = 1
s[n] = s[n-1] + (n+1) for all n >= 1
Why do we want to do this?
In short, the function definition is sequence(int n), not sequence(int n-1).
Here s[i] just corresponds to calling your function with input parameter i.
And the basic idea for the code:
public static int sequence(int n){
if (/* base case */)
// return value for base case
else
// return other case, includes calling sequence(x) for some x
}
Hope that gives you enough to work from.
I got it, guys. Thank ALL of you for your help! I can't believe how stupidly simple this was. As soon as I figured it out, I gave myself a forceful facepalm. I'm pretty sure I understand recursion now.
public static int sequenceRecursive(int n){
if( n == 0 )
return 0;
else
return n + sequenceRecursive(n-1);
}

Iterating an array from both ends using two indices

This is more of an self defined programming exercise than a real problem. I have an array of java.lang.Comparable items. I need to maintain two pointers (an index into the array i.e., int values) i,j . i starts at the beginning of array and moves right until it encounters an element which is less than or equal to the previous element. When it does it stops moving right and ends up pointing to the element which is out of order(element which is not greater than the previous). Similarly j starts at the end of the array and moves left until it finds an element which is not less than the previous.
Also, I need to make sure that the indices don't run out of the array i.e., i cannot go below 0 and j cannot go above arraylength-1
lets say we have an array of 5 elements.
i = 0;
j = 4;(which is the arraylength-1 )
if C,D,E,F,G is the array ,the final values of i and j will be
i = 4 and j = 0
if array is J,D,E,F,G ,the final values of i, j will be
i = 0 , j = 0
if array is B,C,A,D,G , final values of i,j will be
i = 2 , j = 1
I tried to code the logic for moving i to the right, using a while loop as below. I was able to get it working for the i pointer in two cases.
public class PointerMovement{
public static void ptrsPointToOutOfOrderElements(Comparable[] a){
int lo = 0;
int hi = a.length-1;
int i = lo;
int t=i+1;
int j = hi;
//only for moving i to the right .
while(less(a[i],a[t])){
if(t == hi){
i=t;
break;
}
i++;
t++;
}
i=t;
for(Comparable x:a){
System.out.print(x+",");
}
System.out.println();
System.out.println("bad element or end of array at i="+i+"==>"+a[i]);
}
private static boolean less(Comparable x,Comparable y){
return x.compareTo(y) < 0;
}
public static void main(String[] args) {
String[] a = new String[]{"C","D","E","F","G"};//works
//String[] a = new String[]{"B","C","A","D","G"};//works
//String[] a = new String[]{"J","D","E","F","G"};//fails!
ptrsPointToOutOfOrderElements(a);
}
}
My line of reasoning given below
I maintain i=0; and another variable t=i+1
when the while loop fails, less(a[i],a[t]) is false .We need to return a pointer to a[t] which is out of order. so i=t and return i.
if we reach right end of array, the test if(t == hi) passes and we assign i=t and now i points to end of array.
However, the code fails when the out of order element is in the 0th position in the array.
J,D,E,F,G
Instead of i (=0) we get i=1 because i=t is assgined.i ends up pointing to D instead of J.
Can someone point me in the right direction?
update:
this seems to work
public static void ptrsPointToOutOfOrderElements(Comparable[] a){
int lo = 0;
int hi = a.length-1;
int i = lo;
while(less(a[i],a[i+1])){
if(i+1 == hi){
break;
}
i++;
}
i++;
int j = hi;
while(less(a[j-1],a[j])){
if(j-1 == lo){
break;
}
j--;
}
j--;
for(Comparable x:a){
System.out.print(x+",");
}
System.out.println();
if(i>=j){
System.out.println("pointers crossed");
}
System.out.println("bad element or end of array at i="+i+"==>"+a[i]);
System.out.println("bad element or end of array at j="+j+"==>"+a[j]);
}
I do not think you have a problem:
String[] a = new String[]{"C","D","E","F","G"};//works, index should be 4 (but should it be so? It would indicate that G is out of order while it is not. I think you should return 5, indicating that none is out of order.
String[] a = new String[]{"B","C","A","D","G"};//works, index should be 2 as A is out of order
String[] a = new String[]{"J","D","E","F","G"};//works since the first out of order element is indeed D, with index 1
I have tried using simple for loop.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0, j = arr.length - 1; i <= j; i++, j--) {
console.log(arr[i] + ' , ' + arr[j]);
}
Output :
1 , 10
2 , 9
3 , 8
4 , 7
5 , 6

Categories