Pal_Ji10dra
Pal_Ji10dra

Reputation: 1

Add even numbers using one dimensional array of size 10 in C

program to calculate sum of all even elements from one dimensional array of size 10.

#include<stdio.h>
void main(){
    int i,count=0;
    int a[10]; //one dimensional array with size 10
    for(i=0;i<=11;i++){
        a[i]=i; //assigning values to array
        if(i%2==0){
            count=count+a[i]; //add even numbers
        }
    }
    printf("%d",count); //output
}

I expected output to be 30 but actual output is 20.

Upvotes: 0

Views: 736

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

This loop

for(i=0;i<=11;i++){

invokes undefined behavior because within the loop there is an attempt to access memory outside the array.

If an array has N elements then the valid range of indices is [0, N). So rewrite the loop like

for(i=0;i < 10;i++){

The reason of the error is using magic numbers. Use named constants instead of magic numbers. For example

#include <stdio.h>

int main(void) 
{
    enum { N = 10 };
    int count = 0;
    int a[N];

    for ( int i = 0; i < N; i++ )
    {
        a[i] = i;

        if ( i % 2 == 0 )
        {
            count += a[i];
        }
    }

    printf( "%d\n", count ); 

    return 0;
}

Pay attention to that according to the C Standard the function main without parameters shall be declared like

int main( void )

Upvotes: 1

J Fabian Meier
J Fabian Meier

Reputation: 35833

You are assigning a[10] and a[11] which is undefined.

Upvotes: 0

Related Questions