0% found this document useful (0 votes)
28 views11 pages

Day-3 - 4 - C Programming Foundations For DSA

Uploaded by

Khushi
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)
28 views11 pages

Day-3 - 4 - C Programming Foundations For DSA

Uploaded by

Khushi
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/ 11

C Programming Foundations for Data Structures and Algorithms

DAY - 3

Structures

 Structure is a collection of variables of different data types under a single name.


The structure definition is only the blueprint for the creating of variables. You can
imagine it as a datatype.
 It is similar to a class in that, both holds a collection of data of different data types.
 The struct keyword defines a structure type followed by an identifier (name of the
structure). Syntax:

struct Person
{
char name[50];
int age;
float salary;
};

 The members of structure variable is accessed using a dot (.) operator.


 Once you declare a structure Person as above. You can define a structure variable
as: Person p1;

Syntax:
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};

Example:
//Another example of Structure
struct card {
int no;
float amount;
};
int main(){

struct card c1; // variable of type structure


c1.no = 141; //assign values to the members of c1.
c1.amount = 1201.3;
//struct card c1 = { .no = 701, .amount = 1000.5 }; //another way of assignment
printf("card no. is %d \n", c1.no);
printf("card limit is %.2f", c1.amount);
}
Explanation: This code demonstrates how structures can be used to group related data together
into a single entity, making it easier to manage and work with such data.

1
Notes Compiled by: Dr. Anand Motwani, Faculty, SCSE, VIT Bhopal University
In this case, you have defined a structure named card with two members: an integer no and a
floating-point amount. You then create an instance of this structure named c1 and assign values
to its members. Finally, you print the values of these members using printf.

//Program to undestand structure concept


struct Person {
char Name[50];
int age;
float sal;
};
//driver code
int main(){
struct Person p1, p2;
// initializing the p1 structure members
printf("Welcome, enter details: \n");
//scanf("%s", gets(p1.Name)); // wrong
gets(p1.Name); //to get string without
scanf("%d", &p1.age);
scanf("%f", &p1.sal);
//printing the details entered
printf("%s\n", p1.Name);
printf("%d\n", p1.age);
printf("%f\n", p1.sal);
}
Explanation:
The code provided demonstrates the use of C structures (struct) to define a custom data type named
Person and then create instances of that structure to store and display information about individuals.

Pointers

 Pointer is a special type of variable used to store the memory location address of a
variable.
 In c++ programming language, we use the reference operator "&" to access the
address of the variable.
 For example, to access the address of a variable marks, we use &marks.
 In the c++ programming language, we can create pointer variables of any datatype.
Every pointer stores the address of the variable with the same datatype only.
 Syntax: data_type *pointerName;
 In C++, void pointer is a pointer variable that is independent of data type. A void
pointer is used to store the address of a variable of any datatype. We use the keyword
"void" to create void pointer.
 void *anyPtr;

2
Notes Compiled by: Dr. Anand Motwani, Faculty, SCSE, VIT Bhopal University
Pointer to Pointer (Double Pointer) Concept:

//Example of Pointer and double pointer in C


#include<stdio.h>
int main() {
int num = 10; //integer initialized
int *ptr; // declared the pointer
ptr = &num; //assigning the address to ptr.
printf("%p \n", ptr);
printf("%d \n", *ptr); // value at the address

int **d_ptr = &ptr; //declared double pointer and assigned address of ptr.
printf("%d", **d_ptr);
}
// *ptr value at the address
// &num address of operator
The code demonstrates the use of pointers in C, including declaring, assigning, and using
single and double pointers. Here's a step-by-step explanation of the code:

1. int num = 10;: declare an integer variable num and initialize it with the value 10.
2. int *ptr;: declare a pointer to an integer named ptr.
3. ptr = &num;: assign the address of the integer variable num to the pointer ptr.
Now, ptr points to the memory location where num is stored.
4. printf("%p \n", ptr);: use %p format specifier to print the address stored in
ptr.
5. printf("%d \n", *ptr);: use *ptr to dereference the pointer and access the
value stored at the memory location pointed to by ptr. In this case, it's the value 10,
which you print using %d.
6. int **d_ptr = &ptr;: declare a double pointer to an integer named d_ptr and
assign the address of the pointer ptr to it. So, d_ptr points to the memory location
where ptr is stored.
7. printf("%d", **d_ptr);: use **d_ptr to first dereference d_ptr to get the
address stored in ptr, and then dereference ptr to access the value stored at that
address. Again, it's the value 10.
8. Address vary on different systems.

When you run the program, it should print:

3
Notes Compiled by: Dr. Anand Motwani, Faculty, SCSE, VIT Bhopal University
Output:
0x7ffdb34d0a7c
10
10

4
Notes Compiled by: Dr. Anand Motwani, Faculty, SCSE, VIT Bhopal University
DAY - 4

Pointer to Array

A pointer to an array in C is a pointer that points to the first element of an array. It can be
used to access the elements of the array and perform various operations on them. Here's an
example of using a pointer to an array:

// Pointer to Array
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // Pointer to the first element of the array

// Accessing array elements using pointer


printf("Array elements using pointer:\n");
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i + 1, *(ptr + i));
}

// Modifying array elements using pointer


