user601496
user601496

Reputation: 85

C# print every third number!

Help needed to perform an output in C# console application.

I have a maximum number

int maxNr = 10;
int myValue = 1;

public void myMethod(){
int choice = int.Parse(Console.ReadLine());  // only 1 or 2 accepted.

//Only choice = 1 in displayed here.
if(choice == 1){
   while(myValue <= maxNr){
     Console.WriteLine(myValue);
     myValue = myValue + 3;
   }
}
}

Expected output: 1, 4, 7, 10 Next time the function is called the output should be: 3, 6, 9 2, 5, 8

Upvotes: 2

Views: 5407

Answers (7)

HuBeZa
HuBeZa

Reputation: 4761

Add this before the while loop:

if (myValue >= 10)
    myValue -= 10;

Edit:

1.If I understood you correctly, the expected output is:

1st call 1, 4, 7, 10.
2nd call: 3, 6, 9.
3rd call 2, 5, 8.

2.As some suggested, you should use for loop instead of while loops:

if (myValue >= maxNr)
    myValue -= maxNr;

for (; myValue <= maxNr; myValue += 3)
{
    Console.WriteLine(myValue);
}

Upvotes: 2

Devendra D. Chavan
Devendra D. Chavan

Reputation: 9021

You need to store myValue in a temporary variable and update it before exiting the method. As I understand your requirements the code to achieve the output is as given below,

static int maxNr = 10;
static int myValue = 1;

private static void Test()
{
    int lastValue = myValue;
    int choice = int.Parse(Console.ReadLine());  // only 1 or 2 accepted.

    //Only choice = 1 in displayed here.
    if (choice == 1)
    {
        while (myValue <= maxNr)
        {
            Console.WriteLine(myValue);
            myValue = myValue + 3;
        }
    }

    if (lastValue == 1)
    {
        myValue = lastValue + 3 - 1;
    }
    else
    {
        myValue = lastValue - 1;
    }
}


Method Call


static void Main(string[] args)
{
    Test();
    Test();
    Test();

Console.ReadLine();

}


Output
1
4
7
10

3
6
9

2
5
8

Note that the user needs to enter the value 1 at every function call.

Upvotes: 1

A.R.
A.R.

Reputation: 15705

public void myMethod(){
int choice = int.Parse(Console.ReadLine());  // only 1 or 2 accepted.

int maxNr = 10;
int myValue = choice;

//Only choice = 1 in displayed here.
if(choice == 1){
   while(myValue <= maxNr){
     Console.WriteLine(myValue);
     myValue = myValue + 3;
   }
}
}

Reset your starting value each time.

Upvotes: 1

Gambrinus
Gambrinus

Reputation: 2136

myValue is not defined locally, so you need to set it to 0, when calling the method again, otherwise it would still be 10 and you do not enter the loop.

Upvotes: 1

anon
anon

Reputation:

Why not just use this?

for (int i = n; i <= maxNr; i = i+3) {
    Console.WriteLine(i);
}

Upvotes: 1

elp
elp

Reputation: 8131

for (i=0; i<n; i+=3) don't work for you?

Upvotes: 1

Jimmy
Jimmy

Reputation: 6171

myValue is stuck at 13 after the first call, so the code does not enter the loop the second time

Upvotes: 2

Related Questions