0% found this document useful (0 votes)
7 views27 pages

C Unit 4

The document covers various concepts related to programming in C, specifically focusing on structures, unions, and dynamic memory allocation. It includes definitions, syntax, examples, and comparisons between structures and arrays, as well as operations on linked lists. Additionally, it provides sample code snippets and explanations for nested structures, self-referential structures, and memory management functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views27 pages

C Unit 4

The document covers various concepts related to programming in C, specifically focusing on structures, unions, and dynamic memory allocation. It includes definitions, syntax, examples, and comparisons between structures and arrays, as well as operations on linked lists. Additionally, it provides sample code snippets and explanations for nested structures, self-referential structures, and memory management functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

CS3451 – PROGRAMMING IN C

ACADEMIC YEAR 2024-2025 (EVEN)


Department of Computer Science and Engineering
UNIT-IV

PART-A

1. How the nested structure can define in C, explain with syntax and example?
(CO4) (Apr/May 2024)
A structure that contains another structure as its member is called a nested structure.
Syntax
struct name_1
{
member 1;
member 2;
.
.
member n;
};
struct name_2
{
member_1;
member_2;
.
.
member_n;
};
struct structure_name variable_name;
Example
struct DOB
{
int day;
int month;
int year;
};
struct student
{
int roll_no;
char name [100];

SRM MCET / CSE / QUESTION BANK 1


CS3451 – PROGRAMMING IN C

float fees;
struct DOB date;
};
struct student stud1;

2. What will be the output of the following code? (CO4) (Apr/May 2024)
#include<stdio.h>
main()
{
typedef int a;
a b=2,c=8,d;
d=(b*2)/2+8;
printf(“%d”,d);
}
Output
d = (2 * 2) / 2 + 8 = 4 / 2 + 8 = 2 + 8 = 10
10

3. What is the typedef function in C? (CO4) (Apr/May 2024)


The typedef is a keyword that is used to provide existing data types with a new name. The C typedef
keyword is used to redefine the name of already existing data types.
Syntax: typedef existing_type new_name;
Program
#include <stdio.h>
typedef int ss;
int main()
{
ss n = 10;
printf("%d", n);
return 0;
}

SRM MCET / CSE / QUESTION BANK 2


CS3451 – PROGRAMMING IN C

4. Differentiate structure and union. (CO4) (Nov/Dec 2023) (Apr/May 2022)

structure Union

A structure is a user-defined data type that A union is a special data type that allows to
can be used to group the different types into store different data types in the same
a single type. memory location

Every member has its own memory. All members use the same memory.

The struct keyword is used to define the The union keyword is used to define the
structure. union.

All members of structure can be initialized Only the first member of union can be
initialized

Syntax Syntax
struct structure_name union union_name
{ {
structure element 1; union element 1;
structure element 2; union element 2;
. .
. .
. .
. .
structure element n; union element n;
}structure_variable_name; } union_variable_name;

5. Illustrate with an example for each, the following operators with regard to pointers and structures.
&,*,.,->(CO4) (Nov/Dec 2023)
* (Dereference Operator) - Access the value pointed to by the pointer.
int x = 10;
int *ptr = &x;
& (Address-of Operator) - Get the memory address of a variable or structure member.
sint *ptr = &x;
-> (Arrow Operator) - Access members of a structure via a pointer to that structure.
ptr->x, ptr->y
. (Dot Operator) - Access members of a structure directly.
struct point p = {5, 6};
printf("x: %d, y: %d\n", p.x, p.y);

SRM MCET / CSE / QUESTION BANK 3


CS3451 – PROGRAMMING IN C

6. What do you mean by self-referential structure? (CO4) (Nov/Dec 2023,2022)


A self-referential structure in C is a structure that contains a pointer to itself. This means that a
structure type has a member which is a pointer to the same type of structure. This is often used for
creating data structures like linked lists, trees, and other types of recursive data structures.
Syntax
struct structure_name
{
// Data members
// Other members
// Pointer to the same structure type
struct structure_name *pointer_name;
};
Example
struct node
{
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1
struct node ob2; // Node2
}

