How to add numbers in a loop [closed]
I am new in c#,
I want to add the numbers in my coding .
I dont know how to loop.
I want to add numbers in a loop for each time 开发者_开发技巧i want to add 500 in my Addition
I want to do something like this in loop for every time
int StartTime = int.Parse("90000");
int Add = StartTime + "500";
int StartTime = 90000;
int Add = StartTime;
int increment = 500;
for (int i = 0; i < 10; i++) {
Add = Add + increment;
}
// Add is 90,000 + 500 * 10 = 95,000.
The for
loop syntax is a bit weird if you haven't seen it before. You have a thing to do on initialization, int i = 0
, a thing to test against each time around the loop, to see if you should continue going i < 10
, and a thing to do at the end of each pass around the loop, i++
(which is a shorter way of writing i = i + 1;
).
So here, First there is a loop variable created, i
. Then if i
is less than 10, the computer goes inside the loop (and sets Add = Add + increment
). Then, the computer adds 1 to i
, so i
is now 1. Then checks if i
is still less than 10. If it is, it goes into the loop again... and so on.
When i
eventually reaches 10, the condition i < 10
no longer holds, so the computer exists the loop.
So if we write this:
int StartTime = 90000;
int Add = StartTime;
int increment = 500;
for (int i = 0; i < 10; i++) {
Console.WriteLine(Add + " " + i);
Add = Add + increment;
}
Console.WriteLine(Add);
The output is this:
90000 0
90500 1
91000 2
91500 3
92000 4
92500 5
93000 6
93500 7
94000 8
94500 9
95000
Note that the loop variable i
only exists inside the loop, so if you were to do:
int StartTime = 90000;
int Add = StartTime;
int increment = 500;
for (int i = 0; i < 10; i++) {
Console.WriteLine(Add + " " + i);
Add = Add + increment;
}
Console.WriteLine(Add + " " + i);
The program would not work.
int count = 10; //amount of times you want to loop
int StartTime = 90000;
int Add = 0;
for (int i=0; i < count; i++)
{
Add = Add + 500;
}
Why in the world are you parsing strings to integer?
And why do you make so many lines?
int StartTime = 90000; //use an integer, not a string!
int Add = StartTime;
for (int i=0; i < 10; i++) //looping 10 times, from 0 to 10, incrementing i for 1 every time
{
Add += 500; //so you add 500 to Add every loop
}
Console.WriteLine(Add);
Result:
95000
精彩评论