public static void Main(string[] args)
{
int n,sum=0;
n=Convert.ToInt32(Console.ReadLine());
int[] arr=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=Convert.ToInt32(Console.ReadLine());
}
foreach(int j in arr)
{
sum+=arr[j];
}
Console.WriteLine(sum);
}
i/p:6
1
2
3
4
10
11
my o/p:Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. at HelloWorld.Main (System.String[] args) [0x00047] in <616dca5eba0b41f0841fc3be1ba6dff5>:0 [ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array. at HelloWorld.Main (System.String[] args) [0x00047] in <616dca5eba0b41f0841fc3be1ba6dff5>:0
expected o/p:31
if you want to add all the values stored in arr. you were trying to use the input value as a index.
foreach(int j in arr){ sum+=j;}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.