Reputation: 51
I am new in C# programming language and I confused with a question. I have a for loop that increase two times by one in one cycle, but in each cycle it increase once.
What is the reason it does omit the i++
?
string inValue;
for (int i = 0; i < 10; i++)
{
Console.Write("Enter Score{0}: ", i + 1);
inValue = Console.ReadLine();
}
Upvotes: 1
Views: 108
Reputation: 37299
The ++
increment operator increases value only by one
for (int i = 0; i < 10; i++)
To increase twice:
for (int i = 0; i < 10; i+=2)
{
Console.Write("Enter Score{0}: ", i);
}
Read more: Increment (++) and Decrement (--) Operators
| If | Equivalent Action | Return value | | variable++ | variable += 1 | value of variable before | | | | incrementing |
The following row:
Console.Write("Enter Score{0}: ", i + 1);
increases the value of i
by plus 1
but that is not stored into i
. It is like writing:
int b = i+1; // i is not affected. New value never stored back into i
Console.Write("Enter Score{0}: ", b);
Any of the following ways will increase value by 2:
//Option 1
for (int i = 0; i < 10; i +=2)
//Option2
Console.Write("Enter Score{0}: ", i++);
//Option3
i = i+1;
Console.Write("Enter Score{0}: ", i);
Upvotes: 3
Reputation: 21
i++
means you just increase the i
by 1 or simply you can just write the code like this i = i + 1
. So if you want loop with increase i + 2
, you can write down code like this:
for(int i = 0; i < 10; i += 2)
{
Console.Write("Enter Score{0}: ", i);
inValue = Console.ReadLine();
}
The loop will increase i
by 2.
Upvotes: 2
Reputation: 1193
(i++) increases i by 1, it's like writing : i = i + 1. (i + 1) does not increases i.
Upvotes: 0