C PROGRAMMING AND DATA STRUCTURES PRACTICAL
7 mins read

C PROGRAMMING AND DATA STRUCTURES PRACTICAL

1. Write a simple C Program
a. Print your Name and Address
b. Find Simple interest and Compound interest.
/* Program to print your Name and Address */

#include <stdio.h>

int main() {
    char name[50];
    char address[100];

    printf("Enter your name: ");
    fgets(name, sizeof(name), stdin);

    printf("Enter your address: ");
    fgets(address, sizeof(address), stdin);

    printf("Name: %s", name);
    printf("Address: %s", address);

    return 0;
}

Output:

Enter your name: John Doe
Enter your address: 123, Main Street, City

Name: John Doe
Address: 123, Main Street, City
/* Program to find Simple interest and Compound interest */

#include <stdio.h>
#include <math.h>

double calculateSI(double p, double r, double n) {
    return (p * r * n) / 100.0;
}

double calculateCI(double p, double r, double n) {
    return p * pow((1 + r / 100.0), n) - p;
}

int main() {
    double p, r, n;

    printf("Enter principal amount: ");
    scanf("%lf", &p);

    printf("Enter interest rate: ");
    scanf("%lf", &r);

    printf("Enter time in years: ");
    scanf("%lf", &n);

    double SI = calculateSI(p, r, n);
    double CI = calculateCI(p, r, n);

    printf("Simple Interest: %.2lf\n", SI);
    printf("Compound Interest: %.2lf\n", CI);

    return 0;
}
Output:

Enter principal amount: 5000
Enter interest rate: 10
Enter time in years: 3
Simple Interest: 1500.00
Compound Interest: 1557.63
2. Write a C program to swap two variable’s using
(i) third variable and (ii) without using a third variable.
/* C program to swap two variable’s */

#include <stdio.h>

void swapWithThirdVar(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void swapWithoutThirdVar(int *a, int *b) {
    *a = *a + *b;
    *b = *a - *b;
    *a = *a - *b;
}

int main() {
    int num1, num2;

    printf("Enter the first number: ");
    scanf("%d", &num1);

    printf("Enter the second number: ");
    scanf("%d", &num2);

    printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);

    // Swapping with a third variable
    swapWithThirdVar(&num1, &num2);
    printf("After swapping with third variable: num1 = %d, num2 = %d\n", num1, num2);

    // Swapping without a third variable
    swapWithoutThirdVar(&num1, &num2);
    printf("After swapping without third variable: num1 = %d, num2 = %d\n", num1, num2);

    return 0;
}
Output:

Enter the first number: 10
Enter the second number: 20
Before swapping: num1 = 10, num2 = 20
After swapping with third variable: num1 = 20, num2 = 10
After swapping without third variable: num1 = 10, num2 = 20
3. Write a program to find the largest number between given three numbers.
/* C Program to find the largest number between given three numbers */

#include <stdio.h>

int findLargest(int num1, int num2, int num3) {
    int largest = num1;

    if (num2 > largest) {
        largest = num2;
    }

    if (num3 > largest) {
        largest = num3;
    }

    return largest;
}

int main() {
    int num1, num2, num3;

    printf("Enter three numbers: ");
    scanf("%d %d %d", &num1, &num2, &num3);

    int largest = findLargest(num1, num2, num3);

    printf("The largest number is: %d\n", largest);

    return 0;
}
Output:

Enter three numbers: 5 10 7
The largest number is: 10
4. Write a program to print all prime numbers from 1 to N.
/* C Program to print all prime numbers from 1 to N */

#include <stdio.h>
#include <stdbool.h>

bool isPrime(int num) {
    if (num <= 1) {
        return false;
    }

    for (int i = 2; i <= num / 2; i++) {
        if (num % i == 0) {
            return false;
        }
    }

    return true;
}

void printPrimes(int N) {
    printf("Prime numbers between 1 and %d are:\n", N);

    for (int i = 2; i <= N; i++) {
        if (isPrime(i)) {
            printf("%d ", i);
        }
    }

    printf("\n");
}

int main() {
    int N;

    printf("Enter the value of N: ");
    scanf("%d", &N);

    printPrimes(N);

    return 0;
}
Output:

Enter the value of N: 20
Prime numbers between 1 and 20 are:
2 3 5 7 11 13 17 19
5. Write a program to prepare the total marks for N students by reading the Reg.No, Name, Mark1 to Mark6 by using array of structures.
/* C Program to prepare the total marks for N students by reading the Reg.No, Name, Mark1 to Mark6 by using array of structures */

#include <stdio.h>

#define MAX_STUDENTS 100

struct Student {
    int regNo;
    char name[50];
    int marks[6];
    int totalMarks;
};

