#include <stdio.h>
int main (int argc, const char * argv[])
{
static struct item
{
char code;
float price;
}
table[] =
{
{'a', 3.29},
{'b', 2.99},
{'c', 0.59},
{'d', 1.59},
{'e', 2.39}
};
char item_code[2];
int quantity;
int i;
do {
printf("Enter item code: ");
scanf("%1s", item_code);
if (*item_code != '.') {
for (i=0; i< sizeof(table)/sizeof(struct item)
&& table[i].code != *item_code; i++);
if (i < sizeof(table)/sizeof(struct item)) {
printf("Enter quantity: ");
scanf("%d", &quantity);
printf("\nUnit price = %.2f, total price = %.2f.\n\n\n",
table[i].price, quantity * table[i].price);
}
else
printf("\nItem code %c does not exist. \n\n\n", *item_code);
}
} while (*item_code != '.');
printf("Thank you.\n");
return 0;
}
I am a newbie. I am unable to understand the second “for loop” in the above program. Why is sizeof being used? What exactly is the value of “i” each time the loop is executed?
Thanks.
Let’s examine some simple code in a system where integers are four bytes long:
As per that final line, that calculation is a way to get the number of items in an array.
As an aside, I prefer the construct:
since that will continue to work even if I change the type of
xyzzytodoublefor example. It means I only need to change the one line where the variable is declared rather than hunting for all the size calculations as well.In fact I even have a favorite macro for this:
to make my code a little smaller.
In terms of what that
forloop is doing exactly (and, by the way, it’s not technically the secondforloop since there’s only one, but it is the second loop), it basically iterates through every value ofi(staring at 0, the first index) until it reaches either the point beyond the last element or it finds an element with the desired item code.On exit from that loop,
iwill be set to the number of elements if the item code wasn’t found or set to the correct index if it was found, hence theifstatement following thatforloop.