0% found this document useful (0 votes)
19 views29 pages

ilovepdf_merged (3)

Uploaded by

promita0769
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views29 pages

ilovepdf_merged (3)

Uploaded by

promita0769
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

C Programming Question Bank Answers

General Concepts
1. What is BIOS?
BIOS (Basic Input/Output System) is firmware stored on a small memory chip
on the motherboard. It’s the first software that runs when a computer starts
up. It performs hardware initialization during the booting process and provides
runtime services for operating systems and programs. The BIOS maintains
settings through a complementary metal-oxide-semiconductor (CMOS) chip.

2. Different Stages of Booting


1. Power-On Self-Test (POST)
• Checks hardware components functionality
• Verifies system memory and hardware components
2. BIOS Stage
• Loads and executes BIOS from ROM
• Performs additional hardware checks
3. Bootstrap Loader
• Locates and loads operating system kernel
• Transfers control to the operating system
4. Operating System Loading
• Kernel initializes
• Drivers and system services start
• User interface becomes available

3. What is an Operating System (OS)?


An Operating System is system software that manages computer hardware, soft-
ware resources, and provides common services for computer programs. It acts as
an intermediary between computer hardware and the user, handling tasks like
memory management, process management, file management, and input/output
operations.

4. Functionalities of an OS
• Process Management: Creates, schedules, and terminates processes
• Memory Management: Allocates and deallocates memory to programs
• File System Management: Handles file operations and storage
• Device Management: Controls input/output devices
• Security Management: Provides security and access control
• User Interface: Provides interface between user and computer
• Network Management: Handles network connections and protocols

1
5. Different Types of Number Systems
1. Binary (Base-2): Uses 0 and 1
2. Octal (Base-8): Uses digits 0-7
3. Decimal (Base-10): Uses digits 0-9
4. Hexadecimal (Base-16): Uses digits 0-9 and letters A-F

6. Conversions between Number Systems


a. Converting 786 (decimal) to octal and hexadecimal:
• To Octal: 786�� = 1422�
• To Hexadecimal: 786�� = 312��
b. Converting 1011101 (binary) to decimal: 1011101� = 1×2� + 0×2� + 1×2�
+ 1×2³ + 1×2² + 0×2¹ + 1×2� = 64 + 0 + 16 + 8 + 4 + 0 + 1 = 93��
c. Converting 1011010.0001 (binary) to decimal: 1011010.0001� = 64 + 0 +
16 + 8 + 0 + 2 + 0 + 0.0625 = 90.0625��
d. Converting 675AB (hexadecimal) to decimal: 675AB�� = 6×16� + 7×16³
+ 5×16² + 10×16¹ + 11×16� = 6×65536 + 7×4096 + 5×256 + 10×16 +
11 = 421291��

7. Differences between Compiler and Interpreter


Compiler: - Translates entire source code to machine code at once - Creates
executable file - Faster execution - Memory efficient - Shows all errors at once
Interpreter: - Translates and executes code line by line - No separate executable
file - Slower execution - Less memory efficient - Shows errors one at a time

8. Why is C Called a High-Level Language?


C is called a high-level language because: - It’s machine-independent and
portable - Uses English-like syntax - Supports structured programming - Has
built-in functions and libraries - Abstracts low-level hardware details However,
C is often considered a mid-level language as it also provides low-level access
to memory and hardware.

9. Define Identifiers
Identifiers are names given to variables, functions, arrays, classes, etc. in a
program. Rules for identifiers: - Must start with letter or underscore - Can
contain letters, digits, and underscores - Case-sensitive - Cannot use keywords
- No special characters except underscore

10. Ranges of Data Types


• int: -2,147,483,648 to 2,147,483,647 (4 bytes)

2
• short: -32,768 to 32,767 (2 bytes)
• long: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (8 bytes)
• float: 1.2E-38 to 3.4E+38 (4 bytes)
• double: 2.2E-308 to 1.8E+308 (8 bytes)

11. What is an Algorithm?


An algorithm is a step-by-step procedure or formula for solving a problem. Char-
acteristics: - Input: Zero or more inputs - Output: At least one output - Defi-
niteness: Clear and unambiguous steps - Finiteness: Must terminate after finite
number of steps - Effectiveness: Basic enough to be carried out - Independence:
Should work for different inputs

12. Asymptotic Notations of Time Complexity


