7

So i came across this little incrementing method

since highschool and univeristy I am used to this kind of method

char[] NewArray = new char[5] //I forgot how to declare an array

string temp;

console.writeline("Enter 5 letters)

for (i=0; i<5;i++)
{
   NewArray[i] = console.readline()
}

now based on this code

I declare an array of char with 5 "spaces", then I ouput a message to the console asking the user to enter 5 values

so i = 0, readline e.g. c

thus BEFORE the console.readline statment, i=0, then it continues through the for loop, then returns to the beginning of the loop, incrementing i = 1 BEFORE excecuting the console.readline again

how does this differ to "++i", what will the "++i" do in the for loop?

4 Answers4

17

count++ is post increment where ++count is pre increment. suppose you write count++ means value increase after execute this statement. but in case ++count value will increase while executing this line.

Amit
  • 15,217
  • 8
  • 46
  • 68
15

++x is pre-increment and x++ is post-increment that is in the first x is incremented before being used and in the second x is incremented after being used.

if you write x++ or ++x they are same;. if x=5; x++=6 and ++x=6

but if you execute x++ + x++(5 +6) it will give you different result will be 11

but if you execute x++ + ++x(5 +7) it will give you different result will be 12

but if you execute ++x + ++x(6 +7) it will give you different result will be 13

Ashish
  • 1,943
  • 2
  • 14
  • 17
1

It doesn't differ in the for loop.Because if your condition is true once for loop will execute ,then it perform your step. So this:

for(int=0; i<4; i++)

Equals to:

for(int=0; i<4; ++i)

You can think it's like the same as:

i++;

and;

 ++i;
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

As additional information. This is how you can imagine the two different operators are implemented:

Prefix:

int operator++ () { 
    //let "this" be the int where you call the operator on
    this = this + 1;
    return this;
}

Postfix:

int operator++ (int) { //the dummy int here denotes postfix by convention
    //let "this" be the int where you call the operator on
    int tmp = this; //store a copy value of the integer (overhead with regards to prefix version)
    this = this + 1; //increment
    return tmp; //return the "pre-incremented" value
}
ben
  • 5,671
  • 4
  • 27
  • 55