Reputation: 93
I am currently trying to get a number that increases by one each time its run, I am using a while loop, so in theory every time the loop is run in the code below, the int i should return 1,2,3,4 etc. Although instead it returns 1,1,1,1,1. Just can't get my head around this one.
public static void getresponse(ref int i)
{
i++;
System.Console.WriteLine(i);
}
Upvotes: 0
Views: 86
Reputation: 46047
Put your counter outside of the loop.
static void Main(string[] args)
{
int i = 0;
while (true)
{
getresponse(ref i);
}
}
public static void getresponse(ref int i)
{
i++;
System.Console.WriteLine(i);
}
Upvotes: 0
Reputation: 44605
do you notice you reset i to 0 at every iteration?
just declare i outside the while block and it will work.
Upvotes: 0
Reputation: 1482
Declare i outside your while loop. It is being set to 0 each time.
static void Main(string[] args)
{
int i = 0;
while (true)
{
getresponse(ref i);
}
}
public static void getresponse(ref int i)
{
i++;
System.Console.WriteLine(i);
}
Upvotes: 1
Reputation: 69973
You're redeclaring i and setting it to 0 each time the loop runs.
Move int i = 0
outside of the while loop.
int i = 0;
while (true)
{
getresponse(ref i);
}
Upvotes: 3