1. Big O (O) - Upper bound
• Represents worst-case complexity
• Example: O(n²) for bubble sort
2. Omega (Ω) - Lower bound
• Represents best-case complexity
• Example: Ω(n) for bubble sort
3. Theta (Θ) - Tight bound
• Average case complexity
• When upper and lower bounds are same

13. Operator Precedence Rules


From highest to lowest: 1. () [] -> . 2. ! ~ ++ – + - * & (type) sizeof 3. * / %
4. + - 5. « » 6. < <= > >= 7. == != 8. & 9. ^ 10. | 11. && 12. || 13. ?: 14.
= += -= *= /= %= &= ^= |= «= »= 15. ,

C Programming Basics
14. C Program for Bitwise Operations
#include <stdio.h>

int main() {
int a = 12; // 1100 in binary
int b = 25; // 11001 in binary

printf("AND: %d\n", a & b); // Bitwise AND


printf("OR: %d\n", a | b); // Bitwise OR
printf("XOR: %d\n", a ^ b); // Bitwise XOR
printf("Left Shift: %d\n", a << 2); // Left shift
printf("Right Shift: %d\n", a >> 2); // Right shift
printf("Complement: %d\n", ~a); // Bitwise NOT

3
return 0;
}

15. Preprocessor Directives


a. Role of preprocessor directives:
• File inclusion (#include)
• Macro definitions (#define)
• Conditional compilation (#ifdef, #ifndef)
• File inclusion guards
• Pragma directives
b. Differences between Linker and Loader:
Linker: - Combines object files - Resolves references - Creates executable - Works
before execution
Loader: - Loads program into memory - Allocates memory - Performs relocation
- Works during execution

16. C Program for Input/Output without scanf/printf


#include <unistd.h>

int main() {
char buffer[100];
write(1, "Enter text: ", 11);
read(0, buffer, 100);
write(1, "You entered: ", 12);
write(1, buffer, 100);
return 0;
}

17. Storage Classes in C


1. auto
• Default storage class
• Local variables
• Block scope
2. static
• Retains value between function calls
• File scope for global variables
3. register
• Stored in CPU registers
• Faster access
4. extern

4
• Global scope
• Multiple file access
Example program:
#include <stdio.h>

static int count = 0; // static global variable

void increment() {
static int i = 0; // static local variable
auto int j = 0; // automatic variable
i++;
j++;
count++;
printf("i=%d, j=%d, count=%d\n", i, j, count);
}

int main() {
for(int k = 0; k < 3; k++)
increment();
return 0;
}

18. Default Value of Static Variable


Static variables are automatically initialized to zero (0) if no explicit initializa-
tion is provided.

19. Function and Its Importance


A function is a self-contained block of code that performs a specific task.
Importance: - Code reusability - Modularity - Better organization - Easier main-
tenance - Reduced code duplication - Better debugging - Abstraction

20. Function Prototype


A function prototype is a declaration of a function that specifies function name,
return type, and parameters without the function body. Example:
int sum(int a, int b); // function prototype

21. Call-by-Value and Call-by-Reference Program


#include <stdio.h>

// Call by value
void swapByValue(int a, int b) {

5
int temp = a;
a = b;
b = temp;
}

// Call by reference
void swapByReference(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x = 10, y = 20;

printf("Before swap: x=%d, y=%d\n", x, y);

swapByValue(x, y);
printf("After swap by value: x=%d, y=%d\n", x, y);

swapByReference(&x, &y);
printf("After swap by reference: x=%d, y=%d\n", x, y);

return 0;
}

Recursion
23. What is Recursion?
Recursion is a programming concept where a function calls itself to solve a
smaller instance of the same problem. It consists of: - Base case (termination
condition) - Recursive case - Progress toward base case

24. Recursive Programs


a. Tower of Hanoi:
#include <stdio.h>

void towerOfHanoi(int n, char source, char auxiliary, char destination) {


if (n == 1) {
printf("Move disk 1 from %c to %c\n", source, destination);
return;
}
towerOfHanoi(n-1, source, destination, auxiliary);
printf("Move disk %d from %c to %c\n", n, source, destination);

6
towerOfHanoi(n-1, auxiliary, source, destination);
}

int main() {
int n = 3;
towerOfHanoi(n, 'A', 'B', 'C');
return 0;
}
b. Factorial:
#include <stdio.h>

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

int main() {
int n = 5;
printf("Factorial of %d is %d\n", n, factorial(n));
return 0;
}
c. Fibonacci Series:
#include <stdio.h>

int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n-1) + fibonacci(n-2);
}

int main() {
int n = 10;
for(int i = 0; i < n; i++)
printf("%d ", fibonacci(i));
return 0;
}

Arrays
25. Array and Data Structure
An array is a collection of similar data elements stored in contiguous memory
locations. It’s called a data structure because: - Organizes data in a structured

7
way - Provides efficient access to elements - Allows operations like insertion,
deletion - Supports various algorithms - Enables complex data manipulation

26. Program to Print First 10 Natural Numbers


#include <stdio.h>

int main() {
int arr[10];

// Store numbers
for(int i = 0; i < 10; i++)
arr[i] = i + 1;

// Print numbers
for(int i = 0; i < 10; i++)
printf("%d ", arr[i]);

return 0;
}

27. Program to Find Largest and Smallest Number


#include <stdio.h>

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);

