This is a small program that is suppose to find out the sum of even numbers entered into an array.... but everything works fine without errors but the output am getting is a negative number.... -1717986920.

#include <iostream.h>
void main()
{
	int sum=0;
	int i, a[6];
	int range;
	cout<<"Enter a range"<<endl;
	cin>>range;
	cout<<"Enter some numbers"<<endl;
	for(i=0;i<range; i++)
	{
		cin>>a[i];
	}
	if (a[i]%2==0)
	{
		sum=a[i];
		sum=sum+a[i];
		cout<<"Sum of even numbers="<<sum<<endl;
	}
}

What's happening is that in your for loop, you're looping while i is less than range. In your loop, the i++ is executed at the end of every loop, so when you put in your numbers, the i variable is being incremented one more time. If you put in a range of 4 and 4 numbers, the i variable ends up being 4 after the for loop. When you try to access a[4], it's producing that number because it's filled with crap as there's no value assigned to it and it wasn't initialized to anything.

I can't understand why you have if outside of a loop.
You could write it like:

#include <iostream.h>
void main()
{
	int sum=0;
	int i, a[6];
	int range;
	cout<<"Enter a range"<<endl;
	cin>>range;
	cout<<"Enter some numbers"<<endl;
	for(i=0;i<range; i++)
	{
		cin>>a[i];
	}
	for (i=0;i<range;i++){
		if (a[i]%2==0)
		{
			sum+=a[i];
		}
	}
        cout<<"Sum of even numbers="<<sum<<endl;
}

or maybe

#include <iostream.h>
void main()
{
	int sum=0;
	int i, a[6];
	int range;
	cout<<"Enter a range"<<endl;
	cin>>range;
	cout<<"Enter some numbers"<<endl;
	for(i=0;i<range; i++)
	{
		cin>>a[i];
		if (a[i]%2==0)
		{
			sum+=a[i];
		}
	}
        cout<<"Sum of even numbers="<<sum<<endl;
}

You need to put your sum statements either inside your loop or inside another loop as mimis demonstrates. However, your use of the array is not good.

What happens if you enter a range of, for example, 10? Here's a hint, it's not good. You really should find a better way to do that whole user-controlled range thing. Without dynamic allocation and pointers, the best way would be with another loop and a series of validation statements.

Edited 6 Years Ago by Fbody: n/a

You can also create the array a after the input of the range as

int a[range]

.

You can also create the array a after the input of the range as

int a[range]

.

Not exactly. You'd need to use new if you're doing it that way.

int *a = new int[range];

You can also create the array a after the input of the range as

int a[range]

.

It depends on the compiler. Most older compilers don't allow that, because the input is not a const value.

Some newer compilers that implement newer standards and certain language extensions will allow it. It's better to use new [] to ensure compatibility.

This question has already been answered. Start a new discussion instead.