c labbook
c labbook
Name_______________________________________________________________________
College_____________________________________________________________________
____________________________
Academic Year________________
1
2
Introduction
1. About the workbook
This workbook is intended to be used by F.Y.B.Sc (Computer Science) students for the Computer Science
laboratory courses in their curriculum. In Computer Science, hands-on laboratory experience is critical to
the understanding of theoretical concepts studied in the theory courses. This workbook provides the
requisite background material as well as numerous computing problems covering all difficulty levels.
1) Explain the assignments and related concepts in around ten minutes using whiteboard if required or by
demonstrating the software.
2) Fill in the blanks with different values for each student.
3) Choose appropriate problems to be solved by student by ticking
Hint :For ‘C’ Language make Set A compulsory, minimum two from Set B and minimum one from
Set C.
For RDBMS: Solve any 3 Sets out of Set A, B, C, D, E 4) Make sure that
students follow the instruction as given above.
5) After a student completes an assignment, the instructor has to verify the outputs and sign in the provided
space after the activity.
3
6) Youshouldevaluateeachassignmentcarriedoutbyastudentonascaleof5asspecifiedabove by ticking
appropriate box.
7) The value should also be entered on assignment completion page of the respective Lab course.
You have to ensure appropriate hardware and software is made available to each student. The operating
system and software requirements on server side and also client side are as given below
1) Server Side and client side
a. Operating System
• Linux
b. Software’s to be installed
• C
• PostgreSQL
Prepared by:
Editors:
Dr. Manisha Bharambe MES Abasaheb Garware College, Pune Dr. Poonam Ponde
Nowrosjee Wadia College, Pune
4
Assignment Completion Sheet
Instructor Head
5
6
Lab Course
Section I
Advanced ‘C’ Programming
7
8
Assignment1: Simple Pointers in C.
Sample Program 1)
The following program illustrate how to handle integer values using pointers main()
{
int a=10, b=20;
int *pa, *pb;
pa=&a;
pb=&b; *pb=*pa+5;
printf(“a=%d\tb=%d\n”,a,b);
printf(“*pa=%d \t *pb=%d\n”,*pa,*pb);
}
9
Sample Program 2)
The following program illustrate call by value and call by reference methods of passing the values.
main()
{
int a = 10, b = 20;
void swap1( int x, int y);
void swap2( int *ptr1, int *ptr2);
Sample Program 3)
The following program illustrate displaying array using pointers
main()
{
int a[]={10, 5, 18, 30, 25};
for(i=0; i<5;i++)
printf(”%d\t”,*(a+i));
}
Sample Program 4)
The following program illustrate displaying matrix using pointers main()
{
int a[2][2]={{10, 5}, {18, 25}};
for(i=0; i<2;i++)
{
for(j=0; j<2; j++)
printf(“%d\n”, *(*(a+i)+j));
}
}
10
Set A: Write C programs for the following problems.
1. Write a program to read two integers using pointers and perform all arithmetic operations on them.
2. Write a program to accept an integer using pointer and check whether it is even or odd.
3. Write a program to find maximum from two integers using pointers.
4. Write a program to display the elements of an array containing n integers in the reverse order using a
pointer to the array.
11
Set A. Write C programs for the following problems.
1. Write a program to read two integers using pointers and perform all arithmetic operations on them.
➢ #include <stdio.h>
int main()
{
int n1, n2;
int sum,difference,product,remainder;
float quotient;
int *ptr1, *ptr2;
clrscr();
printf("Enter two integer numbers: ");
scanf("%d %d", &n1, &n2);
ptr1 = &n1;
ptr2 = &n2;
sum = *ptr1 + *ptr2;
difference = *ptr1 - *ptr2;
product = *ptr1 * *ptr2;
quotient = (float)(*ptr1) / *ptr2;
remainder = *ptr1 % *ptr2;
printf("\nSum: %d", sum);
printf("\nDifference: %d", difference);
printf("\nProduct: %d", product);
printf(“\nQuotient: %.2f”,quotient);
printf("Remainder: %d", remainder);
return;
}
2. Write a program to accept an integer using pointer and check whether it is even or odd.
➢ #include <stdio.h>
int main()
{
int number;
int *ptr;
clrscr();
printf("Enter an integer: ");
scanf("%d", &number);
ptr = &number;
12
if (*ptr % 2 == 0)
{
printf("%d is even.\n", *ptr);
}
else
{
printf("%d is odd.\n", *ptr);
}
return;
}
13
4. Write a program to display the elements of an array containing n integers in the reverse order using a
pointer to the array.
➢ #include <stdio.h>
#define N 5
int main()
{
int a[N], i, *ptr;
clrscr();
printf("Enter %d integer numbers:\n", N);
for (i = 0; i < N; i++)
scanf("%d", &a[i]);
ptr = &a[N - 1];
printf("\nElements of the array in reverse order:\n");
for (i = 0; i < N; i++)
printf("%d\n", *ptr--);
return 0;
}
14
Set B. Write C programs for the following problems.
1. Write a program to read N integers in an array using pointers and display minimum from them.
➢ #include <stdio.h>
#define max_size 100
int main()
{
int arr[max_size];
int N, i,min;
int *ptr = arr;
clrscr();
printf("Enter the size of the array: ");
scanf("%d", &N);
printf("Enter %d integers:\n", N);
for (i = 0; i < N; i++) {
scanf("%d", &ptr[i]);
}
int min = *ptr;
for (i = 1; i < N; i++) {
if (*(ptr + i) < min) {
min = *(ptr + i);
}
}
printf("Minimum value in the array: %d\n", min);
return;
}
2. Accept n integers in array A in main. Write a function which takes this array as
parameter and find minimum and maximum from it. Display these values in main.
➢ #include <stdio.h>
#include <conio.h>
void findMinMax(int A[], int n, int *min, int *max);
int main()
{
int A[100], n, min, max;
printf("Enter the number of integers: ");
scanf("%d", &n);
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++)
15
{
scanf("%d", &A[i]);
}
findMinMax(A, n, &min, &max);
printf("Minimum value: %d\n", min);
printf("Maximum value: %d\n", max);
getch();
return 0;
}
void findMinMax(int A[], int n, int *min, int *max)
{
*min = A[0];
*max = A[0];
for (int i = 1; i < n; i++)
{
if (A[i] < *min)
{
*min = A[i];
}
if (A[i] > *max)
{
*max = A[i];
}
}
getch();
16
Assignment 2:Dynamicmemory allocation in C.
Sample program 1)
The following program illustrate how to accept N integers and store them dynamically and access them.
main()
{
int *p, n,i;
printf(“How many elements :”);
scanf(“%d”,&n);
p = (int *)malloc(n*sizeof(int));
/* Accepting data */
for(i=0; i<n;i++)
scanf(”%d”,p+i);
/*Displaying data*/
for(i=0; i<n;i++)
printf(”%d\t”,*(p+i));
}
Sample program 2)
17
#include<stdio.h>
#include<stdlib.h> main() {
int *a[10],r,c,i,j;
printf("Enter the order of matrix\n");
scanf("%d%d",&r,&c); printf("Enter matrix
elements\n");
for(i=0;i<r;i++)
{
/**** dynamically allocate memory for every row ****/
a[i]=(int *)malloc(c*sizeof(int)); for(j=0;j<c;j++)
{
scanf("%d",a[i]+j);
}
}
/****** Display Matrix ******/
printf("The matrix is as below\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",*(*(a+i)+j));
}
printf("\n");
}
}
19
Set A. Write C programs for the following problems.
20
}
printf("The matrix is as below\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",*(*(a+i)+j));
}
printf("\n");
}
}
3. Write a program to accept N integers and store them dynamically display them in reverse order.
➢ #include <stdio.h>
#include <stdlib.h>
void main() {
int n, i;
int *arr;
clrscr();
printf("Enter the number of integers (n): ");
scanf("%d", &n);
arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed. Exiting...\n");
return 1;
}
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Integers in reverse order:\n");
21
for (i = n - 1; i >= 0; i--) {
printf("%d\n", arr[i]);
}
free(arr);
getch();
}
4. Write a program to allocate memory dynamically for n integers such that the memory is initialized to 0. And
display it.
➢ #include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int *arr;
int n;
printf("Enter the number of integers: ");
scanf("%d", &n);
arr = (int *)calloc(n, sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.");
return 1;
}
printf("Initialized memory:\n");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
free(arr);
getch();
return 0;
}
22
Set B. Write C program for the following problems.
1. Accept N integers in an array using dynamic memory allocation. Find maximum from them and display.
➢ #include <stdio.h>
#include <stdlib.h>
void main()
{
int N, i,max;
int *arr;
clrscr();
printf("Enter the number of integers (N): ");
scanf("%d", &N);
arr = (int *)malloc(N * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed. Exiting...\n");
return 1;
}
printf("Enter %d integers:\n", N);
for (i = 0; i < N; i++) {
scanf("%d", &arr[i]);
}
int max = arr[0];
for (i = 1; i < N; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
printf("Maximum value in the array: %d\n", max);
free(arr);
getch();
}
23
2. Accept n integers in an array. Copy only the non-zero elements to another array (allocated using dynamic
memory allocation). Calculate the sum and average of non zero elements.
➢ #include <stdio.h>
#include <stdlib.h>
int main() {
int N, i, j, count = 0;
int *arr, *nonzeroarr;
double sum = 0.0, average;
clrscr();
printf("Enter the number of integers (N): ");
scanf("%d", &N);
arr = (int *)malloc(N * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed. Exiting...\n");
return 1;
}
printf("Enter %d integers:\n", N);
for (i = 0; i < N; i++) {
scanf("%d", &arr[i]);
if (arr[i] != 0) {
count++;
sum += arr[i];
}
}
nonzeroarr = (int *)malloc(count * sizeof(int));
if (nonzeroarr == NULL) {
printf("Memory allocation failed. Exiting...\n");
free(arr);
return 1;
}
j = 0;
for (i = 0; i < N; i++) {
if (arr[i] != 0) {
nonzeroarr[j] = arr[i];
j++;
}
}
if (count > 0) {
average = sum / count;
printf("Sum of non-zero elements: %.2lf\n", sum);
24
printf("Average of non-zero elements: %.2lf\n", average);
} else {
printf("No non-zero elements found.\n");
}
free(arr);
free(nonzeroarr);
return;
}
25
26
Assignment 3: String handling in C and standard library functions for strings
A string is an array of characters terminated by a special character called NULL character(\0). Each character
is stored in 1 byte as its ASCII code.
An array of strings is a two dimensional array of characters. It can be treated as a 1-D array such that each
array element is a string.
Actions Explanation Example
Involving
strings
Declaring char string_name[size]; char str[80];
Strings
Initializing char str[]= { ’G’, ’o ’, ’o’,
Strings d’,’\0’ };
char str [ ] = “Hello”;
Accepting scanf and gets can be used to accept strings char name[20], address[50];
Strings printf(“\n Enter your
name”);
scanf(“%s”,name);
printf(“\n Enter your
address”); gets(address);
Displaying printf and puts can be used to display strings. Printf(“\n The name is %s:”,
Strings name);
printf(“\n The address is :”);
puts(address);
Declaring char array[size1][size2]; char cities[4][10]
String array
All string operations are performed using functions in “string.h”. Some of the most commonly used functions
are
a. strlen(str) – Returns the number of characters in the string (excluding \0)
b. strcpy(deststr, srcstr) – Copies one string to another
c. strcmp(str1,str2) – Compares two strings. Returns 0 (equal), +ve (first string > second), -ve (first string
<second ). It is case sensitive.
d. strcmpi(str1,str2) – Same as strcmp but ignores case
e. strcat(str1,str2) – Concatenates the second string to the first. Returns the concatenated string.
f. strchr(str1, ch) – truncate the string before first occurrence of character in the string.
g. strrchr(str1,ch) –truncate the string before last occurrence of character in the string.
Sample program 1)
#include <string.h>
27
main( )
{
char str1[30],str2[30],str3[60];
printf(“\nEnter the first string:”); gets(str1);
printf(“\n Enter the second string string:”);
gets(str2);
if (strlen(str1) == strlen(str2))
{
strcpy(str3,strrev(str1));
strcat(str3,str2);
puts(str3);
}
else
{
strcat(str1,str2);
puts(str1);
}
}
Sample Program 2)
#include <stdio.h> main( )
{
charlist[10][20]; /*list is an array of 10 strings*/
charname[20];
int i,n;
printf(“\n How many names ?:”);
scanf(“%d”, &n);
/* Accepting n names */
for (i=0;i<n; i++)
{
printf(“\n Enter name %d,”i);
gets(list[i]);
}
28
Set A. Write C programs for the following problems.
1. Write a program to read a string and copy it to another sting and display copied string. Also the length of
copied string. (Use built in functions)
2. Write a program to read two strings. If first string is greater than second then concatenate second to first
and display concatenated string, If first string is smaller than second then concatenate first to second, other-
wise display length of string. (use strcmp)
3. Write a program to read a string and one character. Check whether given character is present in the given
string or not? (Hint: use strchr or strrchr)
29
Set A. Write C programs for the following problems.
1. Write a program to read a string and copy it to another sting and display copied string. Also the length of
copied string. (Use built in functions)
➢ #include <stdio.h>
#include <string.h>
int main() {
char source[100];
char destination[100
int length;
printf("Enter a string: ");
gets(source);
strcpy(destination, source);
length = strlen(destination);
printf("Copied string: %s\n", destination);
printf("Length of copied string: %d\n", length);
return 0;
}
2. Write a program to read two strings. If first string is greater than second then concatenate second to first
and display concatenated string, If first string is smaller than second then concatenate first to second, other-
wise display length of string. (use strcmp)
➢ #include <stdio.h>
#include <string.h>
int main() {
char str1[100];
char str2[100];
int compareresult;
printf("Enter the first string: ");
gets(str1);
printf("Enter the second string: ");
gets(str2);
compareresult = strcmp(str1, str2);
if (str1<str2)
{
30
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
}
else if (str1>str2)
{
strcat(str2, str1);
printf("Concatenated string: %s\n", str2);
}
else
{
printf("Length of the string: %d\n", strlen(str1));
}
return 0;
}
3. Write a program to read a string and one character. Check whether given character is present in the given
string or not? (Hint: use strchr or strrchr)
➢ #include <stdio.h>
#include <string.h>
int main() {
char str[100];
char ch;
char *result;
printf("Enter a string: ");
gets(str);
printf("Enter a character to search for: ");
scanf(" %c", &ch);
result = strchr(str, ch);
if (result) {
31
printf("Character '%c' is present in the string.\n", ch);
printf("First occurrence found at index: %d\n", result - str);
}
else {
printf("Character '%c' is not present in the string.\n", ch);
}
return 0;
}
32
Set B. Write C programs for the following problems.
1. Write a program which accepts a sentence from the user. Find and display reverse of it.
(Don’t use any function).
➢ #include <stdio.h>
#include <conio.h>
int main() {
char sentence[100];
int length = 0, i;
printf("Enter a sentence: ");
gets(sentence);
while (sentence[length] != '\0') {
length++;
}
printf("Reverse of the sentence: ");
for (i = length - 1; i >= 0; i--) {
printf("%c", sentence[i]);
}
getch();
return 0;
}
2. Write a program that accepts n words and outputs them in dictionary order.
➢ #include<stdio.h>
#include<string.h>
#define size 100
void order(int n);
void main()
{
int n;
printf("\n How many words/names do you want to sort:- ");
scanf("%d",&n);
printf("\n");
order(n);
printf("\n");
}
void order(int n)
{
char list[5][20],temp[20];
int i,j;
33
for(i=0;i<n;i++)
scanf("%s",list[i]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(strcmp(list[i],list[j])>0)
{
strcpy(temp,list[i]);
strcpy(list[i],list[j]);
strcpy(list[j],temp);
}
}
printf("\n Words/Names in sorted alphabetical order:- ");
for(i=0;i<n;++i)
printf("\n %s",list[i]);
}
34
Assignment 4: String handling using user defined function and pointers.
Sample program 1)
The following program illustrate user defined function for converting string to lower case without
using pointers
#include<stdio.h>
void string_lower(char t[20], char s[20])
{
int i=0;
while(s[i] != ’\0’)
{
if (‘A’ <= s[i] && s[i] <=’Z’)
t[i]=s[i]-32;
else
t[i]=s[i];
}
t[i]=’\0’; /* terminate target string */
}
main()
{
char str1[30],str2[30];
printf(“Enter string: ”);
gets(str1);
string_lower(str2,str1);
printf(“Converted string is : %s\n”,str2);
}
Sample program 2)
The following program illustrate function for string copy using pointers
#include<stdio.h>
void string_copy(char *t, char *s)
{
while(*s != ’\0’)
{
*t=*s;
s++; t++;
}
*t=’\0’; /* terminate target string */
}
main()
{ char str1[30],str2[30];
printf(“Enter string: ”);
string_copy(str2,str1);
gets(str1);
35
printf(“Copied string is : %s\n”,str2);
}
36
3. Write a function, which displays a given number in words. Use it in main() function.
For Example: 129 One Hundred Twenty Nine
2019 Two Thousand Nineteen
37
Set A. Write C programs for the following problems.
1. Write a program to accept a string and find its length using user defined function.
(Don’t use pointers)
➢ #include <stdio.h>
int find(char input[]);
int main()
{
char str[100];
int len,length;
clrscr();
printf("Enter a string: ");
scanf("%s", str);
len = find(str);
printf("Length of the string: %d\n", len);
return 0;
}
int find(char input[])
{
int length=0;
while (input[length] != '\0')
{
length++;
}
return length;
}
2. Write a function that takes a string as parameter and returns the same string in upper case(use pointers).
Accept this string in main and display converted string in main only.
➢ #include <stdio.h>
#include <ctype.h>
void convert(char *str);
int main()
{
char input[100];
clrscr();
38
printf("Enter a string: ");
scanf("%s", input);
convert (input);
printf("Converted string: %s\n", input);
return 0;
}
void convert(char *str);
{
while (*str != '\0') {
*str = toupper(*str);
str++;
}
getch();
}
41
42
Assignment 5: Structures and union in C
Structure: A structure is a composition of variables possibly of different data types, grouped together under a
single name. Each variable within the structure is called a ‘member’.
Nested structures: The individual members of a structure can be other structures as well. This is called nesting
of structures.
Union : A union is a variable that contains multiple members of possibly different data types grouped together
under a single name. However, only one of the members can be used at a time. They occupy the same memory
area.
Operations performed Syntax / Description Example
43
Creating a nested struct structure2 { struct date
structure ... {
Method 2 }; int dd, mm, yy;
};
struct structure1 {
... struct student
struct structure2 {
variable; int rollno; char
... name[20]; struct date
}; admdate;
};
Sample Program 1)
The following program illustrate array of structures.
#include<stdio.h>
struct student
{
int rollno;
char name[20]:
int marks[3];
floatperc;
};
void main()
{
int i, sum j;
struct student s[10];
printf("n Enter the details of the 10 students \n");
for (i=0;i<10;i++)
{
printf("\n Enter the name and roll number \n");
scanf("%s%d",s[i].name, &s[i].rollno);
44
printf("\n Enter marks for three subjects:");
sum=0;
for (j=0;j<3:j++)
{
scanf("%d", &s[i].marks[j]);
sum = sum + s[i].marks[j];
}
s[i].perc= (float)sum/3;
}
/* Display details of students */
printf("\n\n Name it Roll not Percentage");
printf("\n=====================================\n”);
for(i=0;i<10;i++)
{
printf("\n%s\t%d\t%f",s[i].name,s[i].rollno,s[i].pere);
}
}
Sample Program 2)
The following program illustrate union.
structure is for a library book with the following details : id, title, publisher, code ( 1 – Text book, 2 – Magazine,
3 – Reference book). If the code is 1, store no-of-copies. If code = 2, store the issue month name. If code = 3,
store edition number. Also store the cost.
struct library_book
{
int id;
char title[80],publisher[20] ;
int code;
union u
{
int no_of_copies; char month[10]; int edition;
}info;
intcost;
};
void main( )
{
struct library_book book1;
printf(“\n Enter the details of the book \n”);
45
switch(book1.code)
{
casel: printf("Copies = %d:",book1.info.no_of_copies);
break;
case2: printf("Issue month name=%s", book1.info.month);
break;
case3:printf("Edition number-%d:",book1.info.edition);
break;
} printf(“\n Cost = %d”, book1.cost);
}
2. Create a structure car (car number, model name, colour, cost). Accept details of n cars and write amenu
driven program to perform the following operations. Write separate functions for the different options.
i) Search byname
ii) Displayall
3. Create a structure movie (name, release year, duration). Accept details of n movies.
Write a function to sort them according to release year. Display them in main() function.
(Hint: Use dynamic memory allocation.)
1. Create a structure Fraction (numerator, denominator). Accept details of n fractions and write a menu driven
program to perform the following operations. Write separate functions for the different options. Use
dynamic memoryallocation.
i)Display the largestfraction
ii) Display the smallestfraction
iii) Sortfractions
iv) Displayall
Note: While accepting fractions, store the fractions in the reduced form.
46
2. Modify the sample program 2 above to accept details for n books and write a menu driven program for the
following:
3. i.)Display all referencebooks
ii) Search magazine according for specification
iii)Find the total cost of all the books
(Hint : Useno)
4. Create a structure employee(id, name, joiningdate(dd, mm, yyyy)). Accept the details for n employees.
Accept month and display the details of employee having birthdate in that month. (Hint : Use
Nestedstructure)
47
Set A . Write C programs for the following problems.
1. Create a structure employee (id, name, salary). Accept details of n employees and display display it in
summary format.
#include <stdio.h>
#include <conio.h>
struct employee {
int id;
char name[50];
int salary;
};
int main() {
struct employee emp[100];
int n, i;
clrscr();
printf("Enter the number of employees: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nEnter details for employee %d:\n", i + 1);
printf("ID: ");
scanf("%d", &emp[i].id);
printf("Name: ");
scanf("%s", emp[i].name); // Note: No spaces allowed in name
printf("Salary: ");
scanf("%d", &emp[i].salary);
}
printf("\nEmployee Summary:\n");
printf("ID\tName\t\tSalary\n");
for (i = 0; i < n; i++) {
printf("%d\t%s\t\t%d\n", emp[i].id, emp[i].name, emp[i].salary);
}
getch();
return 0;
}
48
2. Type sample program 2 and execute it.
struct library_book
{
int id;
char title[80],publisher[20] ;
int code;
union u
{
int no_of_copies; char month[10]; int edition;
}info;
int cost;
};
void main( )
{
struct library_book book1;
clrscr();
printf(“\n Enter the details of the book \n”);
printf(“\n Enter the id, title and publisher \n”);
scanf(“%d%s%s”,&book1.id, book1.title, book1.publisher);
printf(“\nEnterthecode:1-TextBook,2-Magazine,3-Reference”);
scanf(“%d”,book1.code);
switch(book1.code)
{
casel: printf("Copies = %d:",book1.info.no_of_copies);
break;
case2: printf("Issue month name=%s", book1.info.month);
break;
49
case3: printf("Edition number-%d:",book1.info.edition);
break;
}
printf(“\n Cost = %d”, book1.cost);
getch();
}
50
Set B . Write C programs for the following problems.
1. Create a structure car (car number, model name, colour, cost). Accept details of n cars and write amenu
driven program to perform the following operations. Write separate functions for the different options.
i) Search byname
ii) Displayall
➢ #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define MAX_CARS 100
#define MAX_NAME_LENGTH 50
struct car {
int carNumber;
char modelName[MAX_NAME_LENGTH];
char colour[MAX_NAME_LENGTH];
float cost;
};
void searchByName(struct car cars[], int n, char name[]);
void displayAll(struct car cars[], int n);
int main() {
struct car cars[MAX_CARS];
int n, choice;
char modelName[MAX_NAME_LENGTH];
clrscr();
printf("Enter the number of cars: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("\nEnter details for car %d:\n", i + 1);
printf("Car Number: ");
scanf("%d", &cars[i].carNumber);
printf("Model Name: ");
scanf("%s", cars[i].modelName);
printf("Colour: ");
scanf("%s", cars[i].colour);
printf("Cost: ");
scanf("%f", &cars[i].cost);
}
do {
printf("\nMenu:\n");
printf("1. Search by model name\n");
printf("2. Display all cars\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
51
switch (choice) {
case 1:
printf("Enter the model name to search: ");
scanf("%s", modelName);
searchByName(cars, n, modelName);
break;
case 2:
displayAll(cars, n);
break;
case 3:
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 3);
getch();
return 0;
}
void searchByName(struct car cars[], int n, char name[]) {
int found = 0;
for (int i = 0; i < n; i++) {
if (strcmp(cars[i].modelName, name) == 0) {
printf("Car Number: %d\n", cars[i].carNumber);
printf("Model Name: %s\n", cars[i].modelName);
printf("Colour: %s\n", cars[i].colour);
printf("Cost: %.2f\n", cars[i].cost);
found = 1;
break;
}
}
if (!found) {
printf("Car with model name '%s' not found.\n", name);
}
}
void displayAll(struct car cars[], int n) {
printf("Details of all cars:\n");
for (int i = 0; i < n; i++) {
printf("Car Number: %d\n", cars[i].carNumber);
printf("Model Name: %s\n", cars[i].modelName);
printf("Colour: %s\n", cars[i].colour);
printf("Cost: %.2f\n", cars[i].cost);
printf("\n");
}
getch();
52
}
53
2. Create a structure movie (name, release year, duration). Accept details of n movies.
Write a function to sort them according to release year. Display them in main() function.
(Hint: Use dynamic memory allocation.)
➢ #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[50];
int release_year;
int duration;
} Movie;
int compare(const void *a, const void *b) {
return (((Movie *)a)->release_year - ((Movie *)b)->release_year);
}
int main() {
int n, i;
printf("Enter the number of movies: ");
scanf("%d", &n);
Movie *movies = (Movie *)malloc(n * sizeof(Movie));
for(i = 0; i < n; i++) {
printf("Enter details for movie %d\n", i+1);
printf("Name: ");
scanf("%s", movies[i].name);
printf("Release Year: ");
scanf("%d", &movies[i].release_year);
printf("Duration: ");
scanf("%d", &movies[i].duration);
}
qsort(movies, n, sizeof(Movie), compare);
printf("\nMovies sorted by release year:\n");
for(i = 0; i < n; i++) {
printf("Name: %s, Release Year: %d, Duration: %d\n", movies[i].name,
movies[i].release_year, movies[i].duration);
}
free(movies);
getch();
}
54