-3

Im trying to learn C# from scratch and I have issue with one simple task. I cant understand why this is Not working,can you please explain me :

     namespace ConsoleApplication1
{
    class intro
    {
        static void Main(string[] args)
        {
            int i;
            int j;
            for (i = 1; j=-1; i <= 100 && j >= -100; i += 2, j -=2)
            {
                Console.WriteLine(i+j);
            }
        }
    }
}     

Edit: I missed why is NOT working, sorry for that. Semicolon instead of colon was the problem... Stupid question but thank you for patience.

tslid
  • 315
  • 1
  • 4
  • 16
  • 2
    Simple. You're looping until `i <= 100 && j >= -100`. Each loop, `i` has 2 added to it.. `j` has 2 removed. You should review basic `for..` loops if you don't understand this. – Simon Whitehead Feb 06 '14 at 12:45
  • 3
    The code actually doesn't compile. Should be "for(i=1, j=-1" ...comma instead of semicolon. – Grzegorz Sławecki Feb 06 '14 at 12:48
  • 1
    This code does not compile (`for(;;;)` ). – H H Feb 06 '14 at 12:48
  • 1
    This site is better for explaining why code is _not_ working. What is your actual question here? – H H Feb 06 '14 at 12:49
  • 1
    Why this code _is_ working, or why this code _isn't_ working? – Svish Feb 06 '14 at 12:50
  • Leaving out a __not__ is a big typo in a question... Also, always provide the full error messages. – H H Feb 06 '14 at 12:56
  • Your `for` is doing -1+1 = 0 then +3-3=0 then +5-5=0 then ... then +n-n=0 – Alex Feb 06 '14 at 13:10
  • Yes, I just realized this... Thinking is really good thing if you actually can do it... It was stupid question but thank you for patience and answers ! – tslid Feb 06 '14 at 13:13

3 Answers3

0

What do you mean by:

I cant understand why this is working

It is working because it is a valid code.Except this comma should be semicolon:

i = 1; <-- wrong
i = 1, <-- correct

You are constructing a for loop.You define two variable,i and j then,you starting i from 1 and j form -1. Then you specify the loop condition. i <= 100 && j >= -100.With this condition you are saying the loop should execute as long as i <= 100 AND j >= -100 And last statement you specifying the expression which will be executed in every step.That's it.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

for loop needs to have a structure of

for (initializer; condition; iterator)
    body

Please refer to MSDN, these are the most basics of every programming language.

Tarec
  • 3,268
  • 4
  • 30
  • 47
0

There is a very common mistake, you placed `;' in the place ',';

for (i = 1, j=-1; i <= 100....

I don't know what you want to do with the code but it produce only '0' but the code is working as it should.

Iqbal
  • 1,266
  • 1
  • 17
  • 21