7. In language C can we allocate memory dynamically? How?


(CO4) (Apr/May 2023)
malloc(): Allocates a specified number of bytes of memory. It returns a pointer to the allocated
memory.
ptr = (cast-type*) malloc(byte-size)
calloc(): Allocates memory for an array of elements and initializes all bits to zero.
ptr = (cast-type*)calloc(n, element-size);
realloc(): Resizes previously allocated memory (increased or decreased size).
ptr = realloc(ptr, newSize);
free(): Frees dynamically allocated memory when it's no longer needed.
free(ptr);

SRM MCET / CSE / QUESTION BANK 4


CS3451 – PROGRAMMING IN C

8. What is meant by structure definition? (CO4) (Nov/Dec 2022)


A structure is a user-defined data type that can be used to group the different types into a single type.
The struct keyword is used to define a structure. The items in the structure are called its member.
Syntax
struct structure_name
{
data_type1 member1;
data_type2 member2;

};
Example
struct student
{
char name[50];
int age;
float grade;
};

9. Compare and contrast structure with an array. (CO4) (Apr/May 2023)

Array Structure

Array refers to a collection of similar data Structure refers to a collection of different


type(homogeneous) data type(heterogeneous)
Array declaration is done simply using [] Structure declaration is done with the help
and not any keyword. of “struct” keyword.

Syntax
Syntax
struct structure_name{ data_type1 ele1;
data_type array_name[size];
data_type2 ele2; };

Array elements are accessed by their index Structure elements are accessed by dot
number. operator.

Arrays is a derived datatype Structure is a user-defined datatype.

SRM MCET / CSE / QUESTION BANK 5


CS3451 – PROGRAMMING IN C

10. Write the syntax of pointers to structure (CO4) (Apr/May 2018,2012)


A pointer can be declared in such a way that it points to a structure data type.
A pointer to a structure is created as follows
Syntax
struct structure_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
……………………………….
}*ptr;
Example
struct student
{
int rno;
char name[23];
float avg;
}*str;

11.Define the structure called ID_card to hold the details of the student.
(CO4) (Apr/May 2016)
struct ID_card
{
char Reg_no[20];
char name[50];
int Grade;
char mobile[15];
char address[50];
int age;
}b1;
Accessing structure elements
b1.Reg_no[i]
b1.name[i]
b1. Grade[i]
b1. Mobile[i]
b1.address[i]
b1.age[i]

SRM MCET / CSE / QUESTION BANK 6


CS3451 – PROGRAMMING IN C

12. Define dynamic memory allocation functions and its types.


The process of allocating memory during program execution is called dynamic memory allocation.
There are 4 types of dynamic memory function are as follows
 malloc()
 calloc()
 realloc()
 free()

13. What is the output of the following code fragment? (CO4) (Apr/May 2019)
struct point
{
int x;
int y;
};struct point origin,*pp;
main()
{
pp=&origin;
printf(“origin is(%d%d)\n”,(*pp).x,pp->y);
}
Output
Origin is (0,0)

14. How to create node in linked list? (CO4) (Apr/May 2018,2008)


malloc() function is used to allocate space in memory during the execution of the program. The node in
a linked list is created using malloc().
Syntax
newnode=malloc(size of (node));

15. Define singly Linked List. (CO4) (Apr/May 2010)


It is a linear data structure and type of list. In singly linked list, each node in the list store the content of
the node and a pointer or reference to the next node in the list.

Figure 4.1 Structure of singly linked list

SRM MCET / CSE / QUESTION BANK 7


CS3451 – PROGRAMMING IN C

Example
struct node
{
int data;
struct node *next;
}

16. Define calloc function.