int main() {
    int n;
    struct Student students[MAX_STUDENTS];

    printf("Enter the number of students: ");
    scanf("%d", &n);

    // Reading student details
    for (int i = 0; i < n; i++) {
        printf("Enter details for student %d:\n", i + 1);
        
        printf("Registration Number: ");
        scanf("%d", &students[i].regNo);
        
        printf("Name: ");
        scanf("%s", students[i].name);

        printf("Enter marks for 6 subjects:\n");
        for (int j = 0; j < 6; j++) {
            printf("Mark %d: ", j + 1);
            scanf("%d", &students[i].marks[j]);
        }
    }

    // Calculating total marks for each student
    for (int i = 0; i < n; i++) {
        int total = 0;
        for (int j = 0; j < 6; j++) {
            total += students[i].marks[j];
        }
        students[i].totalMarks = total;
    }

    // Displaying the total marks for each student
    printf("Total marks for each student:\n");
    for (int i = 0; i < n; i++) {
        printf("Student %d:\n", i + 1);
        printf("Registration Number: %d\n", students[i].regNo);
        printf("Name: %s\n", students[i].name);
        printf("Total Marks: %d\n", students[i].totalMarks);
        printf("\n");
    }

    return 0;
}
Output:

Enter the number of students: 3
Enter details for student 1:
Registration Number: 1001
Name: John
Enter marks for 6 subjects:
Mark 1: 80
Mark 2: 85
Mark 3: 90
Mark 4: 75
Mark 5: 95
Mark 6: 88

Enter details for student 2:
Registration Number: 1002
Name: Sarah
Enter marks for 6 subjects:
Mark 1: 92
Mark 2: 88
Mark 3: 78
Mark 4: 86
Mark 5: 90
Mark 6: 91

Enter details for student 3:
Registration Number: 1003
Name: David
Enter marks for 6 subjects:
Mark 1: 75
Mark 2: 80
Mark 3: 82
Mark 4: 78
Mark 5: 85
Mark 6: 80

Total marks for each student:
Student 1:
Registration Number: 1001
Name: John
Total Marks: 513

Student 2:
Registration Number: 1002
Name: Sarah
Total Marks: 525

Student 3:
Registration Number: 1003
Name: David
Total Marks: 480
6. Write a program using the function power (a,b) to calculate the value of a raised to b.
/* C Program using the function power (a,b) to calculate the value of a raised to b */

#include <stdio.h>

double power(double a, int b);

int main() {
    double base;
    int exponent;

    printf("Enter the base number: ");
    scanf("%lf", &base);

    printf("Enter the exponent: ");
    scanf("%d", &exponent);

    double result = power(base, exponent);

    printf("%.2lf raised to the power of %d is %.2lf\n", base, exponent, result);

    return 0;
}

double power(double a, int b) {
    double result = 1.0;

    if (b >= 0) {
        for (int i = 0; i < b; i++) {
            result *= a;
        }
    } else {
        for (int i = 0; i > b; i--) {
            result /= a;
        }
    }

    return result;
}
Output:

Enter the base number: 2.5
Enter the exponent: 3
2.50 raised to the power of 3 is 15.63
7. Write a program to find the length of the given string using pointers.
/* C Program to find the length of the given string using pointers */

#include <stdio.h>

int stringLength(char *str);

int main() {
    char str[100];

    printf("Enter a string: ");
    scanf("%s", str);

    int length = stringLength(str);

    printf("Length of the string is: %d\n", length);

    return 0;
}

int stringLength(char *str) {
    int length = 0;

    while (*str != '\0') {
        length++;
        str++;
    }

    return length;
}
Output:

Enter a string: Hello World
Length of the string is: 11
8. Write a program to find factorial of a number using recursion.
#include <stdio.h>

int factorial(int n);

int main() {
    int num;

    printf("Enter a positive integer: ");
    scanf("%d", &num);

    if (num < 0) {
        printf("Factorial is not defined for negative numbers.\n");
    } else {
        int result = factorial(num);
        printf("Factorial of %d is %d\n", num, result);
    }

    return 0;
}

int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}
Output:

Enter a positive integer: 5
Factorial of 5 is 120
9. Write a program in ‘C’ to create a singly linked list containing at least five elements. Make necessary assumptions.
/* C Program to to create a singly linked list containing at least five elements */

#include <stdio.h>
#include <stdlib.h>

// Define the structure for a node
struct Node {
    int data;
    struct Node *next;
};

// Function to create a new node
struct Node *createNode(int value) {
    struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
    if (newNode == NULL) {
        printf("Memory allocation failed.\n");
        return NULL;
    }
    newNode->data = value;
    newNode->next = NULL;
    return newNode;
}

// Function to insert a node at the beginning of the linked list
struct Node *insertNode(struct Node *head, int value) {
    struct Node *newNode = createNode(value);
    if (newNode == NULL) {
        return head;
    }
    if (head == NULL) {
        return newNode;
    }
    newNode->next = head;
    return newNode;
}

