neiloth
neiloth

Reputation: 167

for loop condition issue

int a, b, c;
a = 1;
b = 2;
c = a + 2*b;
for (a=1; c<15; a++)
{               
    Console.WriteLine(c.ToString());
}

Console.ReadLine();

I have a simple question. Do I have to define my condition depending on my initializing variable?
In the example above, I want the loop to stop when a variable "a" becomes 10, so variable "c" will be less than 15.
But the output is infinite lines of "5". I expect my output to be 14.

what am I doing wrong?

Upvotes: 1

Views: 89

Answers (4)

Mong Zhu
Mong Zhu

Reputation: 23732

do i have to define my condition depending on my initializing variable?

no you don't you can define any condition you want.

what am I doing wrong?

You never so something to make this condition false it will run forever like in your case.

You change c only once before the loop starts:

c = a + 2*b;
for (a=1; c<15; a++)
{               
    Console.WriteLine(c.ToString());
}

as soon as you enter the loop c is never changed again! Move the changing part into the loop:

for (a=1; c<15; a++)
{               
    c = a + 2*b;
    Console.WriteLine(c.ToString());
}

You could even write the loop using a bool variable

bool condition = true;
for (int a = 0; condition; i++)
{
    c = a + 2*b;
    if (c > 15)
    { 
        condition = false;
    }
}

EDIT

You could even do the computation inside the comparison block of the for-loop and it would work:

for (a = 0; (c = a + 2 * b) < 15; a++)
{
    Console.WriteLine(c.ToString());
}

Disclaimer: I would not recommend it because it is cryptic and horrible to read.

Upvotes: 1

Vikrant
Vikrant

Reputation: 5036

A inside condition:

for (a=1; a<=10; a++)
{
    c = a + 2*b;
    Console.WriteLine(c.ToString());
}

Loop will stop when, c becomes 14.

Upvotes: 0

Sayse
Sayse

Reputation: 43300

If you really wanted you could omit all 3 parts of a for loop so it essentially becomes a while(true) loop

for(;;)

So no, it doesn't need to.

But to make your program work, you'll need to update the value of c inside the loop

    for (a=1; c<15; a++)
    {
        c = a + 2*b;
        Console.WriteLine(c.ToString());
    }

Upvotes: 1

Maksim Simkin
Maksim Simkin

Reputation: 9679

move c change inside of the loop, or you will itereate without end:

for (a=1; c<15; a++)
{
    c = a + 2*b;
    Console.WriteLine(c.ToString());
}

Upvotes: 5

Related Questions