Simple Array program to display sum in array



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include<stdio.h>
 void main()
 {
 int i ;
 int arr [4]; 
int sum=o;
 for (i=0; i<=4; i++) 
{ 
printf (“enter %d element \n”, i+1);
 scanf (“%d”, &arr[i]);
 } 
for (i=0; i<=4; i++)
 { 
sum = sum + a[i];
 } 
printf (“the sum of  is %d”, sum);
 }

Enter a value for arr[0] =5 
Enter a value for arr[1] =10
 Enter a value for arr[2] =15
 Enter a value for arr[3] =20
The sum is 50
.
You didn't ask a question.
However, clearly the issue is that you're going out of bounds.
arr[4] has 4 indices, but they are 0 to n -1, so arr[0], arr[1], arr[2], arr[3].
Not 4 itself.

Also, in both C and C++, main should return int, not void.
Last edited on
for (i=0; i<=4; i++) max index for array is 3
The for loops at lines 7 and 12 are making the array go out of bounds, you are trying to write/read 5 elements in a 4 element array:
for (i = 0; i < 4; i++)

Line 6, 0 (zero), not o. o is an undefined variable.

Line 14, did you mean arr[i]? a[i] is an undefined array.

Your quotes (") are some weird typographic quotes, not plain text file quotes.

The C standard for main is int main(void) or int main(int argc, char *argv[]). void main() hasn't been legal C or C++ for quite some time.
https://en.cppreference.com/w/c/language/main_function

Though some implementations do allow it, using void main() is not guaranteed to be portable.
Last edited on
Topic archived. No new replies allowed.