Basic Pointer Programming Questions
I am Jyotiprakash, a deeply driven computer systems engineer, software developer, teacher, and philosopher. With a decade of professional experience, I have contributed to various cutting-edge software products in network security, mobile apps, and healthcare software at renowned companies like Oracle, Yahoo, and Epic. My academic journey has taken me to prestigious institutions such as the University of Wisconsin-Madison and BITS Pilani in India, where I consistently ranked among the top of my class.
At my core, I am a computer enthusiast with a profound interest in understanding the intricacies of computer programming. My skills are not limited to application programming in Java; I have also delved deeply into computer hardware, learning about various architectures, low-level assembly programming, Linux kernel implementation, and writing device drivers. The contributions of Linus Torvalds, Ken Thompson, and Dennis Ritchie—who revolutionized the computer industry—inspire me. I believe that real contributions to computer science are made by mastering all levels of abstraction and understanding systems inside out.
In addition to my professional pursuits, I am passionate about teaching and sharing knowledge. I have spent two years as a teaching assistant at UW Madison, where I taught complex concepts in operating systems, computer graphics, and data structures to both graduate and undergraduate students. Currently, I am an assistant professor at KIIT, Bhubaneswar, where I continue to teach computer science to undergraduate and graduate students. I am also working on writing a few free books on systems programming, as I believe in freely sharing knowledge to empower others.
Here are 10 C programming exercises that focus on pointers:
Swap using Pointers: Write a program to swap the values of two integers using pointers.
Array Manipulation: Create an array of integers and write a program to find the sum and average of the elements using pointers.
Dynamic Memory Allocation: Implement a program that dynamically allocates memory for an integer and then deallocates it.
String Operations: Write a program that takes a string as input and uses pointers to count the number of vowels and consonants in it.
Linked List: Implement a simple linked list. Write functions to insert, delete, and display elements using pointers.
Pointer Arithmetic: Create an array of integers and use pointer arithmetic to find the difference between consecutive elements.
Function Pointers: Write a program that uses function pointers to implement different mathematical operations (addition, subtraction, multiplication, division).
Matrix Operations: Implement a program to perform matrix multiplication using pointers.
Structures and Pointers: Define a structure representing a student with name, roll number, and marks. Write a program to store and display student information using pointers.
File Operations with Pointers: Create a file containing integers. Write a program to read the file using pointers, find the sum of the numbers, and then write the result to another file.
These exercises cover a range of pointer-related concepts and will help you practice and strengthen your skills in C programming. I have solved all of the above with explanatory comments. You should first make a sincere attempt at solving these problems before looking at the solutions.
1. Swap using Pointers:
#include <stdio.h>
void swap(int *a, int *b) {
// Temporary variable to hold the value during the swap
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
// Calling the swap function with pointers
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
2. Array Manipulation:
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int *ptr = arr;
int sum = 0;
// Calculating sum and average using pointers
for (int i = 0; i < n; i++) {
sum += *ptr;
ptr++;
}
printf("Sum: %d\n", sum);
printf("Average: %.2f\n", (float)sum / n);
return 0;
}
3. Dynamic Memory Allocation:
#include <stdio.h>
#include <stdlib.h>
int main() {
// Dynamically allocating memory for an integer
int *ptr = (int *)malloc(sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
*ptr = 42;
printf("Dynamically allocated value: %d\n", *ptr);
// Deallocating the dynamically allocated memory
free(ptr);
return 0;
}
4. String Operations:
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
int vowels = 0, consonants = 0;
char *ptr = str;
// Counting vowels and consonants using pointers
while (*ptr != '\0') {
if (isalpha(*ptr)) {
char ch = tolower(*ptr);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
else
consonants++;
}
ptr++;
}
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
return 0;
}
5. Linked List:
#include <stdio.h>
#include <stdlib.h>
// Node structure for the linked list
struct Node {
int data;
struct Node *next;
};
// Function to insert a new node at the end of the linked list
void insertNode(struct Node **head, int value) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
struct Node *temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// Function to display the linked list
void displayList(struct Node *head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
int main() {
struct Node *head = NULL;
// Inserting nodes into the linked list
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
// Displaying the linked list
printf("Linked List: ");
displayList(head);
return 0;
}
6. Pointer Arithmetic:
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int *ptr = arr;
// Using pointer arithmetic to find the difference between consecutive elements
for (int i = 0; i < n - 1; i++) {
printf("Difference between arr[%d] and arr[%d]: %d\n", i + 1, i, *(ptr + i + 1) - *(ptr + i));
}
return 0;
}
7. Function Pointers:
#include <stdio.h>
// Function pointer type for mathematical operations
typedef int (*Operation)(int, int);
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
int divide(int a, int b) {
if (b != 0)
return a / b;
else
return -1; // Indicating division by zero
}
int main() {
int x = 10, y = 5;
// Function pointer variable
Operation operation;
// Using function pointers to perform different operations
operation = add;
printf("Addition: %d\n", operation(x, y));
operation = subtract;
printf("Subtraction: %d\n", operation(x, y));
operation = multiply;
printf("Multiplication: %d\n", operation(x, y));
operation = divide;
int result = operation(x, y);
if (result == -1)
printf("Division by zero is not allowed.\n");
else
printf("Division: %d\n", result);
return 0;
}
8. Matrix Operations:
#include <stdio.h>
void multiplyMatrices(int mat1[][3], int mat2[][3], int result[][3]) {
// Performing matrix multiplication
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
result[i][j] = 0;
for (int k = 0; k < 3; ++k) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}
void displayMatrix(int matrix[][3]) {
// Displaying the matrix
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int mat1[3][3] = {{1, 2, 3}, {4
, 5, 6}, {7, 8, 9}};
int mat2[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int result[3][3];
// Multiplying matrices and displaying the result
multiplyMatrices(mat1, mat2, result);
printf("Matrix 1:\n");
displayMatrix(mat1);
printf("\nMatrix 2:\n");
displayMatrix(mat2);
printf("\nResultant Matrix:\n");
displayMatrix(result);
return 0;
}
9. Structures and Pointers:
#include <stdio.h>
// Structure representing a student
struct Student {
char name[50];
int rollNumber;
float marks;
};
int main() {
struct Student student1 = {"John Doe", 101, 85.5};
// Pointer to the student structure
struct Student *ptrStudent = &student1;
// Displaying student information using pointers
printf("Student Name: %s\n", ptrStudent->name);
printf("Roll Number: %d\n", ptrStudent->rollNumber);
printf("Marks: %.2f\n", ptrStudent->marks);
return 0;
}
10. File Operations with Pointers:
#include <stdio.h>
int main() {
FILE *inputFile, *outputFile;
int number, sum = 0;
// Open the input file for reading
inputFile = fopen("numbers.txt", "r");
// Check if the file was opened successfully
if (inputFile == NULL) {
perror("Error opening file");
return 1;
}
// Read numbers from the file and calculate the sum
while (fscanf(inputFile, "%d", &number) == 1) {
sum += number;
}
// Close the input file
fclose(inputFile);
// Open the output file for writing
outputFile = fopen("result.txt", "w");
// Check if the file was opened successfully
if (outputFile == NULL) {
perror("Error opening file");
return 1;
}
// Write the sum to the output file
fprintf(outputFile, "Sum: %d\n", sum);
// Close the output file
fclose(outputFile);
printf("Result written to result.txt\n");
return 0;
}