int max = arr[0], min = arr[0];

for(int i = 1; i < n; i++) {


if(arr[i] > max)
max = arr[i];
if(arr[i] < min)
min = arr[i];
}

printf("Largest: %d\nSmallest: %d\n", max, min);


return 0;
}

28. Program to Insert and Delete Elements


#include <stdio.h>

void insert(int arr[], int *n, int pos, int value) {

8
for(int i = *n; i > pos; i--)
arr[i] = arr[i-1];
arr[pos] = value;
(*n)++;
}

void delete(int arr[], int *n, int pos) {


for(int i = pos; i < *n-1; i++)
arr[i] = arr[i+1];
(*n)--;
}

int main() {
int arr[100] = {1, 2, 3, 4, 5};
int n = 5;

// Insert 10 at position 2
insert(arr, &n, 2, 10);

// Delete element at position 3


delete(arr, &n, 3);

// Print array
for(int i = 0; i < n; i++)
printf("%d ", arr[i]);

return 0;
}

29. Program to Find First Two Largest Numbers


#include <stdio.h>

int main() {
int arr[] = {12, 35, 1, 10, 34, 1};
int n = sizeof(arr)/sizeof(arr[0]);
int first = arr[0], second = -1;

for(int i = 1; i < n; i++) {


if(arr[i] > first) {
second = first;
first = arr[i];
}
else if(arr[i] > second && arr[i] < first) {
second = arr[i];
}

9
}

printf("First largest: %d\nSecond largest: %d\n", first, second);


return 0;
}

30. Program to Remove Duplicates


