-
Looping Error
Code:
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
int main () {
int auc_num, items, cur_bid, i;
//auc_num being the auction, items for items, and cur_bid for the bids on the auction
float max, total_raised=0;
FILE * ifp = fopen("input.txt", "r");
fscanf(ifp, "%d", &auc_num);
fscanf(ifp, "%d", &items);
//calculating winning bid
for(i=0; i<=items; i++){
fscanf(ifp, "%d", &cur_bid);
if (cur_bid> max)
max = cur_bid;
printf("Auction %d was sold for $%.0f.\n\n", i+1, max);
total_raised += max;
}
printf("The total raised for charity was $%.0f!\n\n", total_raised);
fclose(ifp);
//closes file
return 0;
}
The input was
5
4
100 500 250 300
1
700
3
300 150 175
2
920 680
8
20 10 15 25 50 30 19 23
It's supposed to show the winning bid for every 3rd line, but the output isn't doing that. I think i'm missing an index or maybe my looping is wrong I've tried messing around with it a lot but haven't found a solution.
-
Two changes to make:
1) give max a value of zero, before line #18 starts the for loop. In C, automatic variables like max are not set to 0, by default.
2) don't do this:
Code:
for(i=0; i<=items; i++)
Because you are over-running the last valid item.
do this:
Code:
for(i=0; i<items; i++) //NO EQUAL SIGN
And in C, you will almost always be correct.
-
The variable max is not initialised the first time in the loop. You're mistaken if you expect that an uninitialised variable defaults to a zero value. Why are max and total_raised floats when they are holding integral values?
The printf() saying the item was sold will print out the current maximum for every item.
The loop over items is iterating more than the number of items.
There is also no looping related to the number of auctions (i.e. that is controlled using auc_num). All that code will therefore do is read the first three lines of a file (plus one more value).