Aiml Ds Lab Manual_2024 25
Aiml Ds Lab Manual_2024 25
(BCSL305)
(As per Visvesvaraya Technological University Course type- PCCL)
Compiled by
Name:
USN:
BSCL305:Data Structure Lab
Disclaimer
The information contained in this document is the proprietary and exclusive property of
RNS Institute except as otherwise indicated. No part of this document, in whole or in
part, may be reproduced, stored, transmitted, or used for course material development
purposes without the prior written permission of RNS Institute of Technology.
The information contained in this document is subject to change without notice. The
information in this document is provided for informational purposes only.
Trademark
Edition: 2024- 25
Document Owner
The primary contact for questions regarding this document is:
1. Prof. Shruthi U
Author(s):
2. Prof. Rashmi B C
3.
Department: CSE (AI & ML)
Contact email ids : [email protected]
[email protected]
COURSE OUTCOMES
Course Outcomes: At the end of this course, students are able to:
CO1- Analyze various linear and non-linear data structures
CO2- Demonstrate the working nature of different types of data structures and their applications
CO3- Use appropriate searching and sorting algorithms for the given scenarios
CO4- Apply the appropriate data structure for solving real-world problems
COURSE
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3 PSO4
OUTCOMES
CO1 3 3 3 3 3 2 2 2 2
CO2 3 3 3 3 3 2 2 2 2
CO3 3 3 3 3 3 2 2 2 2
CO4 3 3 3 3 3 2 2 2 2
7 Lab Test 1
14 Lab Test 2
Program 1:
Source code:
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
# define DAYS 3
struct activity
{
char *nday; int dday; char *desc;
};
typedef struct activity Plan; Plan* create();
void read(Plan *);
void display(Plan *);
int main()
{
Plan *cal = NULL; cal = create( );
read(cal);
display(cal);
}
Plan* create()
{
Plan *t = (Plan *) malloc(sizeof(Plan)*7);
if (t == NULL)
{
printf("Sufficient memory not allocated\n"); return 0;
}
return t;
}
int i;
for(i=0;i<DAYS;i++)
{
p[i].nday = (char *) malloc(9);
printf("Enter name of the day ");
scanf(" %s",p[i].nday);
printf("Enter date of the day ");
scanf("%d",&(p[i].dday));
printf("Enter description of the activity ");
p[i].desc = (char *) malloc(400);
scanf(" %[^\n]",p[i].desc);
p[i].desc = (char *) realloc(p[i].desc,strlen(p[i].desc)+1);
}
}
Sample Output:
Program 2:
©Department of CSE(AI&ML), RNSIT, Bengaluru.
BSCL305:Data Structure Lab
strLen = stringLength(str);
index = patternExists(str, pattern);
}
if (index == -1) {
printf("Pattern not found in the main string.\n");
}
}
int main() {
char mainString[100], pattern[50], replace[50];
Program 3:
AIM: Develop a menu driven Program in C for the following operations on STACK of Integers (Array
Implementation of Stack with maximum size MAX)
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate how Stack can be used to check Palindrome
d. Demonstrate Overflow and Underflow situations on Stack
e. Display the status of Stack f. Exit Support the program with appropriate functions for each of the above
operations
Source Code:
#include <stdio.h>
#include <stdbool.h>
#define MAX 100
// Define a stack data structure
struct Stack {
int data[MAX];
int top;
};
// Function to initialize the stack
void initialize(struct Stack *stack) {
stack->top = -1;
}
// Function to push an element onto the stack
void push(struct Stack *stack, int value) {
if (stack->top == MAX - 1) {
printf("Stack Overflow: Cannot push element onto a full stack.\n");
} else {
stack->data[++stack->top] = value;
printf("Pushed %d onto the stack.\n", value);
}
}
{
struct Stack stack;
initialize(&stack);
int i = 0;
while (str[i] != '\0') {
push(&stack, str[i]);
i++;
}
i = 0;
while (str[i] != '\0') {
if (str[i] != pop(&stack)) {
return false;
}
i++;
}
return true;
}
int main() {
struct Stack stack;
initialize(&stack);
while (1) {
printf("\nStack Operations Menu:\n");
printf("1. Push Element\n");
printf("2. Pop Element\n");
printf("3. Check Palindrome\n");
switch (choice) {
case 1:
printf("Enter an element to push onto the stack: ");
scanf("%d", &element);
push(&stack, element);
break;
case 2:
element = pop(&stack);
if (element != -1) {
printf("Popped %d from the stack.\n", element);
}
break;
case 3:
printf("Enter a string to check if it's a palindrome: ");
scanf(" %[^\n]", str);
if (isPalindrome(str)) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
break;
case 4:
displayStack(&stack);
break;
case 5:
return 0;
default:
printf("Invalid choice. Please select a valid option.\n");
}
}
return 0;
}
Sample Output:
Program 4:
AIM: Develop a Program in C for converting an Infix Expression to Postfix Expression. Program should
support for both parenthesized and free parenthesized expressions with the operators: +, -, *, /, %
(Remainder), ^ (Power) and alphanumeric operands.
Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int i, j;
i = j = 0;
if (isalnum(current)) {
postfix[j++] = current;
} else if (current == '(') {
push(&stack, current);
} else if (current == ')') {
while (!isEmpty(&stack) && stack.items[stack.top] != '(') {
postfix[j++] = pop(&stack);
}
if (!isEmpty(&stack) && stack.items[stack.top] == '(') {
pop(&stack); // Pop the opening parenthesis
}
} else if (isOperator(current)) {
while (!isEmpty(&stack) && getPrecedence(current) <=
getPrecedence(stack.items[stack.top])) {
postfix[j++] = pop(&stack);
}
push(&stack, current);
}
i++;
while (!isEmpty(&stack)) {
postfix[j++] = pop(&stack);
}
postfix[j] = '\0';
}
int main() {
char infix[100];
char postfix[100];
infixToPostfix(infix, postfix);
return 0;
}
Sample Output:
Program 5 :
Develop a Program in C for the following Stack Applications
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^
b. Solving Tower of Hanoi problem with n disk.
Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
if (isdigit(current)) {
push(&stack, current - '0');
} else {
int operand2 = pop(&stack);
int operand1 = pop(&stack);
int result;
switch (current) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
case '%':
result = operand1 % operand2;
break;
case '^':
result = 1;
for (int j = 0; j < operand2; j++) {
result *= operand1;
}
break;
default:
printf("Invalid operator in expression.\n");
exit(1);
}
push(&stack, result);
}
}
if (stack.top == 0) {
return stack.items[0];
}
else {
printf("Invalid expression.\n");
exit(1);
}
}
int main() {
char expression[100];
return 0;
}
Sample Output:
# include <stdio.h>
void hanoi (int n, char S, char T, char D)
{
if (n==0) return;
hanoi(n-1, S, D, T);
printf("Move disc %d from %c to %c\n", n, S, D);
hanoi(n-1, T, S, D);
}
int main( )
{
int n;
printf("Enter number of discs\n");
scanf("%d",&n);
hanoi(n , 'A', 'B', 'C');
}
Sample Output:
Program 6:
AIM: Develop a menu driven Program in C for the following operations on Circular QUEUE of Characters
(Array Implementation of Queue with maximum size MAX)
a. Insert an Element on to Circular QUEUE
b. Delete an Element from Circular QUEUE
c. Demonstrate Overflow and Underflow situations on Circular QUEUE
d. Display the status of Circular QUEUE
e. Exit
Support the program with appropriate functions for each of the above operations
Source Code:
#include <stdio.h>
#include <stdlib.h>
#define Max 3
void insert(char [], int *, int *);
void del(char [], int *, int *);
void display(char [], int, int);
int main()
{
char q[Max];
int r=-1,f=0,cnt=0; int ch;
while(1)
{
printf("1: Insert\n2: Delete\n3: Display\n4: Exit\n");
printf("Enter choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert(q,&r,&cnt);
break;
case 2: del(q,&f,&cnt);
break;
case 3: display(q,f,cnt);
break;
case 4: exit(0)
default: printf(“Invalid Choice\n”);
}
}
}
Sample Output:
Program 7:
AIM: Develop a menu driven Program in C for the following operations on Singly Linked List (SLL) of
Student Data with the fields: USN, Name, Programme, Sem, PhNo
a. Create a SLL of N Students Data by using front insertion.
b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL(Demonstration of stack)
e. Exit
Source Code:
#include<stdio.h> #include<stdlib.h> typedef struct node
{
char USN[10], name[20], branch[10]; int sem;
long int ph; struct node *link;
}nd;
int main()
{
nd * first = NULL; int ch;
for(;;)
{
printf("1. Create N students\n2. Status of SLL\n");
printf("3. Insert front\n4. Insert rear\n5. Delete front\n");
printf("6. Delete rear\n7. Display\n8. Exit\n");
scanf("%d", &ch);
©Department of CSE(AI&ML), RNSIT, Bengaluru.
BSCL305:Data Structure Lab
switch(ch)
{
case 1: first = create(first);
break;
case 2: status(first);
break;
case 4: first = ins_rear(first); break; case 5: first = del_front(first); break; case 6: first = del_rear(first);
break; case 7: display(first); break;
case 8: exit(0);
}
}
}
nd * del_front(nd *f)
{
nd *t;
if (f==NULL)
{
printf("SLL is empty\n"); return NULL;
}
printf("Information to be deleted is...\n");
printf("%s\t%s\t%s\t%d\t%ld\n",(f->USN),(f->name),(f->branch),(f->sem),(f->ph));
if (p!=NULL)
{ p->link=NULL; return f; } else
return NULL;
}
nd * ins_rear(nd * f)
{
nd *p=f;
nd *t=(nd*)malloc(sizeof(nd)); t->link=NULL;
printf("Enter USN, Name, Branch, Sem and Phone of the student:\n"); scanf("%s%s%s%d%ld",(t-
>USN),(t->name),(t->branch), &(t->sem), &(t->ph));
if (f==NULL) return t;
Sample Output:
Program 8:
AIM: Develop a menu driven Program in C for the following operations on Doubly Linked List (DLL) of
Employee Data with the fields: SSN, Name, Dept, Designation, Sal, PhNo
a. Create a DLL of N Employees Data by using end insertion.
b. Display the status of DLL and count the number of nodes in it
c. Perform Insertion and Deletion at End of DLL
d. Perform Insertion and Deletion at Front of DLL
e. Demonstrate how this DLL can be used as Double Ended Queue. f. Exit
Source code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
printf("Salary: ");
scanf("%f", &newEmployee->Sal);
printf("Phone Number: ");
scanf(" %[^\n]", newEmployee->PhNo);
newEmployee->prev = NULL;
newEmployee->next = NULL;
return newEmployee;
}
// Function to display the status of the DLL and count the number of nodes
void displayDLL(struct Employee *head) {
struct Employee *current = head;
int count = 0;
if (current == NULL) {
printf("Doubly Linked List is empty.\n");
} else {
printf("Doubly Linked List Contents:\n");
while (current != NULL) {
displayEmployee(current);
current = current->next;
count++;
}
printf("Total number of nodes: %d\n", count);
}
}
if (head == NULL) {
head = newEmployee;
} else {
struct Employee *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newEmployee;
newEmployee->prev = current;
}
printf("Employee added to the end of the list.\n");
return head;
}
return head;
}
int main() {
struct Employee *head = NULL;
int choice, N;
while (1) {
printf(“\nDoubly Linked List Operations Menu:\n”);
printf(“1. Create DLL of N Employees Data by End Insertion\n”);
printf(“2. Display DLL and Count Nodes\n”);
printf(“3. Insert Employee at End\n”);
printf(“4. Delete Employee from Front\n”);
printf(“5. Demonstrate DLL as Double-Ended Queue\n”);
printf(“6. Exit\n”);
printf(“Enter your choice: “);
scanf(“%d”, &choice);
switch (choice) {
case 1:
printf(“Enter the number of employees (N): “);
scanf(“%d”, &N);
head = createDLL(head, N);
break;
case 2:
displayDLL(head);
break;
case 3:
head = insertEnd(head);
break;
case 4:
head = deleteFront(head);
break;
case 5:
printf(“Demonstrating DLL as a Double-Ended Queue:\n”);
printf(“1. Enqueue at Front\n”);
printf(“2. Dequeue at End\n”);
printf(“3. Exit\n”);
break;
default:
printf(“Invalid choice. Please select a valid option.\n”);
}
break;
case 6:
exit(0);
default:
printf(“Invalid choice. Please select a valid option.\n”);
}
}
return 0;
}
Sample Output:
Program 9:
AIM: Develop a Program in C for the following operationson Singly Circular Linked List (SCLL) with
header nodes
a. Represent and Evaluate a Polynomial P(x,y,z) = 6x 2 y 2 z-4yz 5 +3x 3 yz+2xy 5 z-2xyz 3
b. Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and store the result in
POLYSUM(x,y,z) Support the program with appropriate functions for each of the above operations
Source Code:
# include <stdio.h>
# include <stdlib.h>
# include <math.h>
struct term
{
int coef, xexp, yexp, zexp;
struct term *link;
};
typedef struct term tm;
void create(tm *);
void display(tm *);
void evaluate(tm *);
void add( tm *, tm *, tm *);
int main()
{
tm p1={.link=&p1},p2={.link=&p2},p3={.link=&p3};
int ch;
while(1)
{
printf("1. Evaluate\n2. Polynomial addition\n3. Exit\n");
printf("Choice: "); scanf("%d",&ch);
switch(ch)
{
case 1: if (p1.link != &p1) p1.link = &p1;
create(&p1);
printf("Terms in polynomial are...\n");
display(&p1);
evaluate(&p1);
break;
case 2: if (p1.link != &p1) p1.link = &p1;
if (p2.link != &p2) p2.link = &p2;
if (p3.link != &p3) p3.link = &p3;
create(&p1); create(&p2);
printf("Terms in poly1 are...\n");
display(&p1);
printf("Terms in poly2 are...\n");
display(&p2);
add(&p1,&p2,&p3);
printf("Resultant polynomial...\n"); display(&p3); break;
case 3: return 0;
}
}
}
{
case 0: attach(0,tp,r);
tp = tp->link; delete(p,tp); break;
case 1: val = tp->coef + tq->coef;
attach(val,tp,r); delete(p,tp);
delete(q,tq);
tp = tp->link;
tq = tq->link; break;
}
}
{
attach(0,tq,r); tq = tq ->link;
}
}
void evaluate(tm *p)
{
int x,y,z,res=0; tm *t;
printf("Enter value of x,y and z\n");
scanf("%d%d%d",&x,&y,&z);
for(t=p->link; t!=p ; t=t->link)
res=res+t->coef*pow(x,t->xexp)*pow(y,t->yexp)*pow(z,t->zexp);
printf("Evaluation of polynomial is %d\n",res);
}
void display(tm *p)
{
tm *t;
if (p->link == p)
{
printf("SCLL is empty\n");
return;
}
for(t=p->link; t!=p ; t=t->link)
printf("(%dx^%dy^%dz^%d) +",t->coef,t->xexp,t->yexp,t->zexp);
printf("\n");
}
scanf("%d%d%d%d",&(t->coef),&(t->xexp),&(t->yexp),&(t->zexp));
t->link = p->link; p->link = t;
}
}
Sample Output:
Program 10:
AIM: Develop a menu driven Program in C for the following operations on Binary Search Tree (BST) of
Integers . a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2 b. Traverse the BST in Inorder,
Preorder and Post Order c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit
Source Code:
#include <stdio.h>
#include <stdlib.h>
return root;
}
if (root->data == key) {
return 1; // Key found
}
int main() {
while (1) {
printf("\nBinary Search Tree (BST) Operations Menu:\n");
printf("1. Inorder Traversal\n");
printf("2. Preorder Traversal\n");
printf("3. Postorder Traversal\n");
printf("4. Search for a Key\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Inorder Traversal: ");
inorderTraversal(root);
printf("\n");
break;
case 2:
printf("Preorder Traversal: ");
preorderTraversal(root);
printf("\n");
break;
case 3:
printf("Postorder Traversal: ");
postorderTraversal(root);
printf("\n");
break;
case 4:
printf("Enter the key to search: ");
scanf("%d", &key);
if (searchBST(root, key)) {
printf("Key found in the BST.\n");
} else {
printf("Key not found in the BST.\n");
}
break;
case 5:
return 0;
default:
printf("Invalid choice. Please select a valid option.\n");
}
}
return 0;
}
Sample Output:
Program 11:
AIM: Develop a Program in C for the following operations on Graph(G) of Cities
a. Create a Graph of N cities using Adjacency Matrix.
b. Print all the nodes reachable from a given starting node in a digraph using DFS/BFS method
Source Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_CITIES 20
return graph;
}
// Function to print all nodes reachable from a given starting node using DFS
void printDFS(struct Graph graph, int start) {
int visited[MAX_CITIES] = {0};
printf("Nodes reachable from City %d using DFS:\n", start + 1);
DFS(graph, start, visited);
}
visited[start] = 1;
queue[++rear] = start;
// Function to print all nodes reachable from a given starting node using BFS
void printBFS(struct Graph graph, int start) {
int visited[MAX_CITIES] = {0};
printf("Nodes reachable from City %d using BFS:\n", start + 1);
int main() {
int N, startCity;
scanf("%d", &N);
return 0;
}
Sample Output:
Program 12:
AIM: Given a File of N employee records with a set K of Keys (4-digit) which uniquely
determine the records in file F. Assume that file F is maintained in memory by a Hash Table
(HT) of m memory locations with L as the set of memory addresses (2-digit) of locations in
HT. Let the keys in K and addresses in L are Integers. Develop a Program in C that uses Hash
function H: K →L as H(K)=K mod m (remainder method), and implement hashing technique
to map a given key K to the address space L. Resolve the collision (if any) using linear probing.
Source Code:
#include <stdio.h>
#include <stdlib.h>
// Function to perform linear probing and insert an employee record into the hash
table
void insertEmployee(struct MemoryLocation hashTable[], int m, struct
EmployeeRecord employee) {
int key = employee.key;
int index = key % m; // Initial index using the hash function
hashTable[index].key = key;
hashTable[index].employee = employee;
}
int main() {
int m; // Number of memory locations in the hash table
int n; // Number of employee records
struct EmployeeRecord employeeRecords[MAX_KEYS];
struct MemoryLocation hashTable[MAX_MEMORY_LOCATIONS];
printf("Enter the number of memory locations (m) in the hash table: ");
scanf("%d", &m);
if (m <= 0 || n <= 0) {
printf("Invalid input. Please enter valid values for m and n.\n");
return 1;
}
initializeHashTable(hashTable, m);
printf("Enter the %d employee records (each record includes a 4-digit key):\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &employeeRecords[i].key);
// You can add code to input other fields of the employee record here
insertEmployee(hashTable, m, employeeRecords[i]);
}
displayHashTable(hashTable, m);
return 0;
}
Sample Output:
One example is the Undo feature in software applications. Each action is pushed onto a stack,
and the Undo operation pops the last action to revert the changes.
24. How does a stack help in reversing a string?
By pushing each character of the string onto the stack and then popping them in reverse order,
the string can be effectively reversed.
25. Explain the use of parentheses matching using a stack.
A stack can be used to check if parentheses in an expression are balanced. When an opening
parenthesis is encountered, it is pushed onto the stack. When a closing parenthesis is
encountered, it is checked against the top of the stack.
26. What is the significance of the stack in recursive function calls?
The call stack is used to manage the execution of recursive functions by keeping track of each
function call's local variables and return addresses.
27. How is an expression evaluation carried out using a stack?
In expression evaluation, a stack can be used to store operands and operators. The stack helps
in maintaining the order of operations and ensures proper evaluation.
28. Explain the concept of a stack frame.
A stack frame is a block of memory on the call stack that stores local variables, function
parameters, and the return address for a specific function call.
29. Can a stack be implemented using queues? How?
Yes, a stack can be implemented using two queues. Push operation is simulated by enqueueing
elements into one queue, and pop operation is simulated by dequeuing elements from the other
queue.
30. What is the role of the stack in managing recursive algorithms?
The stack is crucial in managing recursive algorithms as it keeps track of the function calls and
their associated local variables, allowing for proper execution and backtracking.
31. What is a queue?
A queue is a linear data structure that follows the First In, First Out (FIFO) principle, where the
first element added is the first one to be removed.
32. Explain the main operations of a queue.
The main operations are:
Enqueue: Adds an element to the rear (end) of the queue.
Dequeue: Removes the element from the front (beginning) of the queue.
Peek (or Front): Returns the element at the front of the queue without removing it.
33. How is a queue implemented?
A queue can be implemented using an array or a linked list. In the array implementation, a
fixed-size array is used to store elements, and two pointers (front and rear) keep track of the
queue's boundaries.
34. Differentiate between a queue and a stack.
A queue follows the First In, First Out (FIFO) principle, while a stack follows the Last In, First
Out (LIFO) principle.
35. Explain the concept of circular queues.
In a circular queue, the front and rear pointers wrap around to the beginning of the queue when
they reach the end, forming a circle. This allows for better space utilization.
36. What is the significance of the front and rear pointers in a queue?
The front pointer points to the first element in the queue, and the rear pointer points to the last
element. They help in maintaining the order of elements and perform enqueue and dequeue
operations efficiently.
37. What is a priority queue? How is it different from a regular queue?
A priority queue is a variation of a queue where each element has an associated priority.
Elements with higher priority are dequeued before elements with lower priority.
38.Explain the concept of double-ended queues (deque).
A deque is a queue that allows insertion and deletion at both the front and rear ends. It supports
the operations of both stacks and queues.
38. How can a queue be implemented using two stacks?
Two stacks can be used to implement a queue by using one stack for enqueue operations and
the other for dequeue operations.
39. Explain the concept of a priority queue with a real-world example.
A real-world example of a priority queue is the scheduling of tasks in an operating system,
where tasks with higher priority are scheduled to run before those with lower priority.
40. How can a queue be implemented using a linked list?
In a linked list implementation of a queue, each node contains data and a pointer to the next
node. Enqueue and dequeue operations involve adding and removing nodes, respectively, at the
front and rear of the linked list.
41. What is a linked list?
A linked list is a data structure that consists of a sequence of elements, where each element
points to the next one in the sequence.
42. Explain the advantages of a linked list over an array.
Linked lists can dynamically change in size, require less memory allocation, and support
efficient insertions and deletions compared to arrays.
43. What are the types of linked lists?
Types of linked lists include singly linked lists, doubly linked lists, and circular linked lists.
©Department of CSE(AI&ML), RNSIT, Bengaluru.
BSCL305:Data Structure Lab
Sample Programs:
1. C program to illustrate the use of structures
#include <stdio.h>
// declaring structure with name str1
struct str1 {
int i;
char c;
float f;
char s[30];
};
// declaring structure with name str2
struct str2 {
int ii;
char cc;
float ff;
} var; // variable declaration with structure template
// Driver code
int main()
{
// variable declaration after structure template
// initialization with initializer list and designated
// initializer list
struct str1 var1 = { 1, 'A', 1.00, "RNSIT" },
var2;
struct str2 var3 = { .ff = 5.00, .ii = 5, .cc = 'a' };
}
Output
Struct 1:
i = 1, c = A, f = 1.000000, s = RNSIT
Struct 2:
i = 1, c = A, f = 1.000000, s = RNSIT
Struct 3
i = 5, c = a, f = 5.000000
2. Working of Pointers
#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}
Output:
Address of c: 2686784
Value of c: 22
Address of pointer pc: 2686784
20
36
Sum = 156
4. Example 2: calloc() and free()
// Program to calculate the sum of n numbers entered by the user
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}