0

I'm doing some excercises for school and ran into a problem. When I try to count the characters in a array it just gives back the array itself. Can anyone tell me what I'm missing? The code is in C#.

public static int CountFor(int n)
{
        int count = 0;

        int[] a = new int[] {n};
        for (int i = 0; i < a.Length; i++)
        {
            count += i;
        }
        return count;
} 

and in the main to show the results:

Console.WriteLine(CountFor(1024));
Console.ReadKey();
Jcl
  • 27,696
  • 5
  • 61
  • 92
  • 4
    Visual Studio has a built-in debugger which works faster, more accurate and more satisfying than posting on Stack Overflow. Place a breakpoint (F9) and step through your code (F10) and inspect your variables to see what your code is doing. The code `a = new int[] {n}` is not doing what you expect it to, which is the root cause of your issue. By inspecting it, you could have falsified your problem statement of _"it just gives back the array itself"_, which it doesn't. – CodeCaster Jan 12 '15 at 11:57

2 Answers2

5

Change

new int[] {n}

to

new int[n]

With new int[] {n}, you have an array with 1 element as n.

Read: Arrays Tutorial

You can easily use Enumerable.Range and Enumerable.Sum methods to simplify your method like;

public static int CountFor(int n)
{
   return Enumerable.Range(1, n).Sum();
} 
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • But the console gives back 523776 while it's supposed to give back 4 as 1024 contains 4 integers. Can you explain this? – Johan Wijts Jan 12 '15 at 12:00
  • 2
    @Johan your code adds `1+2+3+...+1024`. You can find this out for yourself by using the debugger. If you want to count the number of digits in an integer, that's a different question, which is answered in [How can I get a count of the total number of digits in a number?](http://stackoverflow.com/questions/4483886/how-can-i-get-a-count-of-the-total-number-of-digits-in-a-number). – CodeCaster Jan 12 '15 at 12:00
  • Thanks again, I can figure the rest out myself like this. – Johan Wijts Jan 12 '15 at 12:04
1

You need to use new int[n], otherwise you are generating a new array with length 1 with the passed integer as the content of the array

Jcl
  • 27,696
  • 5
  • 61
  • 92