jkuehlin
jkuehlin

Reputation: 137

Is it possible to pass a variable into a for loop?

Is it possible to initialize 'int number' and pass it a value from the user input? I'm wondering if there's a cleaner way to do this by initializing number outside of the for loop.

for (int number = Convert.ToInt16(Console.ReadLine()); number < 10; number++)
       {
           Console.WriteLine(number);
       }

I would like to do something like this, where a variables is initialed outside the loop, then handed directly in. - However this doesn't seem to work.

int n;
for (n; n<10; n++) 
{ 
     Console.Writeline(n)
}

I understand that it can be assigned and passed into the loop, but is it possible to do this without having to?

int n = Convert.ToInt16(Console.ReadLine());
for (int i = n; i<10; i++) 
     Console.Writeline(i);

in other words, can I use int n, without having to change it to i?

Upvotes: 2

Views: 2232

Answers (2)

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26058

It's very close to what you had, just leave off the first part.

int n = 0;
for (; n < 10; n++) 
{ 
     Console.WriteLine(n)
}

Yeah this works, just tried in jsfiddle (https://dotnetfiddle.net/ZkL4BP). Just make sure nis initialized to something prior to the loop just int n gives a variable not initialized error.

As others are pointing out it is definitely an odd pattern, typically you want your for loop counter to only live the duration of the loop, and do whatever manipulation to other variables within the block. But it is accepted by the compiler.

Upvotes: 4

voidengine
voidengine

Reputation: 2579

You can do that by simply omitting the first part of the for statement

int n = Convert.ToInt16(Console.ReadLine());
for (; n<10; n++) 
     Console.Writeline(n);

Parts of the for statement are statements themselves and may contain arbitrary stuff - including an empty statement.

That said, you need to keep in mind that your variable is changed inside the loop. It's not great from the aspect of readability, so I wouldn't recommend it.

Upvotes: 0

Related Questions