calloc() is a function that assigns a specified number of blocks of memory to a single variable. calloc()
is used to indicate contiguous memory allocation. calloc() is slower than malloc().
Syntax
ptr = (castType*)calloc(n, size);

17. Define realloc with its syntax


realloc() function modifies the allocated memory size by malloc() and calloc() function to new size.If
enough space doesn’t exist in memory of current block to extend,new block is allocated for full size
reallocation,then copies the existing data to new block and then frees the old block.
Syntax
realloc(pointer_name,number *sizeof(int));

18. Define free() funtion in C.


It is one of the dynamic memory allocation.The memory occupied by malloc() or calloc() functions
must be released by calling free function.otherwise it consume memory until program exit.
Syntax
free(pointer_name);

19. Write array of structures with an example.(CO4) (Nov/Dec 2022)


In an array of structures ,each element of an array is of the structure type. Create the structure variable
as an array to handle more records within one structure,That kind of declaration is called array of structure.
Syntax: struct structure_name struct_variable[index];
Example
struct student
{
int r_no;
char name[20];
char course[20];

SRM MCET / CSE / QUESTION BANK 8


CS3451 – PROGRAMMING IN C

float fees;
};
struct student s[30];

20. Write the C program to read and print the student details.
#include <stdio.h>
struct Student
{
char name[50];
int roll_no;
};
int main()
{
struct Student s;
// Input student details
printf("Enter student name: ");
scanf("%s", s.name);
printf("Enter roll number: ");
scanf("%d", &s.roll_no);
// Output student details
printf("\nStudent Details:\n");
printf("Name: %s\n", s.name);
printf("Roll Number: %d\n", s.roll_no);
return 0;
}

SRM MCET / CSE / QUESTION BANK 9


CS3451 – PROGRAMMING IN C

Part-B
1. Discuss the concepts,advantages of self-referential structure and explain with an example program.
(CO4) (Apr/May 2024)
Self Referential Structure
Structures pointing to the same type of structures. A self-referential structure in C is a structure that
contains a pointer to itself. This means that a structure type has a member which is a pointer to the same type
of structure. This is often used for creating data structures like linked lists, trees, and other types of recursive
data structures.
Syntax
struct node{
int data1;
char data2;
struct node* link;
};
Program
#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1
// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2; // Node2
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
// Linking ob1 and ob2
ob1.link = &ob2;
// Accessing data members of ob2 using ob1
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);

SRM MCET / CSE / QUESTION BANK 10


CS3451 – PROGRAMMING IN C

return 0;
}
Output
30
40
Advantages
 Dynamic memory Allocation
 Efficient insertion and Deletion
 Easy to extend
 Flexible data representation
 Recursive data modeling

2. Give an example for nested structure. (CO4) (Nov/Dec 2023)


Nested structure
A structure that contains another structure as its member is called a nested structure.
Syntax
struct name_1
{
member 1;
member 2;
.
.
member n;
};
struct name_2
{
member_1;
member_2;
.
.
member_n;
};
struct structure_name variable_name;
Accessing in Nested structure
Accessing the member of nested structure by the following syntax
outer_structure_variable_name.inner_structure variable_name.member
Program
#include <stdio.h>
#include <conio.h>
int main()
{
struct DOB

SRM MCET / CSE / QUESTION BANK 11


CS3451 – PROGRAMMING IN C

{
int day;
int month;
int year;
};
struct student
{
int roll_no;
char name [100];
float fees;
struct DOB date;
};
struct student stud1;
clrscr();
printf("\n Enter the roll number: ");
scanf("%d", &stud1.roll_no);
printf("\n Enter the name: ");
scanf("%s", stud1.name);
printf("\n Enter the fees: ");
scanf("%f", &stud1.fees);
printf("\n Enter the DOB: ");
scanf("%d %d %d", &stud1.date.day, &stud1.date.month, &stud1.date. year);
printf("\n *** STUDENT'S DETAILS ***");
printf("\n ROLL No. = %d", stud1.roll_no);
printf("\n NAME %%s", stud1.name);
printf("\n FEES = %f", stud1. fees);
printf("\n DOB %d %d %d", stud1. date.day, stud1.date.month, stud1.date. year);
getch();
return 0;
}
Output
Enter the roll number: 01
Enter the name: Rahul
Enter the fees: 45000
Enter the DOB: 25 09 1991

