โจทย์
จัดเก็บข้อมูลหนังสือในห้องสมุดด้วยภาษา C
อัลกอริทึม
Step 1: ประกาศ struct เก็บข้อมูลหนังสือ
Step 2: ใช้ switch case จัดการเมนู
Case 1: เพิ่มข้อมูลหนังสือ
Case 2: แสดงข้อมูลหนังสือ
Case 3: นับจำนวนหนังสือ
Case 4: ออกจากโปรแกรม
โปรแกรม
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct library {
char bookname[50];
char author[50];
int noofpages;
float price;
};
int main() {
struct library lib[100];
char bookname[30];
int i, j, keepcount = 0;
while (j != 6) {
printf("\n1. Add book information\n");
printf("2. Display book information\n");
printf("3. No of books in the library\n");
printf("4. Exit\n");
printf("Enter one of the above: ");
scanf("%d", &j);
switch (j) {
case 1:
printf("Enter book name = ");
scanf("%s", lib[i].bookname);
printf("Enter author name = ");
scanf("%s", lib[i].author);
printf("Enter pages = ");
scanf("%d", &lib[i].noofpages);
printf("Enter price = ");
scanf("%f", &lib[i].price);
keepcount++;
i++;
break;
case 2:
printf("You have entered the following information\n");
for (i = 0; i < keepcount; i++) {
printf("Book name = %s\n", lib[i].bookname);
printf("\tAuthor name = %s\n", lib[i].author);
printf("\tPages = %d\n", lib[i].noofpages);
printf("\tPrice = %f\n", lib[i].price);
}
break;
case 3:
printf("\nNo of books in library: %d\n", keepcount);
break;
case 4:
exit(0);
}
}
return 0;
}
ผลลัพธ์ตัวอย่าง
1. Add book information
2. Display book information
3. No of books in the library
4. Exit
Enter one of the above: 1
Enter book name = HarryPotter
Enter author name = hp
Enter pages = 250
Enter price = 350.6
...