My C# code printing random numbers instead of the sum

I am new to C# and was trying to solve the following problem:

Write a program in C# to find the sum of all elements of the array. Go to the editor
Test Data:

Input the number of elements to be stored in the array: 3
Input 3 elements in the array:
element - 0: 2
element - 1: 5
element - 2: 8

Expected Output:

Sum of all elements stored in the array is: 15

Here is the solution I came up with:

Console.Write("Enter the length of the array : ");
int len = Convert.ToInt32 (Console.ReadLine());
int[] arr = new int[len];
for (int i = 0; i < len; i++) {
    arr[i] = Convert.ToInt32(Console.Read());
}
Console.WriteLine(arr.Sum());

But I am getting the following outputs:
1

Can somebody please tell me what I am doing wrong here?

>Solution :

Try changing Console.Read to Console.ReadLine and using int.Parse directly:

for (int ii = 0; ii < len; ii++) {
    arr[ii] = int.Parse(Console.ReadLine());
}

And then enter numbers on different lines (note that usually int.TryParse is recommended to use to validate the input, because int.Parse will throw if string can’t be parsed into a number).

Console.Read already returns an int which is:

The next character from the input stream, or negative one (-1) if there are currently no more characters to be read.

Which represents encoded character (including spaces, letters, etc.) value. I.e. if you enter 1 you will get 49 as the result (try for example Console.WriteLine((int)'1')).

Leave a Reply