In: Computer Science
Write a program that defines an animal data type, with an animal name, age, and category (cat, dog, etc.), as well as an animal array type that stores an array of animal pointers. (ex.
structType *arr[size];) Your program will prompt the user to enter the data for as many animals as they wish. It will initialize a dynamically allocated animal structure for each animal, and it will store each animal in an instance of the animal array structure. Your program will then print all the animal information to the screen. You will upload your C program as one file.
Source code of the program and its working are given below.Comments are included for better understanding the code.Screen shot of the code and output are also attached.If find any difficulty, feel free to ask in comment section. Please do upvote the answer.Thank you.
Working of the program
Source code
#include<stdio.h>
//including stdlib.h for using malloc() function
#include<stdlib.h>
//defining structure animal
struct animal
{
char name[20];
int age;
char category[20];
};
int main()
{
//declaring integer variables i and n
int n,i;
//prompt user to enter number of animals
printf("Enter the number of animals: ");
//reading number of animals
scanf("%d",&n);
//creating array of animal pointers
struct animal *arr[n];
//for loop to read information of n animals
for(i=0;i<n;i++)
{
//allocating memory for structure
animal and stores its base address to array of pointers
arr[i]=(struct animal
*)malloc(sizeof(struct animal));
//prompt user to enter animal
information
printf("\nEnter animal %d
information:",i+1);
printf("\nAnimal name: ");
//reading into structure animal
using pointer
scanf("%s",&arr[i]->name);
printf("Animal age: ");
//reading into structure animal
using pointer
scanf("%d",&arr[i]->age);
printf("Animal category: ");
//reading into structure animal
using pointer
scanf("%s",&arr[i]->category);
}
printf("\n****Animal information:***");
//printing animal information using for loop
for(i=0;i<n;i++)
{
printf("\n\nAnimal %d
information:",i+1);
printf("\nName:
%s",arr[i]->name);
printf("\nAge:
%d",arr[i]->age);
printf("\nCategory:
%s",arr[i]->category);
}
return 0;
}
Screen shot of the program
Screen shot of the output