“‘c #include <stdio.h>
int main() { int arr[] = {1, 2, 2, 3, 4, 4,

10
30. Program to Remove Duplicates (continued)
#include <stdio.h>

int main() {
int arr[] = {1, 2, 2, 3, 4, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
int j = 0;

// Remove duplicates
for(int i = 0; i < n-1; i++) {
if(arr[i] != arr[i+1]) {
arr[j] = arr[i];
j++;
}
}
arr[j] = arr[n-1];

// Print array
for(int i = 0; i <= j; i++)
printf("%d ", arr[i]);

return 0;
}

31. Program to Separate Odd and Even Numbers


#include <stdio.h>

int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = sizeof(arr)/sizeof(arr[0]);
int odd[50], even[50];
int o = 0, e = 0;

for(int i = 0; i < n; i++) {


if(arr[i] % 2 == 0)
even[e++] = arr[i];
else
odd[o++] = arr[i];
}

printf("Even numbers: ");


for(int i = 0; i < e; i++)
printf("%d ", even[i]);

1
printf("\nOdd numbers: ");
for(int i = 0; i < o; i++)
printf("%d ", odd[i]);

return 0;
}

32. Program to Count Repeated Elements


#include <stdio.h>

int main() {
int arr[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
int n = sizeof(arr)/sizeof(arr[0]);

for(int i = 0; i < n; i++) {


int count = 1;
if(arr[i] != -1) {
for(int j = i+1; j < n; j++) {
if(arr[i] == arr[j]) {
count++;
arr[j] = -1;
}
}
if(count > 1)
printf("%d appears %d times\n", arr[i], count);
}
}
return 0;
}

33. Program to Count Non-Repeated Elements


#include <stdio.h>

int main() {
int arr[] = {1, 2, 2, 3, 3, 3, 4, 5, 6, 6};
int n = sizeof(arr)/sizeof(arr[0]);
int count = 0;

for(int i = 0; i < n; i++) {


int j;
for(j = 0; j < n; j++) {
if(i != j && arr[i] == arr[j])
break;
}

2
if(j == n)
count++;
}

printf("Number of non-repeated elements: %d\n", count);


return 0;
}

34. Program to Split Array and Add First Part to End


#include <stdio.h>

void splitArray(int arr[], int n, int position) {


// Store first position elements
int temp[position];
for(int i = 0; i < position; i++)
temp[i] = arr[i];

// Shift remaining elements


for(int i = 0; i < n-position; i++)
arr[i] = arr[i+position];

// Add first part to end


for(int i = 0; i < position; i++)
arr[n-position+i] = temp[i];
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
int position = 2;

splitArray(arr, n, position);

for(int i = 0; i < n; i++)


printf("%d ", arr[i]);

return 0;
}

35. Program to Search Element in Array


#include <stdio.h>

// Linear Search
int linearSearch(int arr[], int n, int key) {

3
for(int i = 0; i < n; i++) {
if(arr[i] == key)
return i;
}
return -1;
}

// Binary Search (for sorted array)


int binarySearch(int arr[], int left, int right, int key) {
while(left <= right) {
int mid = left + (right - left) / 2;

if(arr[mid] == key)
return mid;

if(arr[mid] < key)


left = mid + 1;
else
right = mid - 1;
}
return -1;
}

int main() {
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/sizeof(arr[0]);
int key = 10;

int result = linearSearch(arr, n, key);


printf("Linear Search: Element found at index %d\n", result);

result = binarySearch(arr, 0, n-1, key);


printf("Binary Search: Element found at index %d\n", result);

return 0;
}

36. Program for 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

4
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);

bubbleSort(arr, n);

printf("Sorted array: ");


for(int i = 0; i < n; i++)
printf("%d ", arr[i]);

return 0;
}

37. Program to Find K-th Largest Element


#include <stdio.h>

void sort(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]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

int main() {
int arr[] = {12, 3, 5, 7, 19};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 2;

sort(arr, n);

printf("%dth largest element is %d\n", k, arr[k-1]);


return 0;

5
}

38. Program to Print Alternate Elements


#include <stdio.h>

int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = sizeof(arr)/sizeof(arr[0]);

printf("Alternate elements: ");


for(int i = 0; i < n; i += 2)
printf("%d ", arr[i]);

return 0;
}

39. Programs for Matrix Operations


#include <stdio.h>

#define N 3

// Matrix Addition
void addMatrix(int A[][N], int B[][N], int C[][N]) {
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++)
C[i][j] = A[i][j] + B[i][j];
}

// Matrix Multiplication
void multiplyMatrix(int A[][N], int B[][N], int C[][N]) {
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
C[i][j] = 0;
for(int k = 0; k < N; k++)
C[i][j] += A[i][k] * B[k][j];
}
}
}

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

6
int B[N][N] = {{1, 0, 0},
{0, 1, 0},
{0, 0, 1}};

int C[N][N];

addMatrix(A, B, C);
multiplyMatrix(A, B, C);

return 0;
}

40. Program Passing Arrays to Functions


#include <stdio.h>

// Function taking 1D array


void process1DArray(int arr[], int n) {
for(int i = 0; i < n; i++)
arr[i] *= 2;
}

// Function taking 2D array


void process2DArray(int arr[][3], int rows) {
for(int i = 0; i < rows; i++)
for(int j = 0; j < 3; j++)
arr[i][j] += 1;
}

int main() {
int arr1D[] = {1, 2, 3, 4, 5};
int arr2D[][3] = {{1, 2, 3},
{4, 5, 6}};

process1DArray(arr1D, 5);
process2DArray(arr2D, 2);

return 0;
}

Pointers
41. Pointers and Pointer Arithmetic
#include <stdio.h>

int main() {

7
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr;

// Basic pointer operations


printf("Value at ptr: %d\n", *ptr);
printf("Value at ptr+1: %d\n", *(ptr+1));

// Increment/decrement
ptr++; // moves to next integer
ptr--; // moves back

// Array indexing
printf("Third element: %d\n", ptr[2]);

return 0;
}

42. Dynamic Memory Allocation


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

int main() {
// malloc
int *ptr1 = (int*)malloc(5 * sizeof(int));

// calloc
int *ptr2 = (int*)calloc(5, sizeof(int));

// realloc
ptr1 = (int*)realloc(ptr1, 10 * sizeof(int));

// free memory
free(ptr1);
free(ptr2);

return 0;
}