// Function to display the linked list
void displayList(struct Node *head) {
    struct Node *current = head;
    if (current == NULL) {
        printf("List is empty.\n");
        return;
    }
    printf("Linked List: ");
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

int main() {
    // Create an empty linked list
    struct Node *head = NULL;

    // Insert nodes at the beginning of the linked list
    head = insertNode(head, 5);
    head = insertNode(head, 4);
    head = insertNode(head, 3);
    head = insertNode(head, 2);
    head = insertNode(head, 1);

    // Display the linked list
    displayList(head);

    return 0;
}
Output:

Linked List: 1 2 3 4 5
11. Write a “C” program to perform operations in stack using array.
/* C Program to perform operations in stack using array */

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 10

struct Stack {
    int items[MAX_SIZE];
    int top;
};

void initializeStack(struct Stack* stack) {
    stack->top = -1;
}

int isFull(struct Stack* stack) {
    return stack->top == MAX_SIZE - 1;
}

int isEmpty(struct Stack* stack) {
    return stack->top == -1;
}

void push(struct Stack* stack, int item) {
    if (isFull(stack)) {
        printf("Stack is full. Cannot push item.\n");
    } else {
        stack->top++;
        stack->items[stack->top] = item;
        printf("Pushed %d to the stack.\n", item);
    }
}

int pop(struct Stack* stack) {
    if (isEmpty(stack)) {
        printf("Stack is empty. Cannot pop item.\n");
        return -1;
    } else {
        int item = stack->items[stack->top];
        stack->top--;
        printf("Popped %d from the stack.\n", item);
        return item;
    }
}

int peek(struct Stack* stack) {
    if (isEmpty(stack)) {
        printf("Stack is empty.\n");
        return -1;
    } else {
        return stack->items[stack->top];
    }
}

void display(struct Stack* stack) {
    if (isEmpty(stack)) {
        printf("Stack is empty.\n");
    } else {
        printf("Stack elements: ");
        for (int i = 0; i <= stack->top; i++) {
            printf("%d ", stack->items[i]);
        }
        printf("\n");
    }
}

int main() {
    struct Stack stack;
    initializeStack(&stack);

    push(&stack, 1);
    push(&stack, 2);
    push(&stack, 3);
    push(&stack, 4);
    display(&stack);

    pop(&stack);
    display(&stack);

    int top = peek(&stack);
    printf("Top element: %d\n", top);

    return 0;
}
Output:

Pushed 1 to the stack.
Pushed 2 to the stack.
Pushed 3 to the stack.
Pushed 4 to the stack.
Stack elements: 1 2 3 4
Popped 4 from the stack.
Stack elements: 1 2 3
Top element: 3
11. Write a “C” program to convert an infix expression into post fix expression
/* C Program to convert an infix expression into post fix expression */

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

#define MAX_SIZE 100

struct Stack {
    char items[MAX_SIZE];
    int top;
};

void initializeStack(struct Stack* stack) {
    stack->top = -1;
}

bool isFull(struct Stack* stack) {
    return stack->top == MAX_SIZE - 1;
}

bool isEmpty(struct Stack* stack) {
    return stack->top == -1;
}

void push(struct Stack* stack, char item) {
    if (isFull(stack)) {
        printf("Stack is full. Cannot push item.\n");
    } else {
        stack->top++;
        stack->items[stack->top] = item;
    }
}

char pop(struct Stack* stack) {
    if (isEmpty(stack)) {
        printf("Stack is empty. Cannot pop item.\n");
        return '\0';
    } else {
        char item = stack->items[stack->top];
        stack->top--;
        return item;
    }
}

char peek(struct Stack* stack) {
    if (isEmpty(stack)) {
        return '\0';
    } else {
        return stack->items[stack->top];
    }
}

int getPrecedence(char operator) {
    switch (operator) {
        case '+':
        case '-':
            return 1;
        case '*':
        case '/':
            return 2;
        case '^':
            return 3;
        default:
            return -1;
    }
}

bool isOperator(char ch) {
    return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^');
}

bool isOperand(char ch) {
    return ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'));
}

void infixToPostfix(char* infix, char* postfix) {
    struct Stack stack;
    initializeStack(&stack);
    int i, j = 0;

    for (i = 0; infix[i] != '\0'; i++) {
        char ch = infix[i];

        if (isOperand(ch)) {
            postfix[j++] = ch;
        } else if (isOperator(ch)) {
            while (!isEmpty(&stack) && getPrecedence(ch) <= getPrecedence(peek(&stack))) {
                postfix[j++] = pop(&stack);
            }
            push(&stack, ch);
        } else if (ch == '(') {
            push(&stack, ch);
        } else if (ch == ')') {
            while (!isEmpty(&stack) && peek(&stack) != '(') {
                postfix[j++] = pop(&stack);
            }
            if (!isEmpty(&stack) && peek(&stack) == '(') {
                pop(&stack);
            }
        }
    }

    while (!isEmpty(&stack)) {
        postfix[j++] = pop(&stack);
    }

    postfix[j] = '\0';
}

int main() {
    char infix[MAX_SIZE];
    char postfix[MAX_SIZE];

    printf("Enter the infix expression: ");
    scanf("%s", infix);

    infixToPostfix(infix, postfix);

    printf("Postfix expression: %s\n", postfix);

    return 0;
}
Output:

Enter the infix expression: a+b*c-d/e
Postfix expression: abc*+de/-
12. Write a “C” program to perform operations in queue using array.
/* C Program to perform operations in queue using array*/

#include <stdio.h>

#define MAX_SIZE 100

int queue[MAX_SIZE];
int front = -1;
int rear = -1;

void enqueue(int value) {
    if (rear == MAX_SIZE - 1) {
        printf("Queue is full. Cannot enqueue.\n");
        return;
    }
    if (front == -1) {
        front = 0;
    }
    rear++;
    queue[rear] = value;
    printf("Enqueued %d\n", value);
}

void dequeue() {
    if (front == -1 || front > rear) {
        printf("Queue is empty. Cannot dequeue.\n");
        return;
    }
    printf("Dequeued %d\n", queue[front]);
    front++;
}

void display() {
    if (front == -1 || front > rear) {
        printf("Queue is empty.\n");
        return;
    }
    printf("Queue elements: ");
    for (int i = front; i <= rear; i++) {
        printf("%d ", queue[i]);
    }
    printf("\n");
}

int main() {
    enqueue(10);
    enqueue(20);
    enqueue(30);
    display();
    dequeue();
    display();
    enqueue(40);
    display();

    return 0;
}
Output:

Enqueued 10
Enqueued 20
Enqueued 30
Queue elements: 10 20 30 
Dequeued 10
Queue elements: 20 30 
Enqueued 40
Queue elements: 20 30 40 
13. Write a “C” program to add two 3 x 3 matrices and display the result in Matrix form.
/* C Program to add two 3 x 3 matrices and display the result in Matrix form */

#include <stdio.h>

void addMatrices(int matrix1[][3], int matrix2[][3], int result[][3]) {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            result[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }
}

void displayMatrix(int matrix[][3]) {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int matrix1[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
    int matrix2[3][3] = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} };
    int result[3][3];

    addMatrices(matrix1, matrix2, result);

    printf("Matrix 1:\n");
    displayMatrix(matrix1);

    printf("\nMatrix 2:\n");
    displayMatrix(matrix2);

    printf("\nResultant Matrix:\n");
    displayMatrix(result);

    return 0;
}
Output:

Matrix 1:
1 2 3
4 5 6
7 8 9

Matrix 2:
9 8 7
6 5 4
3 2 1

Resultant Matrix:
10 10 10
10 10 10
10 10 10
14. Write a “C” program to read 10 elements and sort the above numbers using bubble sort.
/* C Program to read 10 elements and sort the above numbers
using bubble sort */

#include <stdio.h>

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap arr[j] and arr[j+1]
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int arr[10];
    printf("Enter 10 elements:\n");

    for (int i = 0; i < 10; i++) {
        scanf("%d", &arr[i]);
    }

    bubbleSort(arr, 10);

    printf("Sorted array in ascending order:\n");
    for (int i = 0; i < 10; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}
Output:

Enter 10 elements:
9 5 2 7 3 6 1 8 4 0
Sorted array in ascending order:
0 1 2 3 4 5 6 7 8 9
15. Write a “C” Program for binary searching.
/* C Program for binary searching*/

#include <stdio.h>

int binarySearch(int arr[], int n, int key) {
    int low = 0;
    int high = n - 1;

    while (low <= high) {
        int mid = (low + high) / 2;

        if (arr[mid] == key) {
            return mid; // Element found at index mid
        } else if (arr[mid] < key) {
            low = mid + 1; // Search in the right half
        } else {
            high = mid - 1; // Search in the left half
        }
    }

    return -1; // Element not found
}

int main() {
    int arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
    int n = sizeof(arr) / sizeof(arr[0]);

    int key;
    printf("Enter the element to search: ");
    scanf("%d", &key);

    int index = binarySearch(arr, n, key);

    if (index != -1) {
        printf("Element %d found at index %d\n", key, index);
    } else {
        printf("Element not found\n");
    }

    return 0;
}
Output:

Enter the element to search: 12
Element 12 found at index 5

Leave a Reply

Your email address will not be published. Required fields are marked *