B
Bail
I will have a exam on the oncoming friday, my professor told us that it
will base upon this program. i am having troubles understanding this
program, for example what if i want to add all the total calories that
the user input together. determine which food has the largest calories.
how do i start to modifiy the program inorder to do the things i listed
above. thanks
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int calories;
int group;
} FOOD;
void getFood(FOOD foods[ ], int i ) {
FOOD newFood;
void *characters = malloc(81*sizeof(char));
printf("\nPlease enter the requested information:\n");
printf(" for food item %d, what is\n", i+1);
printf(" the name? ");
gets( characters); // NOTE fgets IS BETTER!
newFood.name = characters;
printf(" calories/serving? ");
scanf("%d", &(newFood.calories));
printf(" food group? ");
scanf("%d", &(newFood.group));
printf("\n");
foods = newFood;
} // end getFood // note:a struct is and lvalue !!
void dump( FOOD foods[ ] , int n ) {
int i;
for(i=0; i<n; i++ ) {
printf("Food %d is: \n", i+1);
printf(" name : %s\n", foods.name);
printf(" calories: %d\n", foods.calories);
printf(" group # : %d\n", foods.group);
printf("\n");
} // end for
} // end dump
int main( ) {
int num; // number of foods entered
int i;
char dum[81];
printf("\nHow many foods will you enter? ");
scanf("%d", &num);
FOOD foods[num];
for( i=0; i<num; i++ ) {
gets(dum); //NOTE: THIS IS HERE BECAUSE OF SCANF
getFood( foods, i );
} // end for
dump( foods, num);
return 0;
} // end main
will base upon this program. i am having troubles understanding this
program, for example what if i want to add all the total calories that
the user input together. determine which food has the largest calories.
how do i start to modifiy the program inorder to do the things i listed
above. thanks
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int calories;
int group;
} FOOD;
void getFood(FOOD foods[ ], int i ) {
FOOD newFood;
void *characters = malloc(81*sizeof(char));
printf("\nPlease enter the requested information:\n");
printf(" for food item %d, what is\n", i+1);
printf(" the name? ");
gets( characters); // NOTE fgets IS BETTER!
newFood.name = characters;
printf(" calories/serving? ");
scanf("%d", &(newFood.calories));
printf(" food group? ");
scanf("%d", &(newFood.group));
printf("\n");
foods = newFood;
} // end getFood // note:a struct is and lvalue !!
void dump( FOOD foods[ ] , int n ) {
int i;
for(i=0; i<n; i++ ) {
printf("Food %d is: \n", i+1);
printf(" name : %s\n", foods.name);
printf(" calories: %d\n", foods.calories);
printf(" group # : %d\n", foods.group);
printf("\n");
} // end for
} // end dump
int main( ) {
int num; // number of foods entered
int i;
char dum[81];
printf("\nHow many foods will you enter? ");
scanf("%d", &num);
FOOD foods[num];
for( i=0; i<num; i++ ) {
gets(dum); //NOTE: THIS IS HERE BECAUSE OF SCANF
getFood( foods, i );
} // end for
dump( foods, num);
return 0;
} // end main