43. Array of Pointers


#include <stdio.h>

int main() {
int *arr[3];
int a = 10, b = 20, c = 30;

8
arr[0] = &a;
arr[1] = &b;
arr[2] = &c;

for(int i = 0; i < 3; i++)


printf("%d ", *arr[i]);

return 0;
}

44. Null Pointer


A null pointer is a pointer that doesn’t point to any memory location. It is
initialized to NULL or 0.
#include <stdio.h>

int main() {
int *ptr = NULL;

if(ptr == NULL)
printf("This is a null pointer\n");

return 0;
}

Structures and Unions


45. Structure and Array Differences
Structure: - Collection of different data types - Members stored in contiguous
memory - Accessed using dot operator - Each member has fixed offset
Array of Structures vs Arrays within Structure: - Array of structures: Multiple
instances of same structure - Arrays within structure: Array members within
single structure

46. Structure Variables


#include <stdio.h>

struct Point {
int x;
int y;
} p1, p2; // p1 and p2 are structure variables

int main() {

9
p1.x = 10;
p1.y = 20;

struct Point p3 = {30, 40}; // Another way to declare

return 0;
}

47. Arrays vs Structures


Arrays: - Homogeneous elements - Indexed access - Contiguous memory - Fixed
size
Structures: - Heterogeneous elements - Named member access - May have
padding - Flexible member types

48. Enum Datatype


#include <stdio.h>

enum Days {
SUNDAY = 1,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
};

int main() {
enum Days today = WEDNESDAY;
printf("Day number: %d\n", today);
return 0;
}

49. fflush(stdin)
fflush(stdin) is used to clear the input buffer. It’s commonly used before reading
character input to prevent buffer issues.

50. typedef Operator


#include <stdio.h>

typedef struct {
int x;

10
int y;
} Point;

typedef int Integer;

int main() {
Point p1;
Integer i = 10;
return 0;
}

51. Student Structure Program


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

struct Student {
char name[50];
int roll;
int age;
};

int main() {
struct Student s1;

strcpy(s1.name, "John");
s1.roll = 1;
s1.age = 20;

printf("Name: %s\n", s1.name);


printf("Roll: %d\n", s1.roll);
printf("Age: %d\n", s1.age);

return 0;
}

52. Array of Structures


struct Student {
char name[50];
int roll;
float marks;
};

struct Student students[10]; // Array of 10 student structures

11
53. Employee Records Program
“‘c #include <stdio.h> #include <string.h>
struct Employee { int id; char name[50]; float salary; };
int main() { struct Employee emp[10];
// Input data
for(int i = 0; i < 10; i++) {
printf("Enter employee details:\n");
scanf("%d %s %f", &emp[i].id, emp[i].name,

12
53. Employee Records Program (continued)
#include <stdio.h>
#include <string.h>

struct Employee {
int id;
char name[50];
float salary;
};

int main() {
struct Employee emp[10];

// Input data
for(int i = 0; i < 10; i++) {
printf("Enter employee details:\n");
scanf("%d %s %f", &emp[i].id, emp[i].name, &emp[i].salary);
}

// Display data
printf("\nEmployee Records:\n");
for(int i = 0; i < 10; i++) {
printf("ID: %d\n", emp[i].id);
printf("Name: %s\n", emp[i].name);
printf("Salary: %.2f\n\n", emp[i].salary);
}

return 0;
}

54. Self-Referential Structure


A self-referential structure contains a pointer to a structure variable of the same
type.
#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next; // Self-referential pointer
};

int main() {
struct Node* head = NULL;
head = (struct Node*)malloc(sizeof(struct Node));

1
head->data = 1;
head->next = NULL;

return 0;
}

55. Nested Structures and Passing Structures to Functions


#include <stdio.h>

struct Address {
char street[50];
char city[30];
char state[20];
};

struct Employee {
int id;
char name[50];
struct Address addr; // Nested structure
};

// Function taking structure as parameter


void printEmployee(struct Employee emp) {
printf("ID: %d\n", emp.id);
printf("Name: %s\n", emp.name);
printf("Address: %s, %s, %s\n",
emp.addr.street,
emp.addr.city,
emp.addr.state);
}

// Function taking structure pointer


void updateSalary(struct Employee* emp) {
// Access members using arrow operator
emp->id = 100;
}

int main() {
struct Employee e1 = {1, "John", {"123 St", "NYC", "NY"}};
printEmployee(e1);
updateSalary(&e1);
return 0;
}

2
56. Differences between Unions and Structures
Structures: - All members have their own memory space - Can access all mem-
bers simultaneously - Size is sum of all member sizes (with padding) - Used
when all members are needed
Unions: - All members share same memory space - Can access only one member
at a time - Size is the largest member size - Used when only one member is
needed at a time

File Handling
57. File Handling Programs
a. Creating and Opening Files:
#include <stdio.h>

int main() {
FILE *fp;

// Create new file


fp = fopen("test.txt", "w");
if(fp == NULL) {
printf("Error creating file!");
return 1;
}

// Write to file
fprintf(fp, "Hello, World!\n");

// Close file
fclose(fp);

// Open existing file


fp = fopen("test.txt", "r");
if(fp == NULL) {
printf("Error opening file!");
return 1;
}

fclose(fp);
return 0;
}
b. Reading from File:
#include <stdio.h>

3
int main() {
FILE *fp;
char buffer[100];

fp = fopen("test.txt", "r");
if(fp == NULL) {
printf("Error opening file!");
return 1;
}

// Read line by line


while(fgets(buffer, 100, fp) != NULL) {
printf("%s", buffer);
}

fclose(fp);
return 0;
}
c. Writing to File:
#include <stdio.h>

int main() {
FILE *fp;

fp = fopen("test.txt", "w");
if(fp == NULL) {
printf("Error opening file!");
return 1;
}

fprintf(fp, "Line 1\n");


fputs("Line 2\n", fp);
fputc('A', fp);

fclose(fp);
return 0;
}

58. Advanced File Operations Programs


a. File Creation and Deletion:
#include <stdio.h>

int main() {

4
// Create file
FILE *fp = fopen("newfile.txt", "w");
if(fp != NULL) {
fprintf(fp, "New file content\n");
fclose(fp);
}

// Delete file
if(remove("newfile.txt") == 0)
printf("File deleted successfully\n");
else
printf("Error deleting file\n");

return 0;
}
b. File Operations (Read, Write, Append):
#include <stdio.h>

int main() {
FILE *fp;
char buffer[100];

// Write mode
fp = fopen("file.txt", "w");
fprintf(fp, "Initial content\n");
fclose(fp);

// Append mode
fp = fopen("file.txt", "a");
fprintf(fp, "Appended content\n");
fclose(fp);

// Read mode
fp = fopen("file.txt", "r");
while(fgets(buffer, 100, fp))
printf("%s", buffer);
fclose(fp);

return 0;
}
c. Count, Convert, Replace, and Reverse Operations:
#include <stdio.h>
#include <string.h>
#include <ctype.h>

5
// Count characters in file
int countChars(FILE *fp) {
int count = 0;
char ch;
while((ch = fgetc(fp)) != EOF)
count++;
return count;
}

// Convert file content to uppercase


void convertToUpper(FILE *fp) {
char ch;
FILE *temp = fopen("temp.txt", "w");

while((ch = fgetc(fp)) != EOF)


fputc(toupper(ch), temp);

fclose(temp);
}

// Replace character in file


void replaceChar(FILE *fp, char old, char new) {
char ch;
FILE *temp = fopen("temp.txt", "w");

while((ch = fgetc(fp)) != EOF) {


if(ch == old)
fputc(new, temp);
else
fputc(ch, temp);
}

fclose(temp);
}

// Reverse file content


void reverseFile(FILE *fp) {
fseek(fp, 0, SEEK_END);
long size = ftell(fp);

char *buffer = (char*)malloc(size + 1);

for(long i = size - 1; i >= 0; i--) {


fseek(fp, i, SEEK_SET);
buffer[size - 1 - i] = fgetc(fp);

6
}
buffer[size] = '\0';

fp = freopen(NULL, "w", fp);


fprintf(fp, "%s", buffer);
free(buffer);
}

int main() {
FILE *fp = fopen("test.txt", "r+");
if(fp == NULL) return 1;

printf("Character count: %d\n", countChars(fp));


convertToUpper(fp);
replaceChar(fp, 'a', 'x');
reverseFile(fp);

fclose(fp);
return 0;
}
This completes the comprehensive answer key for all questions in the C program-
ming question bank. Each program includes proper error handling, comments,
and demonstrates the key concepts being tested. The programs can be used as
reference material for learning and practice.

You might also like