Reputation: 25
This program is supposed to take input, put it in an array and output the item #, items in stock, and the sum of the items in the array. Here is the code:
#include <stdio.h>
#define MAX 20
void print_inventory(int inventory[], int numitems);
int input_inventory(int inventory[], int maxnum);
int sum_array(int inventory[], int numitems);
int main()
{
int inventory[MAX];
int num_items;
printf("Please enter the number of items in stock. ");
printf("Enter -1 when you are done.\n");
num_items = input_inventory(inventory, MAX);
print_inventory(inventory, num_items);
return 0;
}
int input_inventory(int inventory[], int maxnum)
{
int index=0;
scanf("%d", &inventory[index]);
while (index < maxnum-1 && inventory[index] != -1){
index++;
scanf("%d", &inventory[index]);
}
if (index == maxnum-1){
printf("No room for more items.\n");
return(index+1);
}
else
return (index);
}
void print_inventory(int inventory[], int numitems)
{
int index;
for (index = 0; index < numitems; index++){
printf("Item number %d:\t\t", index+1);
printf("Number on hand %5d\n", inventory[index]);
}
printf("The total number of items is %d.\n", sum_array(inventory, numitems));
}
int sum_array(int inventory[], int num)
{
int sum, index;
for(index=0; index < num; index++)
sum += inventory[index];
return (sum);
}
When I input the numbers: 7, 4, 6, 7, 9, -1
, the output is 32767
. Which is totally not true. Any idea what's wrong with my sum_array
function?
Upvotes: 0
Views: 244
Reputation: 42889
You need to initialize sum
to zero:
int sum_array(int inventory[], int num)
{
int sum = 0, index;
^^^^^^^^^^^
for(index=0; index < num; index++)
sum += inventory[index];
return (sum);
}
Upvotes: 4