Contents
Beginner-Level Questions ............................................................................................................................ 8
1. Sum of Two Numbers ........................................................................................................................... 8
Code: ..................................................................................................................................................... 8
Explanation: .......................................................................................................................................... 8
2. Even or Odd Check ............................................................................................................................... 8
Explanation: .......................................................................................................................................... 9
3. Print First 10 Natural Numbers ............................................................................................................. 9
Explanation: .......................................................................................................................................... 9
4. Factorial of a Number ......................................................................................................................... 10
Explanation: ........................................................................................................................................ 10
5. Swap Two Numbers Without a Third Variable .................................................................................. 10
Explanation: ........................................................................................................................................ 11
6. Simple Calculator................................................................................................................................ 11
Explanation: ........................................................................................................................................ 12
Intermediate-Level Questions ..................................................................................................................... 12
7. Palindrome Check ............................................................................................................................... 12
Explanation: ........................................................................................................................................ 13
8. Fibonacci Series .................................................................................................................................. 13
Explanation: ........................................................................................................................................ 13
9. Reverse an Integer............................................................................................................................... 14
Explanation: ........................................................................................................................................ 14
10. Sum of Digits .................................................................................................................................... 14
Explanation: ........................................................................................................................................ 15
Advanced-Level Questions ......................................................................................................................... 15
14. Swap Using Pointers ......................................................................................................................... 15
Explanation: ........................................................................................................................................ 15
15. Dynamic Memory Allocation ........................................................................................................... 16
Explanation: ........................................................................................................................................ 16
16. File Handling (Count Words) ........................................................................................................... 17
Explanation: ........................................................................................................................................ 17
1. Enumeration (enum) ............................................................................................................................... 18
Q1: Define an enum for the days of the week and print the integer values of Monday and Friday. .. 18
Q2: Create an enum for traffic light colors and print a message based on the selected color............. 18
Q3: Use an enum for user access levels and display the access level name based on a user input
value. ................................................................................................................................................... 19
2. Structures (struct) .................................................................................................................................... 19
Q4: Define a struct to store a student's name, roll number, and marks. .............................................. 19
Q5: Store and display details of 5 employees using an array of structures. ........................................ 20
3. Unions (union) ........................................................................................................................................ 21
Q7: Define a union and assign values to its members. ....................................................................... 21
4. Strings (char arrays) ................................................................................................................................ 22
Q10: Count vowels and consonants in a string. .................................................................................. 22
5. Pointers ................................................................................................................................................... 23
Q15: Swap two numbers using pointers.............................................................................................. 23
Q16: Allocate memory dynamically for an array using malloc(). ...................................................... 23
6. Functions ................................................................................................................................................. 24
Q20: Find factorial using recursion. ................................................................................................... 24
Q21: Greatest of three numbers. ......................................................................................................... 25
1. Enumeration (enum) ............................................................................................................................... 26
Q25: Create an enum for different programming languages and use it in a function to print the
language name. ................................................................................................................................... 26
2. Structures (struct) .................................................................................................................................... 27
Q26: Create a struct for a car with fields: brand, year, and price. Use an array of structures for 3 cars
and display their details....................................................................................................................... 27
3. Unions (union) ........................................................................................................................................ 28
Q27: Create a union for different data types and show memory size before and after storing values.
............................................................................................................................................................ 28
4. Strings (char arrays) ................................................................................................................................ 29
Q28: Reverse a string without using strrev(). ..................................................................................... 29
5. Pointers ................................................................................................................................................... 30
Q29: Find the largest element in an array using pointers. ................................................................... 30
Q30: Swap two strings using pointers................................................................................................. 30
6. Functions ................................................................................................................................................. 31
Q31: Check if a number is even or odd using a function. ................................................................... 31
Q32: Find the sum of digits of a number using recursion. .................................................................. 32
Q33: Check if a number is prime using a function. ............................................................................ 32
Q34: Convert Celsius to Fahrenheit using a function. ........................................................................ 33
1. File Handling ...................................................................................................................................... 34
Q35: Write a C program to create and write to a file. ......................................................................... 34
Q36: Read contents from a file and display them. .............................................................................. 35
Q37: Append data to an existing file. ................................................................................................. 36
2. Dynamic Memory Management ......................................................................................................... 36
Q38: Allocate memory dynamically for an array using malloc(). ...................................................... 36
Q39: Use realloc() to increase array size. ........................................................................................... 37
3. Data Structures .................................................................................................................................... 38
Q40: Implement a Singly Linked List................................................................................................. 38
Q41: Implement Stack using an array. ................................................................................................ 40
Q42: Implement a Queue using an array............................................................................................. 42
Q43: Implement Bubble Sort. ............................................................................................................. 43
1. Function to Find Maximum ............................................................................................................ 45
2. Swap Two Numbers using Call by Reference ................................................................................ 45
3. Factorial using Recursion................................................................................................................ 46
4. Check if a Number is Prime ............................................................................................................ 46
5. Reverse an Array using a Function ................................................................................................. 47
6. Function Pointer for Arithmetic Operations ................................................................................... 48
7. Find GCD (Greatest Common Divisor) using Recursion ............................................................... 49
8. Variadic Function to Find Sum ....................................................................................................... 49
9. Return Multiple Values using a Struct ............................................................................................ 50
10. Function to Sort an Array (Bubble Sort) ....................................................................................... 51
1. Basics (Fundamentals) .................................................................................................................... 52
2. Functions & Recursion.................................................................................................................... 53
3. Arrays & Strings ............................................................................................................................. 53
4. Pointers (Very Important!) .............................................................................................................. 53
5. Structures & Unions ........................................................................................................................ 53
6. File Handling .................................................................................................................................. 54
7. Data Structures in C ........................................................................................................................ 54
8. Advanced Topics ............................................................................................................................ 54
1. Start with Small Projects (Beginner Level) .................................................................................... 55
2. Move to Intermediate Projects ........................................................................................................ 55
3. Advanced Projects (Real-World Applications) ............................................................................... 55
4. Game Development in C ................................................................................................................. 55
5. Cybersecurity & System-Level Projects ......................................................................................... 56
Next Steps ........................................................................................................................................... 56
Section 1: Data Types (10 Questions)................................................................................................. 56
Section 2: Operators (10 Questions) ................................................................................................... 57
Section 3: Control Structures (10 Questions) ..................................................................................... 57
Section 4: Input/Output (10 Questions) .............................................................................................. 58
Section 5: Loops and Arrays (10 Questions) ...................................................................................... 58
Section 6: Functions and Pointers (10 Questions) .............................................................................. 59
Section 7: File Handling (10 Questions) ............................................................................................. 59
End of Practical Questions .................................................................................................................. 60
Answers ....................................................................................................................................................... 60
Pointers in C - A Complete Guide ...................................................................................................... 105
1. Introduction to Pointers.................................................................................................................... 105
Declaring and Initializing Pointers..................................................................................................... 105
Printing Values Using Pointers .......................................................................................................... 105
2. Pointer Arithmetic............................................................................................................................. 105
Increment and Decrement ................................................................................................................ 106
Pointer Addition and Subtraction ..................................................................................................... 106
Pointer Difference ............................................................................................................................. 106
3. Pointers and Arrays ........................................................................................................................... 106
Array Name as a Pointer ................................................................................................................... 106
Iterating an Array Using a Pointer..................................................................................................... 107
4. Pointers and Strings .......................................................................................................................... 107
Pointer to a String ............................................................................................................................. 107
Modifying a String Using Pointers..................................................................................................... 107
5. Pointers and Functions ..................................................................................................................... 107
Call by Value vs. Call by Reference.................................................................................................... 107
Swapping Two Numbers Using Pointers (Call by Reference) ............................................................ 108
6. Dynamic Memory Allocation............................................................................................................. 108
Using malloc() ............................................................................................................................. 108
Using calloc() ............................................................................................................................. 108
Using realloc() ........................................................................................................................... 108
Freeing Allocated Memory ............................................................................................................... 108
7. Pointers to Pointers (Double Pointers) ............................................................................................. 109
8. Function Pointers .............................................................................................................................. 109
Declaring and Using Function Pointers ............................................................................................. 109
Function Pointer with Parameters .................................................................................................... 109
Conclusion ............................................................................................................................................. 110
Complete Guide to Arrays and Strings in C ............................................................................................... 110
1. Arrays in C ............................................................................................................................................. 110
1.1 Declaring and Initializing Arrays...................................................................................................... 110
Syntax ................................................................................................................................................ 110
Example ............................................................................................................................................. 110
Initializing Arrays ............................................................................................................................... 110
Accessing Array Elements ................................................................................................................. 110
1.2 Looping Through Arrays .................................................................................................................. 111
Using a for loop .............................................................................................................................. 111
Using a while loop.......................................................................................................................... 111
1.3 Multi-Dimensional Arrays ............................................................................................................... 111
2D Array (Matrix) .............................................................................................................................. 111
Accessing Elements in a 2D Array ..................................................................................................... 111
Looping Through a 2D Array ............................................................................................................. 112
1.4 Passing Arrays to Functions ............................................................................................................ 112
2. Strings in C............................................................................................................................................. 112
2.1 Declaring and Initializing Strings ..................................................................................................... 113
Using Character Arrays ..................................................................................................................... 113
Using Pointers ................................................................................................................................... 113
2.2 Input and Output of Strings ............................................................................................................ 113
Using scanf() and printf() ..................................................................................................... 113
Using gets() and puts() ............................................................................................................ 113
2.3 String Manipulation Functions ........................................................................................................ 113
String Length - strlen() ............................................................................................................... 113
String Copy - strcpy() .................................................................................................................. 114
String Concatenation - strcat() .................................................................................................. 114
String Comparison - strcmp()....................................................................................................... 114
Substring Search - strstr() ......................................................................................................... 114
2.4 Pointers and Strings ........................................................................................................................ 115
3. Dynamic Memory Allocation for Strings ............................................................................................... 115
Conclusion ................................................................................................................................................. 116
1. Functions in C ................................................................................................................................ 116
2. Recursion in C................................................................................................................................ 117
Key Points about Recursion: ............................................................................................................. 118
Practice Exercise: .............................................................................................................................. 118
Basic Concepts in File Handling ......................................................................................................... 118
Opening a File ................................................................................................................................... 118
File Opening Modes .......................................................................................................................... 119
Example: Writing to a File ................................................................................................................. 119
Explanation: ...................................................................................................................................... 119
Reading from a File ........................................................................................................................... 120
Explanation: ...................................................................................................................................... 120
Binary File Handling .......................................................................................................................... 120
Explanation: ...................................................................................................................................... 121
Closing a File...................................................................................................................................... 121
Error Handling ................................................................................................................................... 121
File Handling Functions Summary:.................................................................................................... 121
Practice Exercise: .............................................................................................................................. 122
1. File Positioning Functions ............................................................................................................. 122
2. File Error Handling Functions ........................................................................................................ 124
3. Additional File Handling Functions ............................................................................................... 126
4. Buffering in File I/O ....................................................................................................................... 126
Summary of Additional File Handling Functions: .............................................................................. 127
Practice Exercises: ............................................................................................................................. 128
Basic String Handling in C .................................................................................................................. 128
Common String Functions in C .......................................................................................................... 128
String Tokenization (Tokenizing Strings) ........................................................................................... 133
String Manipulation Summary .......................................................................................................... 133
Practice Exercises: ............................................................................................................................. 134
Sure! I'll go step by step and explain each C program in detail.
Beginner-Level Questions
1. Sum of Two Numbers
Code:
#include <stdio.h>
int main() {
int a, b, sum;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
sum = a + b;
printf("Sum: %d\n", sum);
return 0;
}
Explanation:
Takes two integers as input using scanf().
Adds them and stores the result in sum.
Prints the sum.
2. Even or Odd Check
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num % 2 == 0)
printf("Even\n");
else
printf("Odd\n");
return 0;
}
Explanation:
If a number is divisible by 2, it is even; otherwise, it's odd.
3. Print First 10 Natural Numbers
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++)
printf("%d ", i);
return 0;
}
Explanation:
Uses a for loop to print numbers from 1 to 10.
4. Factorial of a Number
#include <stdio.h>
int main() {
int n, fact = 1;
printf("Enter a number: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++)
fact *= i;
printf("Factorial: %d\n", fact);
return 0;
}
Explanation:
The factorial of n is n * (n-1) * (n-2) * ... * 1.
Uses a loop to multiply fact by each number.
5. Swap Two Numbers Without a Third Variable
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("Swapped: %d %d\n", a, b);
return 0;
}
Explanation:
Swaps two numbers without using a third variable.
Uses addition and subtraction instead.
6. Simple Calculator
#include <stdio.h>
int main() {
char op;
double a, b;
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &op);
printf("Enter two numbers: ");
scanf("%lf %lf", &a, &b);
switch (op) {
case '+': printf("Result: %.2lf\n", a + b); break;
case '-': printf("Result: %.2lf\n", a - b); break;
case '*': printf("Result: %.2lf\n", a * b); break;
case '/': printf("Result: %.2lf\n", a / b); break;
default: printf("Invalid operator\n");
}
return 0;
}
Explanation:
Uses a switch statement to perform basic arithmetic operations.
Intermediate-Level Questions
7. Palindrome Check
#include <stdio.h>
int main() {
int num, rev = 0, temp, digit;
printf("Enter a number: ");
scanf("%d", &num);
temp = num;
while (temp > 0) {
digit = temp % 10;
rev = rev * 10 + digit;
temp /= 10;
}
if (num == rev)
printf("Palindrome\n");
else
printf("Not a palindrome\n");
return 0;
}
Explanation:
A palindrome number reads the same forward and backward.
Reverses the number and checks if it matches the original.
8. Fibonacci Series
#include <stdio.h>
void fibonacci(int n) {
int a = 0, b = 1, next;
for (int i = 0; i < n; i++) {
printf("%d ", a);
next = a + b;
a = b;
b = next;
}
}
int main() {
int n;
printf("Enter number of terms: ");
scanf("%d", &n);
fibonacci(n);
return 0;
}
Explanation:
The Fibonacci sequence starts with 0, 1, and each term is the sum of the previous two.
9. Reverse an Integer
#include <stdio.h>
int main() {
int num, rev = 0;
printf("Enter a number: ");
scanf("%d", &num);
while (num > 0) {
rev = rev * 10 + (num % 10);
num /= 10;
}
printf("Reversed: %d\n", rev);
return 0;
}
Explanation:
Extracts the last digit using % 10, builds the reversed number.
10. Sum of Digits
#include <stdio.h>
int main() {
int num, sum = 0;
printf("Enter a number: ");
scanf("%d", &num);
while (num > 0) {
sum += num % 10;
num /= 10;
}
printf("Sum of digits: %d\n", sum);
return 0;
}
Explanation:
Adds each digit by taking num % 10 and reduces the number by / 10.
Advanced-Level Questions
14. Swap Using Pointers
#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("Swapped: %d %d\n", x, y);
return 0;
}
Explanation:
Uses pointers to swap values in memory.
15. Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) return 1;
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
printf("Average: %.2f\n", (float)sum / n);
free(arr);
return 0;
}
Explanation:
Uses malloc() for dynamic memory allocation.
16. File Handling (Count Words)
#include <stdio.h>
int main() {
FILE *file = fopen("[Link]", "r");
if (file == NULL) return 1;
int words = 0;
char word[50];
while (fscanf(file, "%s", word) == 1)
words++;
printf("Word count: %d\n", words);
fclose(file);
return 0;
}
Explanation:
Reads a file and counts the number of words.
This completes the detailed explanation for all questions! Let me know if you need further
clarifications.
Here are solutions for each practice question you requested:
1. Enumeration (enum)
Q1: Define an enum for the days of the week and print the integer values of Monday and Friday.
#include <stdio.h>
enum Weekday { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
int main() {
printf("Monday: %d\n", Monday);
printf("Friday: %d\n", Friday);
return 0;
}
Q2: Create an enum for traffic light colors and print a message based on the selected color.
#include <stdio.h>
enum TrafficLight { Red, Yellow, Green };
int main() {
enum TrafficLight signal = Yellow;
switch (signal) {
case Red:
printf("Stop!\n");
break;
case Yellow:
printf("Get Ready!\n");
break;
case Green:
printf("Go!\n");
break;
}
return 0;
}
Q3: Use an enum for user access levels and display the access level name based on a user input
value.
#include <stdio.h>
enum AccessLevel { Admin = 1, User, Guest };
int main() {
int level;
printf("Enter access level (1-Admin, 2-User, 3-Guest): ");
scanf("%d", &level);
switch (level) {
case Admin: printf("You have Admin access.\n"); break;s
case User: printf("You have User access.\n"); break;
case Guest: printf("You have Guest access.\n"); break;
default: printf("Invalid access level.\n");
}
return 0;
}
2. Structures (struct)
Q4: Define a struct to store a student's name, roll number, and marks.
#include <stdio.h>
struct Student {
char name[50];
int roll;
float marks;
};
int main() {
struct Student s;
printf("Enter name: ");
scanf("%s", [Link]);
printf("Enter roll number: ");
scanf("%d", &[Link]);
printf("Enter marks: ");
scanf("%f", &[Link]);
printf("Student Details:\nName: %s\nRoll: %d\nMarks: %.2f\n", [Link], [Link], [Link]);
return 0;
}
Q5: Store and display details of 5 employees using an array of structures.
#include <stdio.h>
struct Employee {
char name[50];
int ID;
float salary;
};
int main() {
struct Employee emp[5];
for (int i = 0; i < 5; i++) {
printf("Enter details of employee %d\n", i + 1);
printf("Name: ");
scanf("%s", emp[i].name);
printf("ID: ");
scanf("%d", &emp[i].ID);
printf("Salary: ");
scanf("%f", &emp[i].salary);
}
printf("\nEmployee Details:\n");
for (int i = 0; i < 5; i++) {
printf("%s (ID: %d) - Salary: %.2f\n", emp[i].name, emp[i].ID, emp[i].salary);
}
return 0;
}
3. Unions (union)
Q7: Define a union and assign values to its members.
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
data.i = 10;
printf("Integer: %d\n", data.i);
data.f = 20.5;
printf("Float: %.2f\n", data.f);
strcpy([Link], "Hello");
printf("String: %s\n", [Link]);
return 0;
}
Note: Since a union shares memory among all members, only the last assigned value is retained.
4. Strings (char arrays)
Q10: Count vowels and consonants in a string.
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int vowels = 0, consonants = 0;
printf("Enter a string: ");
gets(str);
for (int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
else
consonants++;
}
}
printf("Vowels: %d, Consonants: %d\n", vowels, consonants);
return 0;
}
5. Pointers
Q15: Swap two numbers using pointers.
#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("Swapped values: x = %d, y = %d\n", x, y);
return 0;
}
Q16: Allocate memory dynamically for an array using malloc().
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter size of array: ");
scanf("%d", &n);
int *arr = (int *)malloc(n * sizeof(int));
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Elements are: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
free(arr);
return 0;
}
6. Functions
Q20: Find factorial using recursion.
#include <stdio.h>
int factorial(int n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial: %d\n", factorial(num));
return 0;
}
Q21: Greatest of three numbers.
#include <stdio.h>
int max(int a, int b, int c) {
if (a > b && a > c) return a;
if (b > c) return b;
return c;
}
int main() {
int x, y, z;
printf("Enter three numbers: ");
scanf("%d %d %d", &x, &y, &z);
printf("Greatest: %d\n", max(x, y, z));
return 0;
}
These are the solutions for your requested C programming topics!
Would you like me to add more explanations or modify anything?
Here are more practice questions with their solutions on enum, struct, union, strings, pointers,
and functions:
1. Enumeration (enum)
Q25: Create an enum for different programming languages and use it in a function to print the
language name.
✅Solution
#include <stdio.h>
enum Language { C, Python, Java, JavaScript, Go };
void printLanguage(enum Language lang) {
switch (lang) {
case C: printf("You selected C\n"); break;
case Python: printf("You selected Python\n"); break;
case Java: printf("You selected Java\n"); break;
case JavaScript: printf("You selected JavaScript\n"); break;
case Go: printf("You selected Go\n"); break;
default: printf("Invalid selection\n");
}
}
int main() {
enum Language myLang = Java;
printLanguage(myLang);
return 0;
}
2. Structures (struct)
Q26: Create a struct for a car with fields: brand, year, and price. Use an array of structures for
3 cars and display their details.
✅Solution
#include <stdio.h>
struct Car {
char brand[50];
int year;
float price;
};
int main() {
struct Car cars[3] = {
{"Toyota", 2022, 25000.50},
{"Honda", 2020, 22000.75},
{"Ford", 2019, 19500.00}
};
for (int i = 0; i < 3; i++) {
printf("Car %d: %s, Year: %d, Price: $%.2f\n", i+1, cars[i].brand, cars[i].year,
cars[i].price);
}
return 0;
}
3. Unions (union)
Q27: Create a union for different data types and show memory size before and after storing
values.
✅Solution
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
printf("Size of union: %lu bytes\n", sizeof(data));
data.i = 42;
printf("Integer: %d\n", data.i);
data.f = 3.14;
printf("Float: %.2f\n", data.f);
strcpy([Link], "Hello");
printf("String: %s\n", [Link]);
printf("Size of union remains: %lu bytes\n", sizeof(data));
return 0;
}
4. Strings (char arrays)
Q28: Reverse a string without using strrev().
✅Solution
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
}
5. Pointers
Q29: Find the largest element in an array using pointers.
✅Solution
#include <stdio.h>
int findLargest(int *arr, int size) {
int *max = arr;
for (int i = 1; i < size; i++) {
if (*(arr + i) > *max) {
max = arr + i;
}
}
return *max;
}
int main() {
int arr[] = {12, 45, 7, 89, 34};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Largest element: %d\n", findLargest(arr, size));
return 0;
}
Q30: Swap two strings using pointers.
✅Solution
#include <stdio.h>
#include <string.h>
void swapStrings(char **str1, char **str2) {
char *temp = *str1;
*str1 = *str2;
*str2 = temp;
}
int main() {
char *str1 = "Hello";
char *str2 = "World";
printf("Before swap: str1 = %s, str2 = %s\n", str1, str2);
swapStrings(&str1, &str2);
printf("After swap: str1 = %s, str2 = %s\n", str1, str2);
return 0;
}
6. Functions
Q31: Check if a number is even or odd using a function.
✅Solution
#include <stdio.h>
void checkEvenOdd(int num) {
if (num % 2 == 0)
printf("%d is even.\n", num);
else
printf("%d is odd.\n", num);
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
checkEvenOdd(num);
return 0;
}
Q32: Find the sum of digits of a number using recursion.
✅Solution
#include <stdio.h>
int sumOfDigits(int num) {
if (num == 0)
return 0;
return (num % 10) + sumOfDigits(num / 10);
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Sum of digits: %d\n", sumOfDigits(num));
return 0;
}
Q33: Check if a number is prime using a function.
✅Solution
#include <stdio.h>
int isPrime(int num) {
if (num < 2) return 0;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return 0;
}
return 1;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (isPrime(num))
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
return 0;
}
Q34: Convert Celsius to Fahrenheit using a function.
✅Solution
#include <stdio.h>
float celsiusToFahrenheit(float celsius) {
return (celsius * 9 / 5) + 32;
}
int main() {
float celsius;
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
printf("Temperature in Fahrenheit: %.2f°F\n", celsiusToFahrenheit(celsius));
return 0;
}
These are more practice questions with solutions for your C programming studies.
Would you like me to add more advanced topics, such as file handling, memory
management, or data structures?
Here are advanced C programming practice questions with solutions on file handling,
memory management, and data structures.
1. File Handling
Q35: Write a C program to create and write to a file.
✅Solution
#include <stdio.h>
int main() {
FILE *file = fopen("[Link]", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(file, "Hello, this is a test file.\n");
fprintf(file, "File handling in C is interesting!\n");
fclose(file);
printf("Data written successfully!\n");
return 0;
}
Q36: Read contents from a file and display them.
✅Solution
#include <stdio.h>
int main() {
FILE *file = fopen("[Link]", "r");
char line[100];
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(file);
return 0;
}
Q37: Append data to an existing file.
✅Solution
#include <stdio.h>
int main() {
FILE *file = fopen("[Link]", "a");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(file, "Appending new line to the file.\n");
fclose(file);
printf("Data appended successfully!\n");
return 0;
}
2. Dynamic Memory Management
Q38: Allocate memory dynamically for an array using malloc().
✅Solution
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
printf("Enter %d numbers: ", n);
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Numbers entered: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
free(arr);
return 0;
}
Q39: Use realloc() to increase array size.
✅Solution
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int *)malloc(3 * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
printf("Enter 3 numbers: ");
for (int i = 0; i < 3; i++)
scanf("%d", &arr[i]);
arr = (int *)realloc(arr, 5 * sizeof(int));
printf("Enter 2 more numbers: ");
for (int i = 3; i < 5; i++)
scanf("%d", &arr[i]);
printf("All numbers: ");
for (int i = 0; i < 5; i++)
printf("%d ", arr[i]);
free(arr);
return 0;
}
3. Data Structures
Q40: Implement a Singly Linked List.
✅Solution
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
void insertAtEnd(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;
return;
}
struct Node *temp = *head;
while (temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
void displayList(struct Node *head) {
struct Node *temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
struct Node *head = NULL;
insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
printf("Linked List: ");
displayList(head);
return 0;
}
Q41: Implement Stack using an array.
✅Solution
#include <stdio.h>
#define MAX 5
int stack[MAX], top = -1;
void push(int value) {
if (top == MAX - 1) {
printf("Stack Overflow!\n");
return;
}
stack[++top] = value;
}
int pop() {
if (top == -1) {
printf("Stack Underflow!\n");
return -1;
}
return stack[top--];
}
void display() {
if (top == -1) {
printf("Stack is empty.\n");
return;
}
printf("Stack: ");
for (int i = top; i >= 0; i--)
printf("%d ", stack[i]);
printf("\n");
}
int main() {
push(10);
push(20);
push(30);
display();
printf("Popped: %d\n", pop());
display();
return 0;
}
Q42: Implement a Queue using an array.
✅Solution
#include <stdio.h>
#define MAX 5
int queue[MAX], front = -1, rear = -1;
void enqueue(int value) {
if (rear == MAX - 1) {
printf("Queue Overflow!\n");
return;
}
if (front == -1)
front = 0;
queue[++rear] = value;
}
int dequeue() {
if (front == -1 || front > rear) {
printf("Queue Underflow!\n");
return -1;
}
return queue[front++];
}
void display() {
if (front == -1 || front > rear) {
printf("Queue is empty.\n");
return;
}
printf("Queue: ");
for (int i = front; i <= rear; i++)
printf("%d ", queue[i]);
printf("\n");
}
int main() {
enqueue(5);
enqueue(10);
enqueue(15);
display();
printf("Dequeued: %d\n", dequeue());
display();
return 0;
}
Q43: Implement Bubble Sort.
✅Solution
#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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
These are advanced C programming problems with file handling, memory management,
and data structures.
Would you like more sorting algorithms, binary trees, or something specific?
Here are the answers to the practical C function questions!
1. Function to Find Maximum
#include <stdio.h>
int findMax(int a, int b) {
return (a > b) ? a : b;
}
int main() {
int x = 10, y = 20;
printf("Max: %d\n", findMax(x, y));
return 0;
}
Output: Max: 20
2. Swap Two Numbers using Call by Reference
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
Output:
Before swap: x = 5, y = 10
After swap: x = 10, y = 5
3. Factorial using Recursion
#include <stdio.h>
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
int main() {
int num = 5;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
Output: Factorial of 5 is 120
4. Check if a Number is Prime
#include <stdio.h>
int isPrime(int num) {
if (num < 2) return 0;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return 0;
}
return 1;
}
int main() {
int num = 17;
if (isPrime(num)) printf("%d is prime\n", num);
else printf("%d is not prime\n", num);
return 0;
}
Output: 17 is prime
5. Reverse an Array using a Function
#include <stdio.h>
void reverseArray(int arr[], int size) {
for (int i = 0; i < size / 2; i++) {
int temp = arr[i];
arr[i] = arr[size - i - 1];
arr[size - i - 1] = temp;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
reverseArray(arr, size);
printf("Reversed array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output: Reversed array: 5 4 3 2 1
6. Function Pointer for Arithmetic Operations
#include <stdio.h>
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int divi(int a, int b) { return b != 0 ? a / b : 0; }
int main() {
int (*operation)(int, int);
int choice, x = 10, y = 5;
printf("Choose operation: [Link] [Link] [Link] [Link]\n");
scanf("%d", &choice);
switch (choice) {
case 1: operation = add; break;
case 2: operation = sub; break;
case 3: operation = mul; break;
case 4: operation = divi; break;
default: printf("Invalid choice\n"); return 1;
}
printf("Result: %d\n", operation(x, y));
return 0;
}
User Input Example: 1
Output: Result: 15
7. Find GCD (Greatest Common Divisor) using Recursion
#include <stdio.h>
int gcd(int a, int b) {
return (b == 0) ? a : gcd(b, a % b);
}
int main() {
int x = 48, y = 18;
printf("GCD of %d and %d is %d\n", x, y, gcd(x, y));
return 0;
}
Output: GCD of 48 and 18 is 6
8. Variadic Function to Find Sum
#include <stdio.h>
#include <stdarg.h>
int sum(int count, ...) {
va_list args;
va_start(args, count);
int total = 0;
for (int i = 0; i < count; i++) {
total += va_arg(args, int);
}
va_end(args);
return total;
}
int main() {
printf("Sum: %d\n", sum(4, 1, 2, 3, 4));
return 0;
}
Output: Sum: 10
9. Return Multiple Values using a Struct
#include <stdio.h>
struct Result {
int quotient;
int remainder;
};
struct Result divide(int a, int b) {
struct Result res;
[Link] = a / b;
[Link] = a % b;
return res;
}
int main() {
int x = 10, y = 3;
struct Result res = divide(x, y);
printf("Quotient: %d, Remainder: %d\n", [Link], [Link]);
return 0;
}
Output: Quotient: 3, Remainder: 1
10. Function to Sort an Array (Bubble Sort)
#include <stdio.h>
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - 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[] = {5, 1, 4, 2, 8};
int size = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, size);
printf("Sorted array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output: Sorted array: 1 2 4 5 8
These programs cover:
✔ Function basics
✔ Recursion
✔ Function pointers
✔ Variadic functions
✔ Structs & multiple return values
✔ Sorting algorithms
Let me know if you need any explanations!
That's great! To be well-prepared in C programming, you should cover the following topics:
1. Basics (Fundamentals)
Data types (int, float, char, double)
Operators (+, -, *, /, %, ++, --, &&, ||)
Control structures (if, else, switch, for, while, do-while)
Input/Output (printf(), scanf(), gets(), puts())
2. Functions & Recursion
Function declaration, definition, and calling
Call by value vs. Call by reference
Recursion (factorial, Fibonacci, GCD)
Function pointers
3. Arrays & Strings
1D and 2D arrays (sorting, searching)
String handling (strlen(), strcpy(), strcmp(), strcat())
Passingarrays to functions
4. Pointers (Very Important!)
Pointer basics (*, &)
Pointer arithmetic
Pointers and arrays
Pointers and functions
Pointer to pointer (**)
Memory allocation (malloc(), calloc(), realloc(), free())
5. Structures & Unions
Structs (struct keyword, passing to functions)
Unions (union keyword)
Nested structures
Structs with pointers
6. File Handling
Opening and closing files (fopen(), fclose())
Reading and writing (fscanf(), fprintf(), fgets(), fputs())
File modes (r, w, a, r+, w+, a+)
7. Data Structures in C
Linked Lists (Singly, Doubly, Circular)
Stacks and Queues (Using arrays and linked lists)
Trees (Binary Tree, BST)
Sorting algorithms (Bubble, Selection, Insertion, Quick, Merge)
Searching algorithms (Linear, Binary search)
8. Advanced Topics
Bitwise operators (&, |, ^, <<, >>)
Macros and Preprocessors (#define, #ifdef, #ifndef)
Command-line arguments (int main(int argc, char *argv[]))
Multi-threading (POSIX Threads if needed)
Since you already know some coding, you should focus on pointers, memory management,
data structures, and file handling to become an advanced C programmer.
Let me know if you need practice problems for any of these topics!
Yes! If you know all these topics, you're ready to start building your own projects and apps!
Here’s how to transition from learning to building projects:
1. Start with Small Projects (Beginner Level)
Calculator – Basic arithmetic operations using functions
To-Do List – Store tasks in an array or file
Number Guessing Game – Random number generation
Simple Quiz App – Read questions from a file and evaluate answers
Library Management System – Store book records using structs and file handling
2. Move to Intermediate Projects
Contact Book – Add, delete, update, and search contacts (file handling)
Banking System – Simulate deposit, withdrawal, and balance check
Student Management System – Use structs to store student details
Tic-Tac-Toe – Playable in the console
Mini Shell – Create a basic command-line shell using system()
3. Advanced Projects (Real-World Applications)
File Compression Tool – Implement Huffman coding
Chat Application – Use sockets for real-time messaging
Simple Compiler/Interpreter – Tokenize and execute basic commands
Custom Memory Allocator – Implement malloc() and free()
Operating System Simulation – Create process scheduling algorithms
4. Game Development in C
Snake Game – Using arrays and logic
Pong Game – Using graphics.h (Turbo C) or SDL2
Simple RPG Game – Console-based with inventory system
Flappy Bird Clone – Basic physics simulation
5. Cybersecurity & System-Level Projects
Keylogger – Capture keyboard input
Packet Sniffer – Read network packets (Linux, pcap)
Simple Antivirus Scanner – Scan files for patterns
Brute Force Password Cracker – Dictionary attack using hashing
Next Steps
Pick a project that interests you
Plan – Break it into small steps
Code – Use functions, structs, and pointers efficiently
Debug & Optimize – Learn gdb for debugging
Improve – Add features, fix issues, and make it better
Would you like help picking a project based on your interests?
C Programming Practical Questions
Section 1: Data Types (10 Questions)
1. Write a program to declare an integer, a float, and a character and print their values.
2. Write a program to swap two integer values without using a third variable.
3. Create a program that takes a floating-point number as input and prints it with two
decimal places.
4. Write a C program to check whether a given character is a vowel or consonant.
5. Implement a program that stores and prints the ASCII value of a character entered by the
user.
6. Write a program to convert a temperature given in Fahrenheit to Celsius.
7. Write a C program to find the size of different data types using sizeof().
8. Create a program to check if a number is even or odd using the modulus operator.
9. Write a program that takes two numbers as input and swaps their values.
10. Write a C program that reads an integer and prints whether it is positive, negative, or
zero.
Section 2: Operators (10 Questions)
11. Write a program that takes two numbers as input and performs all arithmetic operations
on them.
12. Implement a program to demonstrate the use of relational operators.
13. Write a program to check whether a given number is divisible by both 5 and 7.
14. Create a program that uses bitwise operators to find whether a number is even or odd.
15. Implement a program to swap two numbers using bitwise XOR.
16. Write a program to check if a number is within a given range using logical operators.
17. Implement a simple calculator using switch-case and arithmetic operators.
18. Write a program to increment and decrement a number using ++ and -- operators.
19. Create a program to find the remainder when dividing two numbers using the modulus
operator.
20. Write a program that uses the ternary operator to check if a number is positive or
negative.
Section 3: Control Structures (10 Questions)
21. Write a program that takes an integer input and prints whether it is prime or not.
22. Implement a program to print the first 10 Fibonacci numbers using a loop.
23. Create a program that prints a multiplication table for a given number.
24. Write a C program to find the sum of digits of a number using a loop.
25. Implement a program to reverse a given integer number.
26. Write a program to check if a number is a palindrome.
27. Implement a program to find the factorial of a number using recursion.
28. Write a program to find the greatest of three numbers using if-else.
29. Create a program to check if a given year is a leap year.
30. Write a program to print numbers from 1 to 100, replacing multiples of 3 with "Fizz" and
multiples of 5 with "Buzz".
Section 4: Input/Output (10 Questions)
31. Write a program that takes two integer inputs and prints their sum.
32. Implement a program that reads a sentence and prints it using gets() and puts().
33. Create a program to read a name from the user and print a greeting message.
34. Write a program to take user input for radius and calculate the area of a circle.
35. Implement a program to take three numbers as input and print their average.
36. Write a program to take a string input and print each character on a new line.
37. Create a program that reads and prints a floating-point number with three decimal places.
38. Write a C program that takes a number as input and prints its square and cube.
39. Implement a program to read two integers and print the larger one.
40. Write a program to take input for an employee's name, age, and salary, then display the
information.
Section 5: Loops and Arrays (10 Questions)
41. Write a program to print numbers from 1 to 10 using a while loop.
42. Implement a program that prints the sum of the first 50 natural numbers.
43. Write a C program to find the largest element in an array.
44. Create a program to reverse the elements of an array.
45. Implement a program to count the number of vowels in a given string.
46. Write a program that finds the second largest number in an array.
47. Create a program that sorts an array in ascending order.
48. Write a program to merge two arrays into a single array.
49. Implement a program that checks whether an array is a palindrome.
50. Write a C program that prints the first n prime numbers.
Section 6: Functions and Pointers (10 Questions)
51. Write a function that takes two numbers as arguments and returns their sum.
52. Implement a function that calculates the power of a number.
53. Create a recursive function to find the factorial of a number.
54. Write a program that demonstrates call-by-value and call-by-reference.
55. Implement a function to check whether a given number is prime.
56. Write a program that swaps two numbers using pointers.
57. Create a function that reverses a given string.
58. Implement a program that finds the length of a string using pointers.
59. Write a function to return the maximum element from an array.
60. Implement a program that dynamically allocates memory for an array.
Section 7: File Handling (10 Questions)
61. Write a program to create a text file and write a string to it.
62. Implement a program that reads the contents of a file and prints them on the screen.
63. Create a program that appends a new line to an existing file.
64. Write a program that counts the number of characters in a file.
65. Implement a program to copy the contents of one file to another.
66. Write a program that checks whether a file exists or not.
67. Create a program that reads and displays student details from a file.
68. Implement a program to count the number of lines in a file.
69. Write a program that replaces a specific word in a file with another word.
70. Implement a program that encrypts and decrypts the contents of a file.
End of Practical Questions
Answers
/* Section 1: Data Types */
#include <stdio.h>
// 1. Declare an integer, a float, and a character and print their values.
void question1() {
int num = 10;
float decimal = 5.25;
char letter = 'A';
printf("Integer: %d\nFloat: %.2f\nCharacter: %c\n", num, decimal, letter);
// 2. Swap two integers without using a third variable.
void question2() {
int a = 5, b = 10;
printf("Before Swap: a = %d, b = %d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("After Swap: a = %d, b = %d\n", a, b);
// 3. Take a float input and print it with two decimal places.
void question3() {
float num;
printf("Enter a floating-point number: ");
scanf("%f", &num);
printf("Formatted: %.2f\n", num);
// 4. Check if a character is a vowel or consonant.
void question4() {
char ch;
printf("Enter a character: ");
scanf(" %c", &ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
printf("%c is a vowel.\n", ch);
} else {
printf("%c is a consonant.\n", ch);
// 5. Store and print ASCII value of a character.
void question5() {
char ch;
printf("Enter a character: ");
scanf(" %c", &ch);
printf("ASCII value of %c is %d\n", ch, ch);
// 6. Convert temperature from Fahrenheit to Celsius.
void question6() {
float f, c;
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &f);
c = (f - 32) * 5 / 9;
printf("Temperature in Celsius: %.2f\n", c);
// 7. Find the size of different data types.
void question7() {
printf("Size of int: %lu bytes\n", sizeof(int));
printf("Size of float: %lu bytes\n", sizeof(float));
printf("Size of char: %lu bytes\n", sizeof(char));
printf("Size of double: %lu bytes\n", sizeof(double));
// 8. Check if a number is even or odd using modulus operator.
void question8() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if (num % 2 == 0)
printf("%d is even.\n", num);
else
printf("%d is odd.\n", num);
}
// 9. Swap two numbers using user input.
void question9() {
int a, b, temp;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
temp = a;
a = b;
b = temp;
printf("After Swap: a = %d, b = %d\n", a, b);
// 10. Check if a number is positive, negative, or zero.
void question10() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if (num > 0)
printf("%d is positive.\n", num);
else if (num < 0)
printf("%d is negative.\n", num);
else
printf("Number is zero.\n");
int main() {
question1();
question2();
question3();
question4();
question5();
question6();
question7();
question8();
question9();
question10();
return 0;
/* Section 2: Operators */
#include <stdio.h>
// 11. Perform all arithmetic operations on two numbers.
void question11() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Addition: %d\n", a + b);
printf("Subtraction: %d\n", a - b);
printf("Multiplication: %d\n", a * b);
printf("Division: %.2f\n", (float)a / b);
printf("Modulus: %d\n", a % b);
// 12. Demonstrate relational operators.
void question12() {
int a = 10, b = 20;
printf("%d > %d = %d\n", a, b, a > b);
printf("%d < %d = %d\n", a, b, a < b);
printf("%d == %d = %d\n", a, b, a == b);
printf("%d != %d = %d\n", a, b, a != b);
}
// 13. Check divisibility by both 5 and 7.
void question13() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num % 5 == 0 && num % 7 == 0)
printf("%d is divisible by both 5 and 7.\n", num);
else
printf("%d is not divisible by both 5 and 7.\n", num);
// 14. Use bitwise operators to check even or odd.
void question14() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if (num & 1)
printf("%d is odd.\n", num);
else
printf("%d is even.\n", num);
}
// 15. Swap two numbers using XOR.
void question15() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("After Swap: a = %d, b = %d\n", a, b);
// 16. Check if a number is within a range using logical operators.
void question16() {
int num, lower, upper;
printf("Enter a number, lower bound, and upper bound: ");
scanf("%d %d %d", &num, &lower, &upper);
if (num >= lower && num <= upper)
printf("%d is within the range [%d, %d].\n", num, lower, upper);
else
printf("%d is out of range.\n", num);
// 17. Simple calculator using switch-case.
void question17() {
int a, b, choice;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Choose operation: 1-Add, 2-Subtract, 3-Multiply, 4-Divide: ");
scanf("%d", &choice);
switch (choice) {
case 1: printf("Result: %d\n", a + b); break;
case 2: printf("Result: %d\n", a - b); break;
case 3: printf("Result: %d\n", a * b); break;
case 4: printf("Result: %.2f\n", (float)a / b); break;
default: printf("Invalid choice\n");
// 18. Increment and decrement operators.
void question18() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Increment: %d\n", ++num);
printf("Decrement: %d\n", --num);
// 19. Find remainder using modulus operator.
void question19() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Remainder: %d\n", a % b);
// 20. Use ternary operator to check positive or negative.
void question20() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("%d is %s\n", num, (num >= 0) ? "positive" : "negative");
}
int main() {
question11();
question12();
question13();
question14();
question15();
question16();
question17();
question18();
question19();
question20();
return 0;
/* Section 3: Control Structures */
#include <stdio.h>
#include <math.h>
// 21. Check if a number is prime.
void question21() {
int num, i, flag = 1;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 2) flag = 0;
for (i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
flag = 0;
break;
printf("%d is %s\n", num, flag ? "prime" : "not prime");
// 22. Print first 10 Fibonacci numbers.
void question22() {
int a = 0, b = 1, temp, i;
printf("Fibonacci series: ");
for (i = 0; i < 10; i++) {
printf("%d ", a);
temp = a + b;
a = b;
b = temp;
printf("\n");
// 23. Print multiplication table of a number.
void question23() {
int num, i;
printf("Enter a number: ");
scanf("%d", &num);
for (i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", num, i, num * i);
// 24. Find sum of digits of a number.
void question24() {
int num, sum = 0;
printf("Enter an integer: ");
scanf("%d", &num);
while (num != 0) {
sum += num % 10;
num /= 10;
printf("Sum of digits: %d\n", sum);
// 25. Reverse an integer number.
void question25() {
int num, reversed = 0;
printf("Enter an integer: ");
scanf("%d", &num);
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
printf("Reversed number: %d\n", reversed);
// 26. Check if a number is a palindrome.
void question26() {
int num, original, reversed = 0;
printf("Enter a number: ");
scanf("%d", &num);
original = num;
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
printf("%d is %s\n", original, (original == reversed) ? "a palindrome" : "not a palindrome");
// 27. Find factorial using recursion.
int factorial(int n) {
return (n == 0 || n == 1) ? 1 : n * factorial(n - 1);
void question27() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d = %d\n", num, factorial(num));
}
// 28. Find the greatest of three numbers.
void question28() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
printf("Greatest number: %d\n", (a > b && a > c) ? a : (b > c) ? b : c);
// 29. Check if a year is a leap year.
void question29() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
printf("%d is a leap year\n", year);
else
printf("%d is not a leap year\n", year);
}
// 30. Print numbers from 1 to 100 replacing multiples of 3 with "Fizz" and multiples of 5 with
"Buzz".
void question30() {
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0)
printf("FizzBuzz ");
else if (i % 3 == 0)
printf("Fizz ");
else if (i % 5 == 0)
printf("Buzz ");
else
printf("%d ", i);
printf("\n");
int main() {
question21();
question22();
question23();
question24();
question25();
question26();
question27();
question28();
question29();
question30();
return 0;
/* Section 3: Control Structures */
#include <stdio.h>
#include <math.h>
// 21. Check if a number is prime.
void question21() {
int num, i, flag = 1;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 2) flag = 0;
for (i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
flag = 0;
break;
printf("%d is %s\n", num, flag ? "prime" : "not prime");
// 22. Print first 10 Fibonacci numbers.
void question22() {
int a = 0, b = 1, temp, i;
printf("Fibonacci series: ");
for (i = 0; i < 10; i++) {
printf("%d ", a);
temp = a + b;
a = b;
b = temp;
}
printf("\n");
// 23. Print multiplication table of a number.
void question23() {
int num, i;
printf("Enter a number: ");
scanf("%d", &num);
for (i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", num, i, num * i);
// 24. Find sum of digits of a number.
void question24() {
int num, sum = 0;
printf("Enter an integer: ");
scanf("%d", &num);
while (num != 0) {
sum += num % 10;
num /= 10;
}
printf("Sum of digits: %d\n", sum);
// 25. Reverse an integer number.
void question25() {
int num, reversed = 0;
printf("Enter an integer: ");
scanf("%d", &num);
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
printf("Reversed number: %d\n", reversed);
// 26. Check if a number is a palindrome.
void question26() {
int num, original, reversed = 0;
printf("Enter a number: ");
scanf("%d", &num);
original = num;
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
printf("%d is %s\n", original, (original == reversed) ? "a palindrome" : "not a palindrome");
// 27. Find factorial using recursion.
int factorial(int n) {
return (n == 0 || n == 1) ? 1 : n * factorial(n - 1);
void question27() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d = %d\n", num, factorial(num));
// 28. Find the greatest of three numbers.
void question28() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
printf("Greatest number: %d\n", (a > b && a > c) ? a : (b > c) ? b : c);
// 29. Check if a year is a leap year.
void question29() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
printf("%d is a leap year\n", year);
else
printf("%d is not a leap year\n", year);
// 30. Print numbers from 1 to 100 replacing multiples of 3 with "Fizz" and multiples of 5 with
"Buzz".
void question30() {
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0)
printf("FizzBuzz ");
else if (i % 3 == 0)
printf("Fizz ");
else if (i % 5 == 0)
printf("Buzz ");
else
printf("%d ", i);
printf("\n");
int main() {
question21();
question22();
question23();
question24();
question25();
question26();
question27();
question28();
question29();
question30();
return 0;
/* Section 5: Loops and Arrays */
#include <stdio.h>
// 41. Print numbers from 1 to 10 using a while loop.
void question41() {
int i = 1;
while (i <= 10) {
printf("%d ", i);
i++;
printf("\n");
}
// 42. Sum of the first 50 natural numbers.
void question42() {
int sum = 0;
for (int i = 1; i <= 50; i++) {
sum += i;
printf("Sum: %d\n", sum);
// 43. Find the largest element in an array.
void question43() {
int arr[] = {12, 45, 67, 89, 23};
int max = arr[0];
for (int i = 1; i < 5; i++) {
if (arr[i] > max) max = arr[i];
printf("Largest element: %d\n", max);
// 44. Reverse elements of an array.
void question44() {
int arr[] = {1, 2, 3, 4, 5};
printf("Reversed array: ");
for (int i = 4; i >= 0; i--) {
printf("%d ", arr[i]);
printf("\n");
// 45. Count vowels in a string.
void question45() {
char str[] = "hello world";
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u')
count++;
printf("Number of vowels: %d\n", count);
// 46. Find the second largest number in an array.
void question46() {
int arr[] = {10, 20, 4, 45, 99};
int first = arr[0], second = -1;
for (int i = 1; i < 5; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second && arr[i] != first) {
second = arr[i];
printf("Second largest: %d\n", second);
// 47. Sort an array in ascending order.
void question47() {
int arr[] = {5, 3, 8, 1, 2};
int n = 5, temp;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
printf("\n");
// 48. Merge two arrays into a single array.
void question48() {
int arr1[] = {1, 3, 5};
int arr2[] = {2, 4, 6};
int merged[6];
for (int i = 0; i < 3; i++) {
merged[i] = arr1[i];
merged[i + 3] = arr2[i];
}
printf("Merged array: ");
for (int i = 0; i < 6; i++) {
printf("%d ", merged[i]);
printf("\n");
// 49. Check if an array is a palindrome.
void question49() {
int arr[] = {1, 2, 3, 2, 1};
int n = 5, flag = 1;
for (int i = 0; i < n / 2; i++) {
if (arr[i] != arr[n - i - 1]) {
flag = 0;
break;
printf("Array is %s palindrome\n", flag ? "a" : "not a");
// 50. Print the first n prime numbers.
void question50() {
int n = 10, count = 0, num = 2;
printf("First %d prime numbers: ", n);
while (count < n) {
int prime = 1;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
prime = 0;
break;
if (prime) {
printf("%d ", num);
count++;
num++;
printf("\n");
int main() {
question41();
question42();
question43();
question44();
question45();
question46();
question47();
question48();
question49();
question50();
return 0;
/* Section 6: Functions and Pointers */
#include <stdio.h>
// 51. Function to return sum of two numbers.
int sum(int a, int b) {
return a + b;
}
// 52. Function to calculate power of a number.
int power(int base, int exp) {
int result = 1;
for (int i = 0; i < exp; i++) {
result *= base;
return result;
// 53. Recursive function to find factorial.
int factorial(int n) {
if (n == 0 || n == 1) return 1;
return n * factorial(n - 1);
// 54. Demonstrate call-by-value and call-by-reference.
void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
}
void swapByReference(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
// 55. Function to check if a number is prime.
int isPrime(int num) {
if (num < 2) return 0;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return 0;
return 1;
// 56. Swap two numbers using pointers.
void swapPointers(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// 57. Function to reverse a string.
void reverseString(char *str) {
int len = 0;
while (str[len] != '\0') len++;
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
// 58. Function to find length of a string using pointers.
int stringLength(char *str) {
int length = 0;
while (*str++) length++;
return length;
// 59. Function to return maximum element in an array.
int maxInArray(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) max = arr[i];
return max;
// 60. Dynamically allocate memory for an array.
void dynamicArrayAllocation() {
int n;
printf("Enter array size: ");
scanf("%d", &n);
int *arr = (int*) malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return;
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
printf("Elements: ");
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
free(arr);
int main() {
printf("Sum: %d\n", sum(5, 10));
printf("Power: %d\n", power(2, 3));
printf("Factorial: %d\n", factorial(5));
int x = 5, y = 10;
swapByValue(x, y);
printf("After call-by-value swap: x=%d, y=%d\n", x, y);
swapByReference(&x, &y);
printf("After call-by-reference swap: x=%d, y=%d\n", x, y);
printf("Is 17 prime? %s\n", isPrime(17) ? "Yes" : "No");
swapPointers(&x, &y);
printf("After pointer swap: x=%d, y=%d\n", x, y);
char str[] = "hello";
reverseString(str);
printf("Reversed string: %s\n", str);
printf("String length: %d\n", stringLength(str));
int arr[] = {12, 43, 56, 78, 21};
printf("Max in array: %d\n", maxInArray(arr, 5));
dynamicArrayAllocation();
return 0;
/* Section 7: File Handling */
#include <stdio.h>
#include <stdlib.h>
// 61. Create a text file and write a string to it.
void createFile() {
FILE *file = fopen("[Link]", "w");
if (file == NULL) {
printf("Error opening file!\n");
return;
fprintf(file, "Hello, this is a test file.\n");
fclose(file);
// 62. Read and print file contents.
void readFile() {
FILE *file = fopen("[Link]", "r");
if (file == NULL) {
printf("Error opening file!\n");
return;
char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
fclose(file);
}
// 63. Append a new line to an existing file.
void appendFile() {
FILE *file = fopen("[Link]", "a");
if (file == NULL) {
printf("Error opening file!\n");
return;
fprintf(file, "Appending a new line.\n");
fclose(file);
// 64. Count the number of characters in a file.
void countCharacters() {
FILE *file = fopen("[Link]", "r");
if (file == NULL) {
printf("Error opening file!\n");
return;
int count = 0;
while (fgetc(file) != EOF) count++;
fclose(file);
printf("Character count: %d\n", count);
// 65. Copy contents of one file to another.
void copyFile() {
FILE *src = fopen("[Link]", "r");
FILE *dest = fopen("[Link]", "w");
if (src == NULL || dest == NULL) {
printf("Error opening files!\n");
return;
char ch;
while ((ch = fgetc(src)) != EOF) {
fputc(ch, dest);
fclose(src);
fclose(dest);
// 66. Check if a file exists.
void checkFileExists() {
FILE *file = fopen("[Link]", "r");
if (file) {
printf("File exists.\n");
fclose(file);
} else {
printf("File does not exist.\n");
// 67. Read and display student details from a file.
void readStudentDetails() {
FILE *file = fopen("[Link]", "r");
if (file == NULL) {
printf("Error opening file!\n");
return;
char name[50];
int age;
float gpa;
while (fscanf(file, "%s %d %f", name, &age, &gpa) != EOF) {
printf("Name: %s, Age: %d, GPA: %.2f\n", name, age, gpa);
}
fclose(file);
// 68. Count the number of lines in a file.
void countLines() {
FILE *file = fopen("[Link]", "r");
if (file == NULL) {
printf("Error opening file!\n");
return;
int lines = 0;
char ch;
while ((ch = fgetc(file)) != EOF) {
if (ch == '\n') lines++;
fclose(file);
printf("Line count: %d\n", lines);
// 69. Replace a specific word in a file.
void replaceWord() {
printf("Feature not implemented yet.\n");
// 70. Encrypt and decrypt file contents.
void encryptDecryptFile() {
printf("Feature not implemented yet.\n");
int main() {
createFile();
readFile();
appendFile();
countCharacters();
copyFile();
checkFileExists();
readStudentDetails();
countLines();
replaceWord();
encryptDecryptFile();
return 0;
}
Pointers in C - A Complete Guide
Pointers are one of the most powerful and complex features of the C programming language.
Mastering pointers will help you understand how memory works, optimize your code, and
interact with data efficiently.
1. Introduction to Pointers
A pointer is a variable that stores the memory address of another variable. Instead of storing
data, a pointer stores a reference to a memory location.
Declaring and Initializing Pointers
int x = 10; // Normal variable
int *ptr; // Pointer variable
ptr = &x; // Assigning the address of x to ptr
int *ptr; → Declares a pointer to an integer.
ptr = &x; → Assigns the address of x to ptr.
Printing Values Using Pointers
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x;
printf("Value of x: %d\n", x); // Direct access
printf("Address of x: %p\n", &x); // Address of x
printf("Value stored in ptr: %p\n", ptr); // Address stored in ptr
printf("Value pointed by ptr: %d\n", *ptr); // Dereferencing
return 0;
}
*ptr is called dereferencing, meaning it accesses the value stored at the memory address.
2. Pointer Arithmetic
You can perform arithmetic operations on pointers.
Increment and Decrement
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30};
int *ptr = arr; // Points to the first element
printf("First element: %d\n", *ptr);
ptr++; // Moves to the next element
printf("Second element: %d\n", *ptr);
ptr--; // Moves back to the first element
printf("Back to first element: %d\n", *ptr);
return 0;
}
ptr++ moves the pointer to the next memory location (next integer).
ptr-- moves the pointer back.
Pointer Addition and Subtraction
int *ptr;
ptr = ptr + 2; // Moves the pointer forward by 2 integers
ptr = ptr - 1; // Moves the pointer back by 1 integer
Pointer Difference
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr1 = &arr[1]; // Points to second element
int *ptr2 = &arr[4]; // Points to last element
int diff = ptr2 - ptr1; // Calculates the number of elements between
printf("Number of elements between: %d\n", diff);
return 0;
}
3. Pointers and Arrays
Array Name as a Pointer
In C, the name of an array is a pointer to the first element.
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // Equivalent to &arr[0]
You can access array elements using pointers:
printf("%d\n", *(arr + 2)); // Same as arr[2]
Iterating an Array Using a Pointer
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
for (int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i)); // Access elements using pointer
arithmetic
}
return 0;
}
4. Pointers and Strings
A string is an array of characters, so pointers can be used to manipulate strings.
Pointer to a String
#include <stdio.h>
int main() {
char str[] = "Hello";
char *ptr = str;
printf("%s\n", ptr); // Prints the whole string
return 0;
}
Modifying a String Using Pointers
#include <stdio.h>
int main() {
char str[] = "Hello";
char *ptr = str;
ptr[0] = 'M'; // Modifies first character
printf("%s\n", ptr); // Output: Mello
return 0;
}
5. Pointers and Functions
Call by Value vs. Call by Reference
Call by Value: The function receives a copy of the variable (no actual change).
Call by Reference: The function receives a pointer to the variable (modifies actual data).
Swapping Two Numbers Using Pointers (Call by Reference)
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
swap(&x, &y);
printf("x = %d, y = %d\n", x, y); // Values are swapped
return 0;
}
6. Dynamic Memory Allocation
Dynamic memory is managed using malloc(), calloc(), realloc(), and free().
Using malloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(5 * sizeof(int)); // Allocates memory for 5
integers
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
for (int i = 0; i < 5; i++) {
ptr[i] = i * 10;
printf("%d ", ptr[i]);
}
free(ptr); // Free memory
return 0;
}
Using calloc()
int *ptr = (int *)calloc(5, sizeof(int)); // Allocates memory for 5 integers,
initializes to 0
Using realloc()
ptr = (int *)realloc(ptr, 10 * sizeof(int)); // Resizes memory block
Freeing Allocated Memory
free(ptr); // Always free allocated memory
7. Pointers to Pointers (Double Pointers)
A pointer that stores the address of another pointer.
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x;
int **ptr2 = &ptr; // Pointer to pointer
printf("Value of x: %d\n", **ptr2);
return 0;
}
8. Function Pointers
A function pointer stores the address of a function and allows calling the function dynamically.
Declaring and Using Function Pointers
#include <stdio.h>
void greet() {
printf("Hello, world!\n");
}
int main() {
void (*funcPtr)(); // Declare function pointer
funcPtr = greet; // Assign function address
funcPtr(); // Call the function using pointer
return 0;
}
Function Pointer with Parameters
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int (*funcPtr)(int, int) = add; // Function pointer
printf("Sum: %d\n", funcPtr(5, 10)); // Call function via pointer
return 0;
}
Conclusion
Pointers are an essential part of C programming. Here’s what you should practice: Basic
pointer operations
Pointer arithmetic
Pointers with arrays, strings, and functions
Dynamic memory allocation
Double pointers and function pointers
Let me know if you need examples or explanations on any specific topic!
Complete Guide to Arrays and Strings in C
Arrays and strings are fundamental concepts in C programming. They help store and manipulate
data efficiently.
1. Arrays in C
An array is a collection of elements of the same data type stored in contiguous memory
locations.
1.1 Declaring and Initializing Arrays
Syntax
data_type array_name[size];
Example
int arr[5]; // Declaring an array of 5 integers
Initializing Arrays
int arr[5] = {10, 20, 30, 40, 50}; // Initialization at declaration
// Partial initialization
int arr2[5] = {1, 2}; // Remaining elements initialized to 0
Accessing Array Elements
#include <stdio.h>
int main() {
int arr[3] = {10, 20, 30};
printf("First element: %d\n", arr[0]);
printf("Second element: %d\n", arr[1]);
printf("Third element: %d\n", arr[2]);
return 0;
}
1.2 Looping Through Arrays
Using loops, we can iterate over arrays.
Using a for loop
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("Element at index %d: %d\n", i, arr[i]);
}
return 0;
}
Using a while loop
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int i = 0;
while (i < 5) {
printf("%d ", arr[i]);
i++;
}
return 0;
}
1.3 Multi-Dimensional Arrays
2D Array (Matrix)
int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
Accessing Elements in a 2D Array
#include <stdio.h>
int main() {
int matrix[2][2] = { {1, 2}, {3, 4} };
printf("Element at [0][1]: %d\n", matrix[0][1]); // Output: 2
printf("Element at [1][0]: %d\n", matrix[1][0]); // Output: 3
return 0;
}
Looping Through a 2D Array
#include <stdio.h>
int main() {
int matrix[2][2] = { {1, 2}, {3, 4} };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
1.4 Passing Arrays to Functions
Since arrays are passed by reference, any changes inside the function affect the original array.
#include <stdio.h>
void modifyArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2; // Double each element
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
modifyArray(arr, 5); // Function call
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]); // Output: 2 4 6 8 10
}
return 0;
}
2. Strings in C
A string is an array of characters terminated by a null character (\0).
2.1 Declaring and Initializing Strings
Using Character Arrays
char str1[] = {'H', 'e', 'l', 'l', 'o', '\0'};
char str2[] = "Hello"; // Automatically adds '\0'
Using Pointers
char *str = "Hello";
2.2 Input and Output of Strings
Using scanf() and printf()
#include <stdio.h>
int main() {
char str[50];
printf("Enter a string: ");
scanf("%s", str); // Accepts only one word (stops at space)
printf("You entered: %s\n", str);
return 0;
}
Using gets() and puts()
#include <stdio.h>
int main() {
char str[50];
printf("Enter a string: ");
gets(str); // Accepts multiple words (unsafe)
puts("You entered:");
puts(str);
return 0;
}
Note: gets() is unsafe. Use fgets() instead.
2.3 String Manipulation Functions
C provides the <string.h> library for string operations.
String Length - strlen()
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
printf("Length: %lu\n", strlen(str)); // Output: 5
return 0;
}
String Copy - strcpy()
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello";
char dest[10];
strcpy(dest, src); // Copy src to dest
printf("Copied String: %s\n", dest);
return 0;
}
String Concatenation - strcat()
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2); // Append str2 to str1
printf("%s\n", str1); // Output: Hello, World!
return 0;
}
String Comparison - strcmp()
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
if (result == 0)
printf("Strings are equal\n");
else if (result < 0)
printf("str1 is smaller\n");
else
printf("str1 is greater\n");
return 0;
}
Substring Search - strstr()
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *ptr = strstr(str, "World");
if (ptr)
printf("Substring found at position: %ld\n", ptr - str);
else
printf("Substring not found\n");
return 0;
}
2.4 Pointers and Strings
Since strings are arrays, pointers can be used to manipulate them.
#include <stdio.h>
int main() {
char str[] = "Hello";
char *ptr = str; // Pointer to first character
while (*ptr != '\0') {
printf("%c", *ptr);
ptr++; // Move pointer to next character
}
return 0;
}
3. Dynamic Memory Allocation for Strings
Using malloc() to allocate memory for strings dynamically.
#include <stdio.h>
#include <stdlib.h>
int main() {
char *str = (char *)malloc(50 * sizeof(char));
if (str == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %s\n", str);
free(str); // Free allocated memory
return 0;
}
Conclusion
Arrays: One-dimensional, multi-dimensional, pointers, functions
Strings: Input/output, functions (strlen(), strcpy(), etc.), pointers
Dynamic memory allocation for strings
Would you like exercises to practice?
Functions and recursion are fundamental concepts in C programming. Let’s break them down:
1. Functions in C
A function is a block of code that performs a specific task. Functions help in organizing code
into modular sections, making it easier to write, maintain, and debug. Functions in C can either
return a value (non-void functions) or not return anything (void functions).
Syntax of a Function in C
return_type function_name(parameter1, parameter2, ...) {
// Body of the function
// Perform the task
return value; // For non-void functions
}
return_type: The data type of the value the function will return (e.g., int, float, char). If the
function doesn't return anything, use void.
function_name: The name of the function.
parameters: Inputs for the function (optional). They define the data that the function will work
with.
return value: The output of the function. If it's a void function, no return value is provided.
Example: A simple function that adds two numbers
#include <stdio.h>
// Function definition
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(3, 4); // Function call
printf("Sum: %d\n", result);
return 0;
}
In this example, the function add() takes two integers and returns their sum. We call the
function in main() and store the result in the variable result.
2. Recursion in C
Recursion is when a function calls itself to solve smaller instances of a problem. It’s a powerful
concept, but it's important to have a base case to avoid infinite recursion, which can cause a
stack overflow.
How Recursion Works
The function calls itself with new arguments (usually smaller or simpler).
This process continues until it reaches a base case, which stops the recursion.
Example: Factorial Calculation using Recursion
The factorial of a number nn (denoted as n!n!) is the product of all positive integers less than or
equal to nn. For example, 5!=5×4×3×2×15! = 5 \times 4 \times 3 \times 2 \times 1.
Recursion for factorial is defined as:
Base case: 1!=11! = 1
Recursive case: n!=n×(n−1)!n! = n \times (n - 1)!
#include <stdio.h>
// Function to calculate factorial using recursion
int factorial(int n) {
// Base case
if (n == 0 || n == 1)
return 1;
else
// Recursive case
return n * factorial(n - 1);
}
int main() {
int number = 5;
printf("Factorial of %d is %d\n", number, factorial(number));
return 0;
}
Here’s what happens:
1. factorial(5) calls factorial(4).
2. factorial(4) calls factorial(3).
3. This continues until factorial(1) hits the base case and returns 1.
4. The recursive calls then unwind, and the final result is calculated.
Key Points about Recursion:
Base case: Prevents infinite recursion by providing a condition to stop.
Recursive case: The function keeps calling itself with different parameters.
Stack overflow: If the base case is not reached or the recursion is too deep, it can cause a stack
overflow, leading to a crash.
Practice Exercise:
Try writing a recursive function to calculate the Fibonacci sequence. The Fibonacci sequence is
defined as:
F(0) = 0
F(1) = 1
F(n) = F(n-1) + F(n-2) for n > 1
Let me know if you’d like help with that!
File handling in C allows you to read from and write to files on disk. This is essential for storing
data persistently beyond the runtime of a program. C provides standard library functions to
perform file I/O operations. Let’s dive into the basic concepts of file handling.
Basic Concepts in File Handling
There are a few operations you can perform on files in C:
Opening a file: Before you can read from or write to a file, you need to open it.
Reading from a file: You can read the contents of a file.
Writing to a file: You can write data to a file.
Closing a file: Once you're done with a file, you should always close it to ensure all data is
properly written and resources are released.
Opening a File
To open a file in C, you use the fopen() function. It requires two arguments:
1. File name (the path to the file).
2. Mode (the mode in which you want to open the file).
Syntax:
FILE *fopen(const char *filename, const char *mode);
File Opening Modes
"r": Read mode. Opens the file for reading.
"w": Write mode. Creates a new empty file for writing. If the file exists, it is overwritten.
"a": Append mode. Opens the file for writing, but new data is added at the end without
overwriting.
"rb", "wb", "ab": Same as above, but for binary files.
"r+": Read and write mode. The file must exist.
"w+": Read and write mode. If the file exists, it is overwritten; if it doesn't exist, a new file is
created.
"a+": Read and append mode. Data is added at the end, and you can read the file as well.
Example: Writing to a File
Let’s write a simple program that writes data to a file.
#include <stdio.h>
int main() {
// Open the file in write mode
FILE *file = fopen("[Link]", "w");
if (file == NULL) {
// Check for errors
printf("Error opening file!\n");
return 1;
}
// Write to the file
fprintf(file, "Hello, world!\n");
fprintf(file, "This is file handling in C.\n");
// Close the file
fclose(file);
printf("Data written to the file successfully.\n");
return 0;
}
Explanation:
We open the file [Link] in write mode ("w"). If the file doesn't exist, it will be created.
We use fprintf() to write text to the file, similar to how printf() is used for output.
After writing to the file, we close it using fclose().
Reading from a File
To read from a file, you use fopen() to open the file in read mode ("r"), then use functions like
fscanf() or fgets() to read the contents.
Example: Reading from a File
#include <stdio.h>
int main() {
char line[100];
// Open the file in read mode
FILE *file = fopen("[Link]", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Read and print each line of the file
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
// Close the file
fclose(file);
return 0;
}
Explanation:
fgets() reads a line from the file. It reads until a newline character is encountered or the end
of the file is reached.
while(fgets(...)) continues reading until the end of the file is reached.
Binary File Handling
Binary files store data in a raw format (as opposed to text files), and they are more efficient for
storing structured data. You can use functions like fread() and fwrite() for binary files.
Example: Writing and Reading a Binary File
#include <stdio.h>
struct Student {
int id;
char name[50];
};
int main() {
// Write to a binary file
FILE *file = fopen("[Link]", "wb");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
struct Student s1 = {1, "John Doe"};
fwrite(&s1, sizeof(struct Student), 1, file);
fclose(file);
// Read from a binary file
file = fopen("[Link]", "rb");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
struct Student s2;
fread(&s2, sizeof(struct Student), 1, file);
printf("ID: %d, Name: %s\n", [Link], [Link]);
fclose(file);
return 0;
}
Explanation:
The fwrite() function is used to write the Student structure to the file.
The fread() function reads the data back into a variable of type Student.
Binary file operations are faster for structured data but require you to be careful with the
format (e.g., endianness).
Closing a File
Always close a file after you're done with it using fclose(). This ensures that all data is
properly written, and resources are freed.
fclose(file);
Error Handling
Always check if the file has been opened successfully by checking if the file pointer is NULL (i.e.,
if (file == NULL)).
When reading, you can use feof() to check if you have reached the end of the file.
File Handling Functions Summary:
Function Description
Function Description
fopen() Opens a file in the specified mode.
fclose() Closes the opened file.
fprintf() Writes formatted text to a file (like printf() but for files).
fscanf() Reads formatted input from a file (like scanf() but from a file).
fgets() Reads a line from a file.
fread() Reads binary data from a file.
fwrite() Writes binary data to a file.
feof() Checks if the end of the file has been reached.
Practice Exercise:
Write a program that takes user input and writes it to a file. Then, read the file content and
display it on the screen.
Create a program that stores an array of structures in a binary file and later retrieves and
displays the data.
Let me know if you need further clarification or examples!
Sure! Let's dive deeper into file handling functions in C and explore more functions and their
uses. We've already covered basic file operations, but C also provides additional functions that
allow more control over files.
1. File Positioning Functions
File positioning functions help you control the position of the file pointer (the position in the file
where the next read or write operation will happen). These are crucial when you're dealing with
large files or need to modify specific parts of a file.
ftell()
The ftell() function returns the current position of the file pointer.
long ftell(FILE *file);
It returns the position of the file pointer in the file. If an error occurs, it returns -1.
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("[Link]", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(file, "Hello, world!\n");
// Get current file position
long position = ftell(file);
printf("Current file position: %ld\n", position);
fclose(file);
return 0;
}
In this example, after writing "Hello, world!" to the file, ftell() gives the position of the file
pointer.
fseek()
The fseek() function is used to move the file pointer to a specific location in the file. You can
move it forward or backward.
int fseek(FILE *file, long offset, int whence);
offset: The number of bytes to move the file pointer.
whence: This tells the function where to start the movement from:
o SEEK_SET: Start from the beginning of the file.
o SEEK_CUR: Start from the current position.
o SEEK_END: Start from the end of the file.
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("[Link]", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Move file pointer to the 7th byte from the beginning
fseek(file, 7, SEEK_SET);
char ch = fgetc(file); // Read the character at the new position
printf("Character at position 7: %c\n", ch);
fclose(file);
return 0;
}
Here, we use fseek() to move the file pointer to the 7th byte and then read the character at that
position.
rewind()
The rewind() function resets the file pointer to the beginning of the file. It is equivalent to
calling fseek(file, 0, SEEK_SET).
void rewind(FILE *file);
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("[Link]", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Read and print the first character
char ch = fgetc(file);
printf("First character: %c\n", ch);
// Rewind to the beginning of the file
rewind(file);
// Read and print the first character again after rewinding
ch = fgetc(file);
printf("After rewind: %c\n", ch);
fclose(file);
return 0;
}
2. File Error Handling Functions
feof()
The feof() function checks if the end of the file has been reached.
int feof(FILE *file);
It returns a non-zero value if the end of the file has been reached, otherwise 0.
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("[Link]", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch); // Print each character
}
if (feof(file)) {
printf("\nEnd of file reached.\n");
}
fclose(file);
return 0;
}
In this example, we use fgetc() to read characters from the file until we reach the end of the
file. Once the end is reached, feof() returns true.
ferror()
The ferror() function checks if a file operation has encountered an error.
int ferror(FILE *file);
It returns a non-zero value if an error occurred during the last file operation; otherwise, it
returns 0.
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("nonexistent_file.txt", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Read the file to simulate an operation
fgetc(file);
// Check if an error occurred
if (ferror(file)) {
printf("Error occurred during file operation.\n");
}
fclose(file);
return 0;
}
In this case, since the file doesn't exist, ferror() will return an error.
3. Additional File Handling Functions
fputc() and fgetc()
fputc() is used to write a single character to a file.
int fputc(int ch, FILE *file);
fgetc() is used to read a single character from a file.
int fgetc(FILE *file);
Example (Writing and Reading One Character):
#include <stdio.h>
int main() {
FILE *file = fopen("[Link]", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write a single character
fputc('A', file);
fclose(file);
// Read the single character
file = fopen("[Link]", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
char ch = fgetc(file);
printf("Character read from file: %c\n", ch);
fclose(file);
return 0;
}
4. Buffering in File I/O
File I/O in C is typically buffered. This means that when you write to a file, data is temporarily
stored in a buffer before being written to the file. Similarly, when you read from a file, data is
first read into a buffer before being accessed by the program.
You can control buffering behavior using the following functions:
setvbuf(): Allows you to set the buffer for a file.
fflush(): Forces a flush of the buffer (i.e., writes the buffered data to the file).
fflush()
The fflush() function forces the file stream to flush its buffer, meaning any buffered data is
written to the file immediately.
int fflush(FILE *file);
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("[Link]", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(file, "Hello, world!");
fflush(file); // Forces the buffer to write the data to the file
fclose(file);
return 0;
}
Summary of Additional File Handling Functions:
Function Description
ftell() Returns the current position of the file pointer.
fseek() Moves the file pointer to a specified position.
rewind() Resets the file pointer to the beginning of the file.
feof() Checks if the end of the file has been reached.
ferror() Checks for errors in the file operations.
fputc() Writes a single character to the file.
fgetc() Reads a single character from the file.
fflush() Forces a flush of the file's output buffer to the file.
Function Description
setvbuf() Controls buffering for a file stream.
Practice Exercises:
1. Use fseek() to go to the end of the file and append data.
2. Write a program that copies the contents of one file to another using fgetc() and fputc().
3. Create a program that writes an array of integers to a binary file using fwrite() and reads it
back using fread().
These functions give you more control over how you interact with files in C. Let me know if
you'd like further explanation or examples!
String manipulation in C is an important part of programming. Strings in C are essentially arrays
of characters, and they are handled a little differently from other data types like integers or floats.
C provides a set of functions to manipulate strings, such as copying, concatenating, comparing,
and searching for characters or substrings.
Basic String Handling in C
Defining Strings
In C, strings are represented as arrays of characters, ending with a null terminator ('\0'), which
signals the end of the string.
char str[] = "Hello, World!";
"Hello, World!" is a string literal.
str is an array of characters that includes the null terminator ('\0').
Alternatively, you can declare an empty string and manually assign values:
char str[20]; // Array with enough space for the string and null terminator
strcpy(str, "Hello");
Common String Functions in C
Here are some key functions from the string.h library for string manipulation:
1. strlen()
The strlen() function returns the length of a string, excluding the null terminator.
#include <string.h>
size_t strlen(const char *str);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
printf("Length of string: %zu\n", strlen(str)); // Outputs: 5
return 0;
}
2. strcpy()
The strcpy() function copies one string to another.
#include <string.h>
char *strcpy(char *dest, const char *src);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello";
char destination[20];
strcpy(destination, source); // Copy the source string to destination
printf("Destination: %s\n", destination); // Outputs: Hello
return 0;
}
3. strncpy()
The strncpy() function copies a specified number of characters from one string to another.
#include <string.h>
char *strncpy(char *dest, const char *src, size_t n);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[10];
strncpy(destination, source, 5); // Copies the first 5 characters
destination[5] = '\0'; // Manually add the null terminator
printf("Destination: %s\n", destination); // Outputs: Hello
return 0;
}
4. strcat()
The strcat() function concatenates two strings. It appends the source string to the destination
string.
#include <string.h>
char *strcat(char *dest, const char *src);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[] = " World!";
strcat(str1, str2); // Concatenate str2 to str1
printf("Concatenated string: %s\n", str1); // Outputs: Hello World!
return 0;
}
5. strncat()
The strncat() function concatenates a specified number of characters from one string to
another.
#include <string.h>
char *strncat(char *dest, const char *src, size_t n);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[] = " World!";
strncat(str1, str2, 3); // Concatenate only the first 3 characters of
str2
printf("Concatenated string: %s\n", str1); // Outputs: Hello Wor
return 0;
}
6. strcmp()
The strcmp() function compares two strings lexicographically. It returns:
0 if the strings are equal.
A positive value if the first string is lexicographically greater.
A negative value if the first string is lexicographically smaller.
#include <string.h>
int strcmp(const char *str1, const char *str2);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2); // Compare str1 and str2
if (result == 0) {
printf("Strings are equal.\n");
} else if (result > 0) {
printf("str1 is greater than str2.\n");
} else {
printf("str1 is less than str2.\n");
}
return 0;
}
7. strncmp()
The strncmp() function compares the first n characters of two strings.
#include <string.h>
int strncmp(const char *str1, const char *str2, size_t n);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, World!";
char str2[] = "Hello, Universe!";
int result = strncmp(str1, str2, 5); // Compare the first 5 characters
if (result == 0) {
printf("The first 5 characters are equal.\n");
} else {
printf("The first 5 characters are not equal.\n");
}
return 0;
}
8. strchr()
The strchr() function searches for the first occurrence of a character in a string. It returns a
pointer to the character if found, or NULL if not found.
#include <string.h>
char *strchr(const char *str, int c);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *ptr = strchr(str, 'o'); // Find the first occurrence of 'o'
if (ptr != NULL) {
printf("Found 'o' at position: %ld\n", ptr - str); // Outputs the
position
} else {
printf("'o' not found.\n");
}
return 0;
}
9. strrchr()
The strrchr() function searches for the last occurrence of a character in a string.
#include <string.h>
char *strrchr(const char *str, int c);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *ptr = strrchr(str, 'o'); // Find the last occurrence of 'o'
if (ptr != NULL) {
printf("Found 'o' at position: %ld\n", ptr - str); // Outputs the
position
} else {
printf("'o' not found.\n");
}
return 0;
}
10. strstr()
The strstr() function finds the first occurrence of a substring in a string.
#include <string.h>
char *strstr(const char *haystack, const char *needle);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *ptr = strstr(str, "World"); // Find the substring "World"
if (ptr != NULL) {
printf("Substring found at position: %ld\n", ptr - str); // Outputs
the position
} else {
printf("Substring not found.\n");
}
return 0;
}
String Tokenization (Tokenizing Strings)
The strtok() function splits a string into tokens based on delimiters. It returns a pointer to the
next token each time it's called.
#include <string.h>
char *strtok(char *str, const char *delim);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World! Welcome to C programming.";
char *token = strtok(str, " ,.!"); // Split string by spaces, commas,
dots, or exclamations
while (token != NULL) {
printf("Token: %s\n", token);
token = strtok(NULL, " ,.!");
}
return 0;
}
String Manipulation Summary
Function Description
strlen() Returns the length of a string (excluding the null terminator).
strcpy() Copies a string to another string.
strncpy() Copies a specified number of characters from one string to another.
strcat() Concatenates two strings.
strncat() Concatenates a specified number of characters from one string to another.
strcmp() Compares two strings lexicographically.
strncmp() Compares a specified number of characters of two strings.
strchr() Finds the first occurrence of a character in a string.
strrchr() Finds the last occurrence of a character in a string.
Function Description
strstr() Finds the first occurrence of a substring in a string.
strtok() Tokenizes a string based on delimiters.
Practice Exercises:
1. Write a program that reverses a string.
2. Create a function that checks if a string is a palindrome.
3. Write a program that finds all occurrences of a substring within a string.
Let me know if you'd like further examples or explanations!