Weekly Tip: C does not check if an array index is within the array's bounds. When programming with an array, ensure that its index remains within the array bounds (0 to (s - 1), where s is the array size).
In this lab, you will experiment with arrays. As with the previous labs, if you get stuck, don't be shy about asking for help - that is what the lab sessions are for.
NOTE: When you have completed this lab, and placed answers into the file called "lab8.txt", follow the instructions (at the bottom of this lab) to submit your answers to Murray Saul's e-mail account...
1. Enter the following program (call it lab8a.c):
#include <stdio.h>
main() {
int nums[10], i, tot = 0;
double avg;
for (i = 0; i < 10; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &nums[i]);
tot += nums[i];
}
avg = tot/10.0;
printf("Numbers bigger than the average (%.1lf):", avg);
for (i = 0; i < 10; i++)
if (nums[i] > avg)
printf(" %d", nums[i]);
printf("\n");
}
Run the program a few times, and make sure you understand what the code is doing. Answer the following questions:
a) What does this program do?
__________________________________________________________________________________________________________
b) Why is the first printf written to display i + 1 and not i?
___________________________________________________________________________________________________________
c) Why is tot divided by 10.0 and not 10?
___________________________________________________________________________________________________________
d) Why are two "for" loops needed (i.e. why couldn't it have been done in a single loop)?
____________________________________________________________________________________________________________
#include <stdio.h>
main() {
int qty[5], i;
double cost[5], value, tot = 0;
for (i = 0; i < 5; i++) {
printf("Enter quantity on hand of item %d: ", i + 1);
scanf("%d", &qty[i]);
printf("Enter unit cost of item %d: ", i + 1);
scanf("%lf", &cost[i]);
}
printf("\nInventory Report\n");
printf("Item Quantity Total Value\n");
printf("---- -------- -----------\n");
for (i = 0; i < 5; i++) {
value = qty[i] * cost[i];
tot += value;
printf("%4d%9d%12.2lf\n", i + 1, qty[i], value);
}
printf("Total inventory value: %.2lf\n", tot);
}
Test this program and ensure that you know what is going on. Notice how the numerical values in the conversion specifiers help generate columnar output. In particular, notice the technique of "parallel arrays", where matching positions in different arrays store information about the same item. Answer the following questions:
a) What is the qty array used to store? ___________________________________
b) What is the cost array used to store? ___________________________________
c) Why are two different arrays needed by the program? ____________________________________________________________
Submission Requirements:
If you are in Murray Saul's class, issue the following command to send your lab #8 answers to Murray Saul: