1

I have written a small code, it works right on VS, but the problem arises when it is to be submitted online, so it needs input formatted in same line.

Format needs an N integer taking no of Numbers in List Next Line needs N no of elements in same line separated by space the next one should output the sum. I have done that, but there is an problem, it does not let me input no greater than 87, it gives me NumberFormatException at line 17. To get array content in one line I took it from here: Reading array elements from the same line (C#) Newbie in C#, was doing it in Java.

class MyClass {
static void Main(string[] args) {

    int i,k;
    int sum=0;
    int n;

    n = Convert.ToInt32(Console.ReadLine());
    //Took this code from above link
    string readLine = Console.ReadLine();
    string[] stringArray = readLine.Split(' ');
    int[] intArray = new int[100];
    for (i = 0; i < n; i++)
    {
        intArray[i] = int.Parse(stringArray[i]); // line 17
    }

    for (k = 0; k <= n; k++)
    {
        sum = sum + k;
    }
    Console.WriteLine(sum);


}
Community
  • 1
  • 1
  • Add try-catch, see the exception. Do you probably want to int.Parse(...) something others than number, or there are space or tabs before or after it. –  Jul 02 '16 at 07:49
  • There are spaces between every value,they should be in same line. tried try catch,it does not give me exception though,program did not pass online test ,but worked in VS though – Azhar Kanorwala Jul 02 '16 at 08:02
  • I just copy paste your code, it works, but your SUM is wrong. SUM should `sum=sum+intArray[k]` but the line `intArray[i] = int.Parse(stringArray[i]);` is ok –  Jul 02 '16 at 08:06
  • Is there a special reason for the redundant data input? The length of stringArray will already tell you the number of items. – Sir Rufo Jul 02 '16 at 08:20
  • New to C#, i used the code from above link at first for taking the inputs horizontally – Azhar Kanorwala Jul 02 '16 at 12:26

2 Answers2

1

You need to access the elements in the array of integers. At the moment you are just adding the loop counter to your sum.

  var n = Convert.ToInt32(Console.ReadLine());
  var stringArray = Console.ReadLine().Split(' ');
  var intArray = new int[100];
  for (var i = 0; i < n; i++)
  {
    intArray[i] = int.Parse(stringArray[i]); // line 17
  }
  var sum = 0;
  for (var k = 0; k <= n; k++)
  {
    sum = sum + intArray[k];
  }
  Console.WriteLine(sum);

Test in Console:
3
10 20 300
330

ChrisF
  • 134,786
  • 31
  • 255
  • 325
0

There is another approach, without n (numbers count). You give only your numbers (10 20 300 ...) then show the SUM :

using System;
using System.Linq;
...    
var stringArray = Console.ReadLine().Split(' ');
var sum = stringArray.Sum(number => int.Parse(number));
Console.WriteLine(sum);