DS Lecture 2
DS Lecture 2
#include <stdio.h>
int main()
{
int numbers[5] = {10, 20, 30, 40, 50};
printf("%d", numbers[4]); //40
return 0;
}
int main()
{
int numbers[] = {10, 20, 30, 40, 50};
printf("%d", numbers[3]); //40
return 0;
}
// Sum of n numbers using 1D Array
#include <stdio.h>
int main() {
int n, i, sum = 0;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
for (i = 0; i < n; i++)
sum += arr[i];
printf("Sum of the numbers is: %d\n", sum);
return 0;
}
// Sorting of n numbers using 1D Array
#include <stdio.h>
int main() {
int n, i, j, temp;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
for (i = 0; i < n; i++) {
for (j = 0; j < n-1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Sorted numbers in ascending order:\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
// Find the Maximum Element in an Array
#include <stdio.h>
int main() {
int arr[] = {3, 8, 1, 6, 7};
int max = arr[0];
int size = sizeof(arr) / sizeof(arr[0]);
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
printf("Maximum: %d\n", max);
return 0;
}
//2D Array
int main()
{
int numbers[][] = {10, 20, 30, 40};
printf("%d", numbers[1][1]); //40
return 0;
}
#include <stdio.h>
int main()
{
int numbers[2][3]={{10,20,30}, {40,50,60}};
printf("%d", numbers[1][0]); //40
return 0;
}
#include <stdio.h>
int main()
{
int numbers[2][2] = {10, 20, 30, 40};
int size = sizeof(numbers)/sizeof(numbers[0]);
printf("%d", size);
return 0;
}
Linked List
// C Program to create a Linked List
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
int main() {
Node *first = (Node *)malloc(sizeof(Node));
first->data = 10;
Node *second = (Node *)malloc(sizeof(Node));
second->data = 20;
Node *third = (Node *)malloc(sizeof(Node));
third->data = 30;
first->next = second; // This will create: 10 -> 20
second->next = third; // 10 -> 20 -> 30
third->next = NULL; // 10 -> 20 -> 30 -> NULL
printf("Linked List: ");
Node* temp = first;
while(temp) {
printf("%d ", temp->data);
temp = temp->next;
}
return 0;
}
Another method
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
int main() {
Node* head = createNode(10);
head->next = createNode(20);
head->next->next = createNode(30);
displayList(head);
return 0;
}
int main() {
Node* head = NULL; // Initialize the head of the list
int n, value;
printf("Enter the number of elements: ");
scanf("%d", &n);