SRM MCET / CSE / QUESTION BANK 12


CS3451 – PROGRAMMING IN C

********STUDENT'S DETAILS ****


ROLL NO. = 01
NAME = Rahul
FEES = 45000.00
DOB = 25-09-1991
Advantages of Nested Structures
 It reduces repetition in programs redundancy
 Improves modularity and readability
 It is used to represent complex data structure

3. List the operations on Linked List. Explain insertion at end deletion at beginning of a singly linked
list. (CO4) (Nov/Dec 2023)
Singly linked list
It is a linear data structure.It is a type of list.In singly linked list,each node in the list store the content
of the node and a pointer or reference to the next node in the list.The node stores the address of the next node
in sequence.A singly linked list allows traversal of data only in one direction.
The following diagram represents the structure of a singly linked list:

Figure 4.2 Structure of singly linked list


Travelling a singly Linked List
 It means accessing the nodes of the list in order to perform some operations on them.
 It contains the pointer variable START which stores the address of the first node of the list.
 The end of the list is marked by storing NULL or -1.
Syntax
struct node
{
int data;
node* next;
};
where,
data: indicates the value stored in the node.
next: is a pointer that will store the address of the next node in the sequence.

SRM MCET / CSE / QUESTION BANK 13


CS3451 – PROGRAMMING IN C

Insert at end of the list


Insertion
 Create a new node with the given value.
 Set the next pointer of the new node to the current head.
 Move the head to point to the new node.
 Return the new head of the linked list.
Before Insertion

Figure 4.3 Insertion Before singly linked list


After Insertion

Figure 4.4 Insertion after singly linked list


Insert at End
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = value;
newNode->next = NULL;
struct node *temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
Deletion at start beginning of the list
Before deletion

Figure 4.5 Deletion Before singly linked list


After deletion

Figure 4.6 Deletion After singly linked list


head = head->next;

SRM MCET / CSE / QUESTION BANK 14


CS3451 – PROGRAMMING IN C

4. Consider a structure ‘furniture’ that includes the information about furniture in shop. write a
function call statement that has the argument as a pointer to the structure and number of furniture.
Also provide the corresponding function definition statement that receives the arguments.
(CO4) (Nov/Dec 2023)
(i) Write the function body that prints the details of ‘n’ furniture
(ii) Use ‘typedef’ to define ‘furniture’ as array of structures
Program
#include <stdio.h>
typedef struct
{
char name[50];
float price;
int quantity;
} Furniture;
void displayFurniture(Furniture *f, int n);
int main()
{
int n, i;
printf("Enter the number of furniture items: ");
scanf("%d", &n);
Furniture items[n];
for (i = 0; i < n; i++)
{
printf("\nEnter details of furniture %d:\n", i + 1);
printf("Name: ");
scanf(" %s", items[i].name); // Reads a line of input
printf("Price: ");
scanf("%f", &items[i].price);
printf("Quantity: ");
scanf("%d", &items[i].quantity);
}
displayFurniture(items, n);
return 0;
}
void displayFurniture(Furniture *f, int n)
{
printf("\nFurniture Details:\n");
for (int i = 0; i < n; i++)

SRM MCET / CSE / QUESTION BANK 15


CS3451 – PROGRAMMING IN C

{
printf("\nFurniture %d:\n", i + 1);
printf("Name: %s\n", f[i].name);
printf("Price: %.2f\n", f[i].price);
printf("Quantity: %d\n", f[i].quantity);
}
}
Output
Enter the number of furniture items: 2

Enter details of furniture 1:


Name: Chair
Price: 49.99
Quantity: 10

