Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding values from 1dimensional array

Status
Not open for further replies.

iamjd

Technical User
Feb 12, 2005
37
US
#include<stdafx.h>

int main()
{
int isbn[10];
int isbnSum;
int i;

for (i=1;i<=10;i++)
{
printf("Enter digit # %d of isbn number.\n", i);
scanf("%d", &isbn);
}

for (i=1;i<=10;i++)
{
isbnSum += isbn;
}

printf("Sum: %d\n", isbnSum);
return 0;
}

Each time i run this program I get some really weird number, almost like an integral memory address location. I want it to add all of the values that belong to the array from array position 1 to 10. I can't spot an error in my code, but it is clear that there must be if i'm not getting the value I should get.

What am I doing wrong?
 
If you declare an array of size 10, the indices go from 0 to 9.
Code:
    for (i=[COLOR=red]0[/color];i[COLOR=red]<[/color]10;i++)
 
I am still getting a negative answer, something like -8273464. The code I am using is below:
Code:
#include <stdafx.h>

int main()
{
	int isbn[10];
	int isbnSum;
	int i;

	for (i=0;i<10;i++)
	{
		printf("Enter digit # %d of isbn number.\n", i + 1);
		scanf("%d", &isbn[i]);
	}

	for (i=0;i<10;i++)
	{	
		isbnSum += isbn[i];
	}

	printf("Sum: %d\n", isbnSum);
	return 0;
}
 
Hi:

Try initializing you sum variable:

int isbnSum=0;
 
yes. initializing my sum variable did the trick! Also starting my index from 0 to 9 worked as well. since arrays start from 0 i assume?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top