Search code examples
c#arrayssumnumbersc#-3.0

I'm trying to sum the 5 number that entered by the user but it doesn't calculate. in c#


static void Main(string[] args)
{
    int[] numbers = new int[5];
    int sum = 0;
    int i;
    Console.WriteLine("Input 5 elements in the array :");
   
    for (i= 0; i < numbers.Length; i++) 
    {
        Console.WriteLine($"element index {i}: ");
        numbers[i] = Convert.ToInt32(Console.ReadLine());
    }
    
    sum = sum + numbers[i];
    
    Console.WriteLine("The sum of the elements of the array is " + sum);
    Console.ReadLine();
    

}

I need it like that

Input 5 elements in the array :

element index 0: 1

element index 1: 1

element index 2: 1

element index 3: 1

element index 4: 1

Expected Output : The sum of the elements of the array is 5


Solution

  • Your "summing" is occurring OUTSIDE the loop, the correction is as follows:

    using System;
                        
    public class Program
    {
        public static void Main()
        {
            
           int[] numbers = new int[5];
           int sum = 0;
           int i;
    
    
           Console.WriteLine("Input 5 elements in the array :");
       
           for (i= 0; i < numbers.Length; i++) 
           {
    
               Console.WriteLine($"element index {i}: ");
    
               numbers[i] = Convert.ToInt32(Console.ReadLine());
    
               sum = sum + numbers[i];
    
           }
        
           Console.WriteLine("The sum of the elements of the array is " + sum);
           Console.ReadLine();
            
        }
        
    }