Enter details of furniture 2:


Name: Table
Price: 120.50
Quantity: 5

Furniture Details:

Furniture 1:
Name: Chair
Price: 49.99
Quantity: 10

Furniture 2:
Name: Table
Price: 120.50
Quantity: 5

SRM MCET / CSE / QUESTION BANK 16


CS3451 – PROGRAMMING IN C

5.Difference between structure and union with example. (CO4) (Apr/May 2023)
Parameter Structure Union
Definition A structure is a user-defined A union is a user-defined
data type that groups data type that allows storing
different data types into a different data types at the
single entity. same memory location.
Keyword The keyword struct is used The keyword union is used
to define a structure to define a union
Size The size is the sum of the The size is equal to the size
sizes of all members, with of the largest member, with
padding if necessary. possible padding.
Memory Allocation Each member within a Memory allocated is shared
structure is allocated unique by individual members of
storage area of location. union.
Accessing Members Individual member can be Only one member can be
accessed at a time accessed at a time.
Syntax struct name { union name {
member1 definition; member1 definition;
member2 definition; member2 definition;
… …
memberN definition; memberN definition;
}; };

Program
#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d bytes", sizeof(uJob));

SRM MCET / CSE / QUESTION BANK 17


CS3451 – PROGRAMMING IN C

printf("\nsize of structure = %d bytes", sizeof(sJob));


return 0;
}
Output
size of union = 32
size of structure = 40

6. Distinguish between calloc() and malloc() functions. (CO4) (Nov/Dec 2023)


S.No. malloc() calloc()

malloc() is a function that creates one calloc() is a function that assigns a specified number
1. block of memory of a fixed size. of blocks of memory to a single variable.

2. malloc() only takes one argument calloc() takes two arguments.

3. malloc() is faster than calloc. calloc() is slower than malloc()

malloc() is used to indicate memory calloc() is used to indicate contiguous memory


4. allocation allocation

6. Syntax : void* malloc(size_t size); Syntax : void* calloc(size_t num, size_t size);

malloc() does not initialize the memory to


calloc() initializes the memory to zero
7. zero

Example program for malloc(),calloc()


#include <stdio.h>
#include <stdlib.h>
int main()
{
int n = 5; // Number of elements
// Using malloc()
int *arr1 = (int *)malloc(n * sizeof(int));
if (arr1 == NULL)
{
printf("Memory allocation failed for malloc\n");
return 1;
}
// Initialize manually

SRM MCET / CSE / QUESTION BANK 18


CS3451 – PROGRAMMING IN C

for (int i = 0; i < n; i++)


{
arr1[i] = i + 1;
}
// Using calloc()
int *arr2 = (int *)calloc(n, sizeof(int));
if (arr2 == NULL)
{
printf("Memory allocation failed for calloc\n");
free(arr1);
return 1;
}
// Print values
printf("Using malloc (uninitialized memory before manual initialization):\n");
for (int i = 0; i < n; i++)
{
printf("%d ", arr1[i]); // Should print assigned values
}
printf("\n");
printf("Using calloc (automatically initialized to zero):\n");
for (int i = 0; i < n; i++)
{
printf("%d ", arr2[i]); // Should print all zeros
}
printf("\n");
// Free allocated memory
free(arr1);
free(arr2);
return 0;
}
Output
Using malloc (uninitialized memory before manual initialization):
12345
Using calloc (automatically initialized to zero):
00000

SRM MCET / CSE / QUESTION BANK 19


CS3451 – PROGRAMMING IN C

