Answer to Question #204543 in C for Lucy

Question #204543

Write a C program that declares an array of structures of type ‘car’, and asks the user to fill in the elements. Once all the structures have been initialized, the program should present a menu to the user so that he can print a certain structure, or modify its elements.


1
Expert's answer
2021-06-08T07:56:56-0400
#include<stdio.h>
#include<stdlib.h>


struct car{
	char make[30];
	char model[30];
	int capacity;
	float weight;
};


int main( void){
	struct car cars[100];
	int totalCars=0;
	int ch=-1;
	int i;
	int selectedCar=-1;


	while(ch!=4){
		printf("1. Add a new car\n");
		printf("2. Display all car\n");
		printf("3. Modify the car\n");
		printf("4. Exit\n");
		printf("Your choice: ");
		scanf("%d",&ch);
		fflush(stdin);
		if(ch==1){
			printf("Enter the make of the car: ");
			gets(cars[totalCars].make);
			printf("Enter the model of the car: ");
			gets(cars[totalCars].model);
			printf("Enter the capacity of the car: ");
			scanf("%d",&cars[totalCars].capacity);
			printf("Enter the weight of the car: ");
			scanf("%f",&cars[totalCars].weight);
			totalCars++;
			printf("\nA new car has been added.\n\n");
		}else if(ch==2){
			if(totalCars>0){
				printf("\n\n%-10s%-20s%-20s%-20s%-20s\n","#","Car make","Car model","Car capacity","Car weight");
				for(i=0;i<totalCars;i++){
					printf("%-10d%-20s%-20s%-20d%-20.2f\n",(i+1),cars[i].make,cars[i].model,cars[i].capacity,cars[i].weight);
				}
			}else{
				printf("\nThe array of cars is empty.\n\n");
			}
		}else if(ch==3){
			if(totalCars>0){
				selectedCar=-1;
				if(selectedCar<=0 || selectedCar>totalCars){
					printf("Select car # to edit [1-%d]: ",totalCars);
					scanf("%d",&selectedCar);
				}
				selectedCar--;
				fflush(stdin);
				printf("Enter a new make of the car: ");
				gets(cars[selectedCar].make);
				printf("Enter a new model of the car: ");
				gets(cars[selectedCar].model);
				printf("Enter a new capacity of the car: ");
				scanf("%d",&cars[selectedCar].capacity);
				printf("Enter a new weight of the car: ");
				scanf("%f",&cars[selectedCar].weight);
				printf("\nThe car has been updated.\n\n");
			}else{
				printf("\nThe array of cars is empty.\n\n");
			}
		}else if(ch==4){
			//exit
		}else{
			printf("\nWrong menu item.\n\n");
		}
	}


	
	return 0;
}





Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS