First, there are code tags that make posted code easier to read and comment.
Please use them. See
http://www.cplusplus.com/articles/jEywvCM9/
I'll repost your code in tags :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <stdio.h>
using namespace std;
int main()
{
int i=0, s=0, a[i], n;
scanf( "%d", &n );
for ( i=0; i<n; i++ )
{
scanf( "%d", &a[i] );
if ( a[i] % n == 0 )
{
n--;
a[i] = 0;
}
s += a[i];
}
printf( "%d", s );
return 0;
}
|
You seem to write in C. The header file and the functions scanf() and printf() are from C Standard Library. The C++ can use them, but has more convenient tools for same tasks.
You do have a serious error on line 7. You do create an array there. The
a
. How many elements does that array have?
The i==0, so you effectively write:
int a[0];
How many integers are in a bag that has 0 integers? 0
How many integers can you put into bag that can hold 0 integers? 0
That is the nature of arrays. Their size is fixed.
In your loop the loop counter 'i' gets values 0, 1, 2, .. n-1
None of them is a valid index for array
a
.
Every time you write to
a[i]
, an
out of range error occurs. You overwrite somebody else's memory. The result is
undefined behaviour.
You could decide what is the largest n that the user is allowed to give. You could then create an array with that many elements. When the user does give n, you must check that it is not larger than you allow. Then you would have enough space in your array.
You do have an another logical issue. The program does not do what it should.
Lets use your example:
* the user says: n=10
* first input: 1
* 10%1==0 and therefore you decrease n to 9
* you add 0 to sum
* second input: 2
* 9%2 != 0. You add 2 to the sum
That is not what it was supposed to be.
The program should first read all n values in.
Then it should look at all n values and remove the undesirables.
The n updates only after all values have been checked.
If the n does update, then recheck all remaining values with the new n.
Repeat until no more undesirables are found.
Now you can compute the sum of remaining values.