C Data Structures for Beginners


Introduction

Data structures are a fundamental concept in computer science and programming. They allow you to organize and manage data efficiently, making it easier to perform operations and solve problems. In this guide, we'll introduce you to some essential data structures in C and provide sample code to illustrate their usage.


Key Data Structures

Before we dive into examples, let's cover some key data structures commonly used in C programming:

  • Arrays: A collection of elements of the same data type stored in contiguous memory locations.
  • Structures: A user-defined data type that groups variables of different data types under a single name.
  • Linked Lists: A data structure that consists of nodes, each containing data and a reference to the next node.
  • Stacks: A linear data structure that follows the Last In, First Out (LIFO) principle.
  • Queues: A linear data structure that follows the First In, First Out (FIFO) principle.
  • Trees: A hierarchical data structure with a root node and child nodes, commonly used in various applications, including binary trees.
  • Hash Tables: A data structure that allows for efficient data retrieval using a key-value pair mechanism.

Sample Code

Let's explore some examples of data structures in C:


Arrays

#include <stdio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
printf("Array elements: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\\n");
return 0;
}

Structures

#include <stdio.h>
#include <string.h>
struct Student {
char name[50];
int age;
float gpa;
};
int main() {
struct Student student1;
strcpy(student1.name, "Alice");
student1.age = 20;
student1.gpa = 3.7;
printf("Student Info:\\n");
printf("Name: %s\\n", student1.name);
printf("Age: %d\\n", student1.age);
printf("GPA: %.2f\\n", student1.gpa);
return 0;
}

Linked Lists

#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
// Print the linked list
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
return 0;
}

Conclusion

Data structures are essential for efficient data management and manipulation in C programming. This guide has introduced you to some fundamental data structures, including arrays, structures, linked lists, and discussed their usage with sample code. As you continue your C programming journey, you'll find data structures to be a cornerstone of solving a wide range of problems and building sophisticated applications.