for (int i = 0; i < 5; i++) {
*(ptr + i) = *(ptr + i) * 2; // Double each element
}

// Displaying modified array


printf("\nModified array elements:\n");
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i + 1, arr[i]);
}
return 0;
}
ptr + i calculates a new memory address by adding i to the address stored in ptr.
This new address points to a specific element in memory.

*(ptr + i) dereferences the address calculated by ptr + i, which means it accesses


the value stored at that memory location.

In this example, sizeof(ptr) evaluates to 8 bytes, indicating that ptr is a pointer to a


64-bit integer (common on 64-bit systems), while sizeof(i) evaluates to 4 bytes,
indicating that i is a 32-bit integer. The exact sizes may vary depending on your system
and compiler.

In this example:

1. An integer array arr is declared and initialized with values.

5
Notes Compiled by: Dr. Anand Motwani, Faculty, SCSE, VIT Bhopal University
2. A pointer ptr is declared and initialized with the address of the first
element of the array arr. This effectively makes ptr a pointer to the
array.
3. The program then uses the pointer ptr to access and print the elements of
the array using pointer arithmetic. It also demonstrates how you can
modify the array elements using the pointer.
4. After modifying the elements using the pointer, it displays the modified
array.

When you run this program, it will print the original array elements, double each
element using the pointer, and then display the modified array.

Pointer to Structure

6
Notes Compiled by: Dr. Anand Motwani, Faculty, SCSE, VIT Bhopal University
#include <stdio.h>
#include <string.h>

// Define a structure
struct Student {
char name[50];
int age;
float grade;
};

int main() {
// Declare a structure variable
struct Student student1;

// Initialize the structure variable


strcpy(student1.name, "John");
student1.age = 20;
student1.grade = 85.5;

// Declare a pointer to a structure of type Student


struct Student *ptrStudent;

// Assign the address of student1 to the pointer


ptrStudent = &student1;

// Access and print the structure members using the pointer


printf("Student Name: %s\n", ptrStudent->name);
printf("Student Age: %d\n", ptrStudent->age);
printf("Student Grade: %.2f\n", ptrStudent->grade);
return 0;
}

7
Notes Compiled by: Dr. Anand Motwani, Faculty, SCSE, VIT Bhopal University
Memory Management

malloc and calloc are two functions in C that are used for dynamic memory
allocation. They are both important in data structure implementations, but they
serve slightly different purposes.

malloc (Memory Allocation):

 malloc stands for "memory allocation."


 It is used to allocate a specified number of bytes of memory.
 It returns a pointer to the first byte of the allocated memory block.
 The allocated memory is not initialized; it contains garbage values.
 It's commonly used when you need to allocate memory for an array, linked list nodes,
or any data structure where you want to manage the memory content manually.
 It's more memory-efficient if you don't need to initialize the memory with specific
values because it doesn't zero out the memory.

Example:
int *arr = (int *)malloc(5 * sizeof(int));

calloc (Contiguous Allocation):

 calloc stands for "contiguous allocation."


 It is used to allocate memory for a specified number of elements, each of a specified
size.
 It returns a pointer to the first byte of the allocated memory block.
 The allocated memory is initialized to zero.
 It's commonly used when you want to initialize memory for arrays or data structures
with default values (e.g., initializing an array of integers to zeros).
 It's generally safer in cases where initialization is necessary because it ensures that all
allocated memory is set to known values.

Example:
int *arr = (int *)malloc(5 * sizeof(int));

8
Notes Compiled by: Dr. Anand Motwani, Faculty, SCSE, VIT Bhopal University
Creating Node in Linked List

Steps:
1. Create Structure: Node
struct Node{
int data;
struct Node *next;

};

2. Declaring and Initializing Node


//declaring and initializing the node.
struct Node *head;
struct Node *n1 = NULL;
struct Node *n2 = NULL;
struct Node *n3 = NULL;
struct Node *n4 = NULL;

3. Allocating memory to nodes

n1 = (struct Node*)malloc(sizeof(struct Node));


n2 = (struct Node*)malloc(sizeof(struct Node));
n3 = (struct Node*)malloc(sizeof(struct Node));
n4 = (struct Node*)malloc(sizeof(struct Node));

4. Assign values to data


//Assign values to data.
n1->data = 8;
n2->data = 6;
n3->data = 4;
n4->data = 2;

9
Notes Compiled by: Dr. Anand Motwani, Faculty, SCSE, VIT Bhopal University
5. Connect Nodes (as per the figure of linked list above)

//Connect nodes
n1->next = n2;
n2->next = n3;
n3->next = n4;
n4->next = NULL;
head = n1; //assign n1 to head.
//printf("%d\n", n1->data);

6. Use function to print the linked list.

void printLinkedList(struct Node *p) {


//Write code here to access
while(p != NULL){
printf("%d \n", p->data);
p = p->next;
}

10
Notes Compiled by: Dr. Anand Motwani, Faculty, SCSE, VIT Bhopal University
USE of malloc() 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*) malloc(n * sizeof(int));

// if memory cannot be allocated


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);
}

printf("Sum = %d", sum);


// deallocating the memory
free(ptr);

return 0;
}

11
Notes Compiled by: Dr. Anand Motwani, Faculty, SCSE, VIT Bhopal University

You might also like