Lab 7: Pointers in C – C Programming Lab Report

Lab 7: Pointers in C

A C Programming Lab Report for Lab 7: Pointers in C

Lab Report Information

Lab No.: 7

Title: Pointers in C

Course: Computer Programming (CT 101), I Year I Part

Credit: Important Notes

C Programming Lab Report: Theory for Lab 7

Pointers in C

This C Programming Lab Report explores the powerful concept of Pointers in C. A pointer is a variable that stores the memory address of another variable. They are essential for direct memory manipulation, dynamic memory allocation, and efficient data handling.

  • Declaration: Pointers are declared with an asterisk: data_type *pointer_name;.
  • Address-of Operator (&): Gets the memory address of a variable (e.g., `ptr = &var;`).
  • Dereferencing Operator (*): Accesses the value at the address a pointer holds (e.g., `value = *ptr;`).
  • Pointer Arithmetic: Incrementing a pointer moves it by the size of the data type it points to.
  • Pointers and Arrays: An array name acts as a constant pointer to its first element.

C Programming Lab Report: Programs for Lab 7

1. Matrix Multiplication Using Pointers

Question:

Write a C program that uses pointers to find the product of two matrices.

Program Code:

#include <stdio.h>
#define MAX_ROWS 10
#define MAX_COLS 10

void multiplyMatrices(int m, int n, int p, int q, int mat1[][MAX_COLS], int mat2[][MAX_COLS], int res[][MAX_COLS]) {
    if (n != p) {
        printf("Calculation cannot be performed.\n");
        return;
    }
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < q; j++) {
            *(*(res + i) + j) = 0;
            for (int k = 0; k < n; k++) {
                *(*(res + i) + j) += *(*(mat1 + i) + k) * *(*(mat2 + k) + j);
            }
        }
    }
}

// ... displayMatrix and main functions ...

Output:

Product of the matrices:
19      22
43      50

Algorithm:

  1. Start
  2. Check if matrix multiplication is possible (cols of 1st == rows of 2nd).
  3. If not, print an error and exit.
  4. Read elements of both matrices.
  5. Use three nested loops to perform multiplication using pointer notation.
  6. Store the result in a third matrix.
  7. Display the resultant matrix.
  8. Stop.

Flowchart:

Flowchart shows reading dimensions, a decision for compatibility, nested loops for reading data, a call to the multiplication function (which itself contains nested loops), and finally loops for printing the result.

2. Second Largest Element Using Pointers

Question:

Write a program to find the second largest element from an array using pointers.

Program Code:

#include <stdio.h>

void bubbleSort(int *arr, int n) { /* ... sort logic ... */ }

int main() {
    int n, arr[100];
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    printf("Enter %d elements:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", arr + i);
    }
    bubbleSort(arr, n);
    printf("The second largest element is: %d\n", *(arr + 1));
    return 0;
}

Output:

Enter the number of elements: 5
Enter 5 elements: 15 29 4 88 32
The second largest element in the array is: 32

Algorithm:

  1. Start
  2. Read array size and elements.
  3. Sort the array in descending order using a function that accepts a pointer to the array.
  4. The element at the second position (index 1) of the sorted array is the second largest.
  5. Print the second largest element.
  6. Stop.

Flowchart:

Flowchart shows reading data, calling a sort function, and then accessing and printing the element at index 1 of the sorted array.

3. Replace Matrix Diagonal with Minimum Element

Question:

Write a program to read a 3x3 matrix, find its minimum element, and replace the diagonal elements with that minimum, using pointers.

Program Code:

#include <stdio.h>

void findMinAndReplace(int *matrix, int size, int *min) {
    *min = *matrix; // Assume first element is min
    for (int i = 0; i < size * size; i++) {
        if (*(matrix + i) < *min) {
            *min = *(matrix + i);
        }
    }
    for (int i = 0; i < size; i++) {
        *(matrix + i * size + i) = *min;
    }
}

// ... displayMatrix and main functions ...

Output:

Original Matrix:
9       8       7
6       5       4
3       2       1
Modified Matrix (Diagonal replaced with minimum element 1):
1       8       7
6       1       4
3       2       1

Algorithm:

  1. Start
  2. Read a 3x3 matrix.
  3. Find the minimum element in the matrix using pointer arithmetic.
  4. Traverse the diagonal elements and replace each with the minimum value.
  5. Display the modified matrix.
  6. Stop.

Flowchart:

Flowchart shows reading the matrix, followed by two loops: one to find the minimum value and a second to replace the diagonal elements. Finally, it prints the modified matrix.

4. Reverse an Array Using Pointers

Question:

Write a C program that calls a function to reverse an array and displays the result using a pointer.

Program Code:

#include <stdio.h>

int* reverseArray(int *arr, int size) {
    int *start = arr;
    int *end = arr + size - 1;
    while (start < end) {
        int temp = *start;
        *start = *end;
        *end = temp;
        start++;
        end--;
    }
    return arr;
}

// ... main function ...

Output:

Enter the size of the array: 5
Enter 5 elements: 10 20 30 40 50
Reversed Array: 50 40 30 20 10

Algorithm:

  1. Start
  2. Read an array and its size.
  3. Create two pointers, `start` pointing to the first element and `end` to the last.
  4. In a loop, swap the values pointed to by `start` and `end`.
  5. Increment `start` and decrement `end`, continuing until they meet or cross.
  6. Print the reversed array.
  7. Stop.

Flowchart:

Flowchart illustrates the two-pointer approach, showing a loop that swaps elements and moves the pointers towards the center until the loop condition (start < end) is false.

5. Filter Letters from a String Using Pointers

Question:

Write a program to read a mixed string and transfer only the alphabetic characters into another string using pointers.

Program Code:

#include <stdio.h>

void transferLetters(char *source, char *dest) {
    while (*source != '\0') {
        if ((*source >= 'a' && *source <= 'z') || (*source >= 'A' && *source <= 'Z')) {
            *dest = *source;
            dest++;
        }
        source++;
    }
    *dest = '\0'; // Terminate the destination string
}

// ... main function ...

Output:

Enter a string...: Hello! 123 World.
String containing only letters: HelloWorld

Algorithm:

  1. Start
  2. Read a source string.
  3. Use two pointers, one for the source and one for the destination string.
  4. Iterate through the source string.
  5. If the current character is an alphabet, copy it to the destination and advance the destination pointer.
  6. Always advance the source pointer.
  7. After the loop, null-terminate the destination string.
  8. Print the destination string.
  9. Stop.

Flowchart:

Flowchart shows a loop iterating through the source string. Inside, a decision checks if the character is an alphabet. If true, the character is copied, and the destination pointer moves. The source pointer moves in every iteration.

Discussion and Conclusion

This C Programming Lab Report on Pointers in C provided a comprehensive exploration of pointers. The exercises demonstrated the practical application of pointer concepts, including declaration, dereferencing, and arithmetic, for manipulating arrays and strings. We implemented solutions for complex tasks like matrix multiplication and array sorting using pointer notation instead of array indexing, highlighting the power of pointers for direct memory manipulation. In conclusion, this lab solidified the understanding of pointers as a core component of C programming, essential for efficient code and advanced data structures.

Scroll to Top