In: Computer Science
(MUST BE DONE IN C (NOT C++))
In this task, you will create a structure with arrays. You will have to create your own structure. However, make sure to meet these guidelines:
- Give the structure whichever name you want.
- It must have at least 3 members.
- Two of the members must be arrays.
- Your members should be of at least two different data-types. In other words, your members cannot be integers only (or floats, or doubles…).
- Your structure cannot have the members as make, mileage, model or price.
Once you define your structure, go ahead and declare one structure of this type inside main. Then, initialize all its members by asking the user (there is no need of functions in this task). When done scanning the information from the user, print it at the end of main.
Code:
#include <stdio.h>
#include <conio.h>
//Defining a structure as per the given
requirement
struct Book {
int bookId;
char bookName[20];
char bookAuthor[20];
int yearPublished;
};
void main() {
int i, j, k, l;
struct Book b1; //Declaring the structure
clrscr();
//Taking user inputs for the structure data
members.
printf("Enter the book id: ");
scanf("%d", &b1.bookId);
printf("\nEnter the book name: ");
for(i = 0; i < 20; i++){
scanf("%c",
&b1.bookName[i]);
if(i > 0 &&
b1.bookName[i] == '\n'){
break;
}
}
printf("\nEnter the author's name:
");
for(j = 0; j < 20; j++){
scanf("%c",
&b1.bookAuthor[j]);
if(j > 0 &&
b1.bookAuthor[j] == '\n'){
break;
}
}
printf("\nEnter the publication year:
");
scanf("%d", &b1.yearPublished);
//Printing the data members
printf("\nBook id is: %d", b1.bookId);
printf("\nBook name is: ");
for(k = 1; k < 13 ; k++){
printf("%c",
b1.bookName[k]);
}
printf("\nBook author's name is: ");
for(l = 0; l < 11; l++){
printf("%c",
b1.bookAuthor[l]);
}
printf("\nBook publication year is: %d",
b1.yearPublished);
getch();
}
Code screenshot:
Output:
Note: C has a very bad garbage collection mechanism. So, printing an unassigned index might give you a garbage value. So, I am printing only the assigned values array.
If you find any trouble in understanding, feel free to ask.