Results 1 to 4 of 4

Thread: [RESOLVED] [1.0/1.1] Loop problem?

  1. #1

    Thread Starter
    Hyperactive Member francisstokes's Avatar
    Join Date
    May 2005
    Location
    Kent, England
    Posts
    272

    Resolved [RESOLVED] [1.0/1.1] Loop problem?

    I only started C# today (i already know VBNET), and can't work out whats wrong with this loop:

    Code:
    		static void Main(string[] args)
    		{
    		 int[] i = new int[3];
    
    
    		 i[0] = 2;
    		 i[1] = 4;
    		 i[2] = 61;
    
    		 int sum;
    
    		 for (int x = 0; x < 2; x++)
    		 {
    
    			sum += i[x];
    		 }
    
    		 Console.WriteLine(sum);
    		 Console.ReadLine();
    		 }
    Sorry for such a simple question.

  2. #2

    Thread Starter
    Hyperactive Member francisstokes's Avatar
    Join Date
    May 2005
    Location
    Kent, England
    Posts
    272

    Re: [1.0/1.1] Loop problem?

    Wait....i know. x doesn't have a value yet, so it can't be used.

  3. #3
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    105,461

    Re: [RESOLVED] [1.0/1.1] Loop problem?

    It's not 'x' that's the issue. It's 'sum'. You need to initialise all variables in C#.
    Code:
    int sum = 0;
    This is one of the ways in which C# is stricter than VB.NET. If you want 'sum' to be zero then you have to specify it. That way you actually have to think about what value you want a variable to have and you won't simply forget to set a value and have a variable default to zero when that isn't what you want.

  4. #4

    Thread Starter
    Hyperactive Member francisstokes's Avatar
    Join Date
    May 2005
    Location
    Kent, England
    Posts
    272

    Re: [RESOLVED] [1.0/1.1] Loop problem?

    Thats what i meant .

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width