Mathew
Mathew

Reputation: 93

Question with incrementing values in C#

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

Answers (4)

James Johnson
James Johnson

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

Davide Piras
Davide Piras

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

Max Barfuss
Max Barfuss

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

Brandon
Brandon

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

Related Questions