7. Write a C program to create mark sheet for students using self-referential structure.
(CO4) (Nov/Dec 2022)
Program
#include <stdio.h>
struct Student
{
char name[50];
int rollNo;
float marks[5]; // Marks for 5 subjects
float totalMarks;
float percentage;
struct Student *next;
};
int main()
{
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
struct Student students[n];
for (int i = 0; i < n; i++)
{
struct Student *current = &students[i];
current->next = NULL; // Initialize next pointer to NULL
printf("\nEnter student %d name: ", i + 1);
scanf(" %[^\n]s", current->name);
printf("Enter roll number: ");
scanf("%d", &current->rollNo);
printf("Enter marks for 5 subjects:\n");
current->totalMarks = 0; // Initialize total marks to 0
for (int j = 0; j < 5; j++)
{
printf("Subject %d: ", j + 1);
scanf("%f", &current->marks[j]);
current->totalMarks += current->marks[j];
}
current->percentage = (current->totalMarks / 500) * 100;
}
printf("\n---- Student Mark Sheet ----\n");
for (int i = 0; i < n; i++)
{
struct Student *current = &students[i];
printf("\nName: %s\n", current->name);
printf("Roll Number: %d\n", current->rollNo);
printf("Marks: ");
for (int j = 0; j < 5; j++)

SRM MCET / CSE / QUESTION BANK 20


CS3451 – PROGRAMMING IN C

{
printf("%f ", current->marks[j]);
}
printf("\nTotal Marks: %f\n", current->totalMarks);
printf("Percentage: %f\n", current->percentage);
}

return 0;
}
Output
Enter the number of students: 2

Enter student 1 name: John Doe


Enter roll number: 101
Enter marks for 5 subjects:
Subject 1: 85
Subject 2: 90
Subject 3: 78
Subject 4: 92
Subject 5: 88

Enter student 2 name: Alice Smith


Enter roll number: 102
Enter marks for 5 subjects:
Subject 1: 75
Subject 2: 88
Subject 3: 91
Subject 4: 84
Subject 5: 90

---- Student Mark Sheet ----

Name: John Doe


Roll Number: 101
Marks: 85.00 90.00 78.00 92.00 88.00
Total Marks: 433.00
Percentage: 86.60%

Name: Alice Smith


Roll Number: 102
Marks: 75.00 88.00 91.00 84.00 90.00
Total Marks: 428.00
Percentage: 85.60%

SRM MCET / CSE / QUESTION BANK 21


CS3451 – PROGRAMMING IN C

8. Write a C program using structures to prepare employee pay roll of a company. The number of
records is created based on the user input. (CO4) (Nov/Dec 2019)
Program
#include<stdio.h>
#include<conio.h>
struct emp
{
int empno ;
char name[10] ;
int bpay, allow, ded, npay ;
} e[10] ;
void main()
{
int i, n ;
printf("Enter the number of employees : ") ;
scanf("%d", &n) ;
for(i = 0 ; i < n ; i++)
{
printf("\nEnter the employee number : ") ;
scanf("%d", &e[i].empno) ;
printf("\nEnter the name : ") ;
scanf("%s", e[i].name) ;
printf("\nEnter the basic pay, allowances & deductions : ") ;
scanf("%d %d %d", &e[i].bpay, &e[i].allow, &e[i].ded) ;
e[i].npay = e[i].bpay + e[i].allow - e[i].ded ;
}
printf("\nEmp. No. Name \t Bpay \t Allow \t Ded \t Npay \n\n") ;
for(i = 0 ; i < n ; i++)
{
printf("%d \t %s \t %d \t %d \t %d \t %d \n", e[i].empno,e[i].name, e[i].bpay, e[i].allow, e[i].ded,
e[i].npay) ;
}
getch() ;
}

SRM MCET / CSE / QUESTION BANK 22


CS3451 – PROGRAMMING IN C

Output
Enter the number of employees: 2
Enter the employee number: 101
Enter the name: Alice
Enter the basic pay, allowances & deductions: 5000 2000 500
Enter the employee number: 102
Enter the name: Bob
Enter the basic pay, allowances & deductions: 6000 1500 700

Emp. No. Name Bpay Allow Ded Npay

101 Alice 5000 2000 500 6500


102 Bob 6000 1500 700 6800

9. Define a structure called book with book name, author name and price. Write a C program to read
the details of book name, author name and price of 200 books in a library and display the total cost of
the books and book details whose price is above Rs.500.(CO4) (Apr/May 2018)
Program
#include <stdio.h>
#define MAX_BOOKS 200
// Define the structure for book
struct book
{
char book_name[100];
char author_name[100];
float price;
};
int main()
{
struct book books[MAX_BOOKS];
float total_cost = 0;
int i;
// Input details for 200 books
for(i = 0; i < MAX_BOOKS; i++)
{
printf("Enter details for book %d:\n", i + 1);

SRM MCET / CSE / QUESTION BANK 23


CS3451 – PROGRAMMING IN C

printf("Enter book name: ");


scanf(“%s”,&books[i].book_name);
printf("Enter author name: ");
scanf(“%s”,&books[i].book_name);
printf("Enter price: ");
scanf("%f", &books[i].price);
// Display the details of books whose price is above Rs.500
printf("\nBooks with price above Rs.500:\n");
if(books[i].price > 500)
{
printf("Book Name: %s", books[i].book_name);
printf("Author Name: %s", books[i].author_name);
printf("Price: Rs. %.2f\n\n", books[i].price);
total_cost = total_cost+book[i].price;
}
}
printf(“the total cost is %f”, total_cost[i]);
}
}
return 0;
}
Output
Enter details for book 1:
Enter book name: Book One
Enter author name: Author A
Enter price: 250

Enter details for book 2:


Enter book name: Book Two
Enter author name: Author B
Enter price: 600

Enter details for book 3:


Enter book name: Book Three
Enter author name: Author C
Enter price: 700

SRM MCET / CSE / QUESTION BANK 24


CS3451 – PROGRAMMING IN C

Books with price above Rs.500:


Book Name: Book Two
Author Name: Author B
Price: Rs. 600.00

Book Name: Book Three


Author Name: Author C
Price: Rs. 700.00
The total cost is 1300

10. Explain about pointers and structure with an example program. (CO4)(Apr/May 2012)

Structure can be created and accessed using pointers. When we have a pointer of structure type we use
to access the structure member.
Syntax
struct structure_name
{
data member;
};
struct structure_name *ptr;

Create one structure variable to assign the address.


struct structure_name s;
ptr=&s;
The data members can accessed by using pointing - to - operator .
Program by using array of array pointer to a structure, to read and display the data of student.
#include <stdio.h>
#include <stdlib.h>
struct student
{
int rollno;
char name[20];
char dept[10];
};
struct student *ptr[10];
int main()
{

SRM MCET / CSE / QUESTION BANK 25


CS3451 – PROGRAMMING IN C

int i,n;
printf("Enter the number of students: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
ptr[i] = (struct student *)malloc(sizeof(struct student));
printf("\nEnter data for student %d:\n", i + 1);
printf("Enter roll number: ");
scanf("%d", &ptr[i]->rollno);
printf("Enter name: ");
scanf("%s", ptr[i]->name);
printf("Enter department: ");
scanf("%s", ptr[i]->dept);
}
// Display student details
printf("\nDetails of students:\n");
for (i = 0; i < n; i++)
{
printf("Student %d:\n", i + 1);
printf("Roll Number: %d\n", ptr[i]->rollno);
printf("Name: %s\n", ptr[i]->name);
printf("Department: %s\n", ptr[i]->dept);
}
return 0;
}
Output:
Enter the number of students: 2
Enter data for student 1:
Enter roll number: 101
Enter name: Alice
Enter department: CS
Enter data for student 2:
Enter roll number: 102
Enter name: Bob
Enter department: IT
Details of students:

SRM MCET / CSE / QUESTION BANK 26


CS3451 – PROGRAMMING IN C

Student 1:
Roll Number: 101
Name: Alice
Department: CS
Student 2:
Roll Number: 102
Name: Bob
Department: IT

SRM MCET / CSE / QUESTION BANK 27

You might also like