Module 4 – Programming in C:
Questions and Answers
1. Write a function (using pointer parameters) that compares two integer arrays to
see whether they are identical. The function returns 1 if they are identical, 0
otherwise.
Answer:
#include <stdio.h>
int compareArrays(int *arr1, int *arr2, int size) {
for(int i = 0; i < size; i++) {
if(*(arr1 + i) != *(arr2 + i)) {
return 0; // Not identical
return 1; // Identical
int main() {
int a[] = {1, 2, 3, 4};
int b[] = {1, 2, 3, 4};
int result = compareArrays(a, b, 4);
printf("Arrays are %s\n", result ? "Identical" : "Not Identical");
return 0;
}
2. What is the difference between a pointer and a normal variable? Provide examples
to support your answer.
Answer:
Example:
int x = 10; // Normal variable
int *ptr = &x; // Pointer
3. Explain pointer arithmetic in C with an example. Write a C program to demonstrate
pointer arithmetic (increment, decrement, addition, subtraction, and pointer
difference) using an integer array. Provide a detailed explanation of the output.
Answer:
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p = arr;
printf("Initial address: %p, value: %d\n", p, *p);
p++; // Increment
printf("After increment: %p, value: %d\n", p, *p);
p--; // Decrement
printf("After decrement: %p, value: %d\n", p, *p);
p = p + 2; // Addition
printf("After adding 2: %p, value: %d\n", p, *p);
p = p - 1; // Subtraction
printf("After subtracting 1: %p, value: %d\n", p, *p);
int *p1 = &arr[1], *p2 = &arr[4];
printf("Pointer difference: %ld\n", p2 - p1); // Outputs 3 (index difference)
return 0;
4. What are the rules of pointer operations?
Answer:
● A pointer must point to a valid memory location.
● You can increment or decrement a pointer.
● You can subtract one pointer from another (if they point to the same array).
● Pointer arithmetic depends on the data type size.
● You cannot perform addition/multiplication between two pointers.
● Pointers of different types should not be directly assigned without casting.
5. Differentiate between char name[] and char *name in C.
Answer:
Example:
char name1[] = "Hello";
char *name2 = "Hello";
6. What do you mean by a pointer variable? How is it initialized?
Answer:
● A pointer variable stores the address of another variable.
● Syntax:
int x = 10;
int *p; // Declaration
p = &x; // Initialization
7. Write a function using pointers to add two matrices and to return the resultant
matrix to the calling function.
Answer:
#include <stdio.h>
#define SIZE 2
void addMatrix(int *a, int *b, int *res, int rows, int cols) {
for(int i = 0; i < rows * cols; i++) {
*(res + i) = *(a + i) + *(b + i);
int main() {
int A[SIZE][SIZE] = {{1, 2}, {3, 4}};
int B[SIZE][SIZE] = {{5, 6}, {7, 8}};
int result[SIZE][SIZE];
addMatrix((int *)A, (int *)B, (int *)result, SIZE, SIZE);
printf("Resultant Matrix:\n");
for(int i = 0; i < SIZE; i++) {
for(int j = 0; j < SIZE; j++) {
printf("%d ", result[i][j]);
printf("\n");
return 0;
}
8. Write a program to calculate the sum of two numbers which are passed as
arguments using the call by reference method.
Answer:
#include <stdio.h>
void add(int *a, int *b, int *sum) {
*sum = *a + *b;
int main() {
int x = 5, y = 10, result;
add(&x, &y, &result);
printf("Sum = %d\n", result);
return 0;
9. Explain how pointers can be passed to functions with an example.
Answer:
We can pass the address of variables to functions so they can modify the original values.
Example:
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
int main() {
int x = 3, y = 4;
swap(&x, &y);
printf("x = %d, y = %d\n", x, y);
return 0;
Output:
x = 4, y = 3
10. How can an array be passed to a function using a pointer? Provide an example.
Answer:
#include <stdio.h>
void display(int *arr, int size) {
for(int i = 0; i < size; i++) {
printf("%d ", *(arr + i));
printf("\n");
int main() {
int a[] = {10, 20, 30, 40};
display(a, 4); // Passing array as pointer
return 0;
}
11. Differentiate between an array of pointers and a pointer to an array.
Answer:
int *arr[3]; // Array of 3 int pointers
int a[5];
int (*ptr)[5] = &a; // Pointer to array of 5 integers
12. Explain the concept of a function to return a pointer to the calling function with
example.
Answer:
● Functions can return pointers, but you must ensure that the returned pointer points
to valid memory (not local variables).
Example:
#include <stdio.h>
int* getMax(int *a, int *b) {
if(*a > *b)
return a;
else
return b;
}
int main() {
int x = 10, y = 20;
int *p = getMax(&x, &y);
printf("Maximum is: %d\n", *p);
return 0;
13. How do you declare and initialize a pointer to a pointer? Write a program to
demonstrate this concept.
Answer:
#include <stdio.h>
int main() {
int x = 10;
int *p = &x;
int **pp = &p;
printf("Value of x = %d\n", x);
printf("Using single pointer: %d\n", *p);
printf("Using double pointer: %d\n", **pp);
return 0;
● *p gives value of x
● **pp also gives value of x
14. Write a C program to reverse a string using pointers.
Answer:
#include <stdio.h>
#include <string.h>
void reverseString(char *str) {
char *start = str;
char *end = str + strlen(str) - 1;
char temp;
while(start < end) {
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
int main() {
char str[100] = "hello";
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
}
15. Write a C program to print the elements of an array in reverse order using
pointers.
Answer:
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p = arr + 4; // Point to last element
for(int i = 4; i >= 0; i--) {
printf("%d ", *p);
p--;
return 0;
16. What is an array of pointers, and how is it useful in string manipulation?
Answer:
Array of Pointers: Each element in the array stores an address (often used with strings).
Useful for handling multiple strings efficiently.
You can change individual strings without reallocating the whole array.
char *names[] = {"Alice", "Bob", "Charlie"};
17. How does pointer arithmetic help in traversing a string?
Answer:
A string is an array of characters ending with \0. Pointer arithmetic helps to:
● Traverse each character
● Access or modify elements without using an index
#include <stdio.h>
int main() {
char str[] = "Hello";
char *p = str;
while(*p != '\0') {
printf("%c ", *p);
p++; // Move to next character
return 0;
18. Explain the difference between *ptr++ and (*ptr)++ if ptr is pointing to the first
element of an array.
Answer:
int arr[] = {10, 20};
int *ptr = arr;
printf("%d\n", *ptr++); // Outputs 10, then ptr points to arr[1]
ptr = arr;
printf("%d\n", (*ptr)++); // Outputs 10, then arr[0] becomes 11
19. Write a program using pointers to compute the sum of all elements stored in an
array.
Answer:
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int *p = arr;
int sum = 0;
for(int i = 0; i < 5; i++) {
sum += *(p + i);
printf("Sum = %d\n", sum);
return 0;
}
20. Write a function using pointers to exchange the values stored in two locations in
the memory.
Answer:
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
int main() {
int x = 5, y = 10;
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
21. What are the advantages of using function pointer in C? Write a program that uses
a function pointer as a function argument.
Answer:
Dynamic function calling: Enables selecting functions at runtime.
● Callback mechanism: Used in libraries, e.g., qsort().
● Efficient tables of functions: Like jump tables or event handling.
● Flexibility: Functionality can be swapped easily.
Example:
#include <stdio.h>
void greet() {
printf("Hello!\n");
void execute(void (*func)()) {
func(); // calling the function using pointer
int main() {
execute(greet); // passing function pointer
return 0;
22. Explain the difference between accessing structure members using a structure
variable and a pointer to structure. Provide an example.
Answer:
Example:
#include <stdio.h>
struct Student {
int id;
char name[20];
};
int main() {
struct Student s = {1, "Nidhi"};
struct Student *ptr = &s;
printf("%d %s\n", s.id, s.name); // using variable
printf("%d %s\n", ptr->id, ptr->name); // using pointer
return 0;
23. Explain the effects of the following statements:
a) int a, *b=&a;
b) int p, *p;
c) char *s;
Answer:
a) int a, *b = &a;
● Declares integer a and pointer b that stores address of a.
b) int p, *p;
● Invalid: Redeclaring p as both int and pointer leads to error.
c) char *s;
● Declares a pointer s that can point to a character or string.
24. What is a pointer to a structure in C? Explain with an example program how to
access structure members using a pointer.
Answer:
● A pointer to a structure stores the address of a structure variable.
● Access members using -> operator.
Example:
#include <stdio.h>
struct Book {
int id;
char title[20];
};
int main() {
struct Book b = {101, "C Programming"};
struct Book *ptr = &b;
printf("%d %s\n", ptr->id, ptr->title);
return 0;
25. Explain the purpose and working of malloc(), calloc(), realloc(), and free()
functions in C with suitable examples.
Answer:
26. What is dynamic memory allocation in C? How does it differ from static memory
allocation? Explain with an example.
Answer:
27. Write a C program to dynamically allocate memory for an array of integers, take
input values from the user, and print the array. Use malloc() for allocation.
Answer:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter size: ");
scanf("%d", &n);
int *arr = (int *)malloc(n * sizeof(int));
if(arr == NULL) {
printf("Memory not allocated.\n");
return 1;
printf("Enter %d elements:\n", n);
for(int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Array: ");
for(int i = 0; i < n; i++)
printf("%d ", arr[i]);
free(arr); // deallocating memory
return 0;
28. What are the consequences of not using free() after dynamic memory allocation in
C?
Answer:
● Memory leaks: Allocated memory stays reserved.
● Heap overflow: System may run out of memory.
● Reduced performance: Wasted memory can't be reused.
● Unpredictable behavior: Over time, leads to crashes or slowdowns.
29. What are the differences between malloc() and calloc() in C?
Answer:
30. What is dynamic memory allocation? Why is it needed?
Answer:
● Dynamic memory allocation: Allocating memory during runtime using functions like
malloc(), calloc().
Need:
● When size of data is unknown in advance.
● Efficient use of memory.
● Useful in data structures like linked lists, trees, etc.
31. Explain the different modes of opening a file with an example.
Answer:
Example:
FILE *fp = fopen("data.txt", "r"); // opens file for reading
32. Explain any 5 file handling functions in C.
Answer:
33. Write a program to read data from the keyboard, write it to a file called INPUT,
again read the same data from the INPUT file, and display it on the screen.
Answer:
#include <stdio.h>
int main() {
FILE *fp;
char data[100];
// Writing to file
fp = fopen("INPUT.txt", "w");
printf("Enter text: ");
fgets(data, sizeof(data), stdin);
fputs(data, fp);
fclose(fp);
// Reading from file
fp = fopen("INPUT.txt", "r");
printf("\nData from file:\n");
fgets(data, sizeof(data), fp);
printf("%s", data);
fclose(fp);
return 0;
34. How can you perform read and write operations on an unformatted data file in C?
Answer:
#include <stdio.h>
int main() {
FILE *fp;
int arr[5] = {1, 2, 3, 4, 5}, readArr[5];
fp = fopen("data.bin", "wb");
fwrite(arr, sizeof(int), 5, fp);
fclose(fp);
fp = fopen("data.bin", "rb");
fread(readArr, sizeof(int), 5, fp);
fclose(fp);
for(int i = 0; i < 5; i++)
printf("%d ", readArr[i]);
return 0;
35. When a program is terminated, all the files used by it are automatically closed.
Why is it then necessary to close a file during execution of the program?
Answer:
Even though files are closed when the program exits:
● It ensures data is written (flushes buffers).
● Frees system resources (memory, file descriptors).
● Prevents data loss or corruption.
● Good practice and helps avoid file handling errors in large programs.
36. Write any three file-handling functions in C.
Answer:
fopen() – Opens a file.
fclose() – Closes an open file.
fgets() – Reads a line of text from a file.
37. Write a program in C to copy the contents of one file into another.
Answer:
#include <stdio.h>
int main() {
FILE *src, *dest;
char ch;
src = fopen("source.txt", "r");
dest = fopen("copy.txt", "w");
if (src == NULL || dest == NULL) {
printf("File error.");
return 1;
while ((ch = fgetc(src)) != EOF)
fputc(ch, dest);
printf("File copied successfully.\n");
fclose(src);
fclose(dest);
return 0;
38. Write a C program to count the number of lines in a text file.
Answer:
#include <stdio.h>
int main() {
FILE *fp = fopen("file.txt", "r");
char ch;
int lines = 0;
if (fp == NULL) {
printf("Cannot open file.\n");
return 1;
while ((ch = fgetc(fp)) != EOF) {
if (ch == '\n')
lines++;
}
fclose(fp);
printf("Number of lines: %d\n", lines + 1); // +1 for last line
return 0;
39. Write a C program to replace vowels in a text file with the character ‘x’.
Answer:
#include <stdio.h>
#include <ctype.h>
int isVowel(char ch) {
ch = tolower(ch);
return (ch == 'a'|| ch == 'e'|| ch == 'i'|| ch == 'o'|| ch == 'u');
int main() {
FILE *in = fopen("input.txt", "r");
FILE *out = fopen("output.txt", "w");
char ch;
if (!in || !out) {
printf("File error.\n");
return 1;
}
while ((ch = fgetc(in)) != EOF) {
if (isVowel(ch))
fputc('x', out);
else
fputc(ch, out);
fclose(in);
fclose(out);
printf("Vowels replaced successfully.\n");
return 0;
40. Explain the use of fseek() and ftell() in file handling.
Answer:
fseek(FILE *stream, long offset, int origin)
Moves the file pointer to a specific position.
● SEEK_SET: from beginning
● SEEK_CUR: from current position
● SEEK_END: from end
ftell(FILE *stream)
Returns the current position of the file pointer.
Example:
#include <stdio.h>
int main() {
FILE *fp = fopen("test.txt", "r");
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
printf("File size: %ld bytes\n", size);
fclose(fp);
return 0;
41. What is the difference between fgets() and fscanf() for reading a file?
Answer:
42. What is the purpose of the FILE pointer in C?
Answer:
A FILE * is a pointer to an internal structure that holds information about a file.
It is used to:
● Connect C programs to files.
● Keep track of the file’s status (position, mode, buffer, etc.).
● Perform operations like read, write, seek, and close.
Example:
FILE *fp = fopen("file.txt", "r");
43. Write a C program to open a text file, move the file pointer to a specific position
using fseek(), and display the content from that position.
Answer:
#include <stdio.h>
int main() {
FILE *fp = fopen("sample.txt", "r");
char ch;
if (fp == NULL) {
printf("File cannot be opened.\n");
return 1;
}
fseek(fp, 10, SEEK_SET); // Move to 11th character
printf("Content from position 10:\n");
while ((ch = fgetc(fp)) != EOF)
putchar(ch);
fclose(fp);
return 0;
44. Write a program to open a file named INVENTORY and store in it item details, then
read and display them.
Answer:
#include <stdio.h>
struct Item {
int id;
char name[20];
float price;
};
int main() {
struct Item it;
FILE *fp = fopen("INVENTORY.txt", "w");
printf("Enter item ID, name, and price: ");
scanf("%d %s %f", &it.id, it.name, &it.price);
fprintf(fp, "%d %s %.2f\n", it.id, it.name, it.price);
fclose(fp);
fp = fopen("INVENTORY.txt", "r");
printf("\nItem details from file:\n");
fscanf(fp, "%d %s %f", &it.id, it.name, &it.price);
printf("ID: %d\nName: %s\nPrice: %.2f\n", it.id, it.name, it.price);
fclose(fp);
return 0;
45. Write a C program which computes the factorial of a given number and write the
result to a file named factorial.
Answer:
#include <stdio.h>
int main() {
int n, i;
long long fact = 1;
FILE *fp = fopen("factorial.txt", "w");
printf("Enter a number: ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
fact *= i;
fprintf(fp, "Factorial of %d is %lld\n", n, fact);
fclose(fp);
printf("Factorial written to file.\n");
return 0;
46. Is it possible to read from and write to the same file without resetting the file
pointer? Justify your answer.
Answer:
Yes, but it must be opened in read/write mode ("r+", "w+", or "a+").
You must move the file pointer using fseek() before switching between reading and
writing.
Why?: Because the buffer doesn't automatically switch modes.
Example:
FILE *fp = fopen("file.txt", "r+");
fseek(fp, 0, SEEK_END); // Move to end before writing
fputs("New data", fp);
47. Explain the purpose of ftell(fp) in C. If ftell(fp) returns 50, what does this indicate?
Answer:
ftell(fp) returns the current position of the file pointer in bytes from the start.
If ftell(fp) returns 50, it means the pointer is at the 50th byte of the file.
48. Explain the purpose and usage of the fseek() and fwrite() functions in file
handling.
Answer:
fseek(FILE *fp, long offset, int origin):
● Moves the file pointer to a specific location.
● origin can be:
○ SEEK_SET: Beginning of file
○ SEEK_CUR: Current position
○ SEEK_END: End of file
fwrite():
● Writes raw (binary) data to a file.
● Syntax: fwrite(&data, sizeof(data_type), count, fp);
Example:
int arr[] = {1, 2, 3};
FILE *fp = fopen("file.bin", "wb");
fwrite(arr, sizeof(int), 3, fp);
fclose(fp);