Click here to Skip to main content
15,890,399 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
int x = 1;
while(x < 10)
{
Console.Write(x);
x++;
}

What I have tried:

int x = 1;
for(int x = 1;i<=10;i++)
{
Console.Write(x);
x++;
}
Posted
Updated 22-Nov-18 0:22am

The code posted under what I have tried should not work because you declare x twice anduse but not declare i. How about this code:

for(int x = 1;x<10;x++)
{
  Console.Write(x);
}
 
Share this answer
 
You are declareign x twice, once here:
int x = 1;
And once here:
for(int x = 1;i<=10;i++)
That's not a good idea as the compiler will tell you:
A local variable named 'x' cannot be declared in this scope because it would give a different meaning to 'x', which is already used in a 'parent or current' scope to denote something else
And you don't declare i at all!
Then there is the ending condition, which isn't the same for the two loops - your new one would perform an extra iteration because it continues to run even when i is equal to 10.
To change this
int x = 1;
while (x < 10)
    {
    Console.Write(x);
    x++;
    }
to a for loop, just do this:
for (int x = 1; x < 10; x++)
    {
    Console.Write(x);
    }
 
Share this answer
 
In the "for" you are setting x to 1, then checking if i is <= 10, then incrementing i.

int x = 1;
for(int x = 1;i<=10;i++)
{
Console.Write(x);
x++;
}


Change to

int x = 1;
for(int i = 1;i<=10;i++)
{
Console.Write(x);
x++;
}


Or you could get rid of x altogether

for(int i = 1;i<=10;i++)
{
Console.Write(i);
}
 
Share this answer
 
for(int i = 1; i < 10; i++)
{
   Console.Write(i);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900