Projects & program guide
Only look at this resource once you have great understanding of the document aboveâ
đ Course Overviewâ
Welcome to the comprehensive C Programming repository aligned with MJBC111 curriculum! This resource provides complete coverage of C programming from basics to advanced concepts, with practical examples, exercises, and detailed explanations for each topic.
đŻ Course Learning Outcomesâ
Upon completing this course, you will:
- CO1: Master the fundamental concepts of C programming language
- CO2: Apply logical problem-solving techniques using C
- CO3: Implement modular programming using functions
- CO4: Design and utilize structures and unions effectively
- CO5: Understand memory management and file handling operations
đ Table of Contentsâ
- Unit 1: Overview of C
- Unit 2: Constants, Variables, Data Types
- Unit 3: Decision Making and Branching
- Unit 4: Concepts of Loops
- Unit 5: Concepts on Arrays
- Unit 6: Understanding Functions - Part 1
- Unit 7: Understanding Functions - Part 2
- Unit 8: Understanding Pointers - Introduction
- Unit 9: Programming with Pointers
- Unit 10: Characters and Strings
Unit 1: Overview of Câ
đ Introduction to C Languageâ
C is a powerful, general-purpose programming language developed by Dennis Ritchie at Bell Labs in 1972. It combines the features of low-level and high-level languages, making it ideal for system programming and application development.
đ Basic Structure of a C Programâ
/*
* Basic Structure of a C Program
* Every C program follows this fundamental structure
*/
#include <stdio.h> // Preprocessor directive - includes standard I/O library
// Main function - Entry point of every C program
int main() {
// Variable declarations
int number = 10;
// Program statements
printf("Hello, World!\n");
printf("Number is: %d\n", number);
// Return statement - indicates successful execution
return 0;
}
đ Your First C Programâ
/*
* Program: Hello World
* Description: Displays a welcome message
* Key Concepts: printf, main function, return statement
*/
#include <stdio.h>
int main() {
printf("Welcome to C Programming!\n");
printf("This is MJBC111 Course\n");
return 0;
}
Output:
Welcome to C Programming!
This is MJBC111 Course
đ Program Execution Processâ
The C program execution involves four main stages:
- Preprocessing: Handles directives like
#includeand#define - Compilation: Converts source code to assembly code
- Assembly: Converts assembly code to machine code (object file)
- Linking: Links object files with libraries to create executable
Unit 2: Constants, Variables, Data Types, Operators and Expressionsâ
đ Data Types in Câ
/*
* Program: Data Types Demonstration
* Shows all primitive data types in C with their sizes
*/
#include <stdio.h>
int main() {
// Integer types
int integer_var = 42;
short short_var = 100;
long long_var = 1000000L;
// Floating-point types
float float_var = 3.14f;
double double_var = 3.141592653589;
// Character type
char char_var = 'A';
// Display values and sizes
printf("Integer: %d (Size: %lu bytes)\n", integer_var, sizeof(int));
printf("Short: %d (Size: %lu bytes)\n", short_var, sizeof(short));
printf("Long: %ld (Size: %lu bytes)\n", long_var, sizeof(long));
printf("Float: %.2f (Size: %lu bytes)\n", float_var, sizeof(float));
printf("Double: %.10f (Size: %lu bytes)\n", double_var, sizeof(double));
printf("Character: %c (Size: %lu bytes)\n", char_var, sizeof(char));
return 0;
}
đ˘ Constants and Variablesâ
/*
* Program: Constants and Variables
* Demonstrates different ways to declare constants and variables
*/
#include <stdio.h>
#define PI 3.14159 // Symbolic constant using #define
int main() {
// Constants
const int MAX_SIZE = 100; // Constant using const keyword
const float GRAVITY = 9.81f;
// Variables
int count = 0;
float temperature = 25.5;
char grade = 'A';
// Variable assignment and modification
count = 10;
temperature = temperature + 5.0;
printf("Constants:\n");
printf("PI = %.5f\n", PI);
printf("MAX_SIZE = %d\n", MAX_SIZE);
printf("GRAVITY = %.2f\n\n", GRAVITY);
printf("Variables:\n");
printf("Count = %d\n", count);
printf("Temperature = %.1f°C\n", temperature);
printf("Grade = %c\n", grade);
return 0;
}
âď¸ Operators in Câ
/*
* Program: Complete Operators Demonstration
* Shows all types of operators with examples
*/
#include <stdio.h>
int main() {
int a = 10, b = 3, result;
printf("=== Arithmetic Operators ===\n");
printf("a = %d, b = %d\n", a, b);
printf("Addition: a + b = %d\n", a + b);
printf("Subtraction: a - b = %d\n", a - b);
printf("Multiplication: a * b = %d\n", a * b);
printf("Division: a / b = %d\n", a / b);
printf("Modulus: a %% b = %d\n\n", a % b);
printf("=== Relational Operators ===\n");
printf("a > b: %d\n", a > b); // 1 (true)
printf("a < b: %d\n", a < b); // 0 (false)
printf("a >= b: %d\n", a >= b); // 1 (true)
printf("a <= b: %d\n", a <= b); // 0 (false)
printf("a == b: %d\n", a == b); // 0 (false)
printf("a != b: %d\n\n", a != b); // 1 (true)
printf("=== Logical Operators ===\n");
int x = 1, y = 0;
printf("x = %d (true), y = %d (false)\n", x, y);
printf("x && y: %d\n", x && y); // AND: 0 (false)
printf("x || y: %d\n", x || y); // OR: 1 (true)
printf("!x: %d\n", !x); // NOT: 0 (false)
printf("!y: %d\n\n", !y); // NOT: 1 (true)
printf("=== Increment/Decrement Operators ===\n");
int n = 5;
printf("Initial n = %d\n", n);
printf("n++ = %d (post-increment)\n", n++);
printf("Now n = %d\n", n);
printf("++n = %d (pre-increment)\n", ++n);
printf("n-- = %d (post-decrement)\n", n--);
printf("Now n = %d\n", n);
printf("--n = %d (pre-decrement)\n\n", --n);
printf("=== Conditional (Ternary) Operator ===\n");
int max = (a > b) ? a : b;
printf("Maximum of %d and %d is: %d\n", a, b, max);
return 0;
}
đ§Ž Type Conversionâ
/*
* Program: Type Conversion
* Demonstrates implicit and explicit type conversion
*/
#include <stdio.h>
int main() {
// Implicit type conversion (automatic)
int int_num = 10;
float float_num = 5.5;
float result = int_num + float_num; // int automatically converted to float
printf("=== Implicit Type Conversion ===\n");
printf("int_num = %d, float_num = %.1f\n", int_num, float_num);
printf("Result (int + float) = %.1f\n\n", result);
// Explicit type conversion (type casting)
printf("=== Explicit Type Conversion ===\n");
float division1 = int_num / 3; // Integer division
float division2 = (float)int_num / 3; // Float division with casting
printf("Without casting: %d / 3 = %.2f\n", int_num, division1);
printf("With casting: (float)%d / 3 = %.2f\n", int_num, division2);
// Character to integer conversion
char ch = 'A';
int ascii_value = (int)ch;
printf("\nCharacter '%c' has ASCII value: %d\n", ch, ascii_value);
return 0;
}
Unit 3: Decision Making and Branchingâ
đ If Statementsâ
/*
* Program: If Statement Variations
* Demonstrates simple if, if-else, and nested if statements
*/
#include <stdio.h>
int main() {
int marks;
printf("Enter your marks (0-100): ");
scanf("%d", &marks);
// Simple if statement
if (marks >= 40) {
printf("You passed!\n");
}
// If-else statement
if (marks >= 80) {
printf("Grade: Excellent\n");
} else {
printf("Grade: Good effort, keep improving!\n");
}
// Nested if-else statements (Grade calculation)
printf("\nDetailed Grade Analysis:\n");
if (marks >= 90) {
printf("Grade: A+ (Outstanding)\n");
} else if (marks >= 80) {
printf("Grade: A (Excellent)\n");
} else if (marks >= 70) {
printf("Grade: B (Very Good)\n");
} else if (marks >= 60) {
printf("Grade: C (Good)\n");
} else if (marks >= 50) {
printf("Grade: D (Average)\n");
} else if (marks >= 40) {
printf("Grade: E (Pass)\n");
} else {
printf("Grade: F (Fail)\n");
}
return 0;
}
đŻ Switch-Case Statementâ
/*
* Program: Calculator using Switch-Case
* Demonstrates switch-case with multiple cases
*/
#include <stdio.h>
int main() {
float num1, num2, result;
char operator;
printf("Simple Calculator\n");
printf("Enter first number: ");
scanf("%f", &num1);
printf("Enter operator (+, -, *, /, %%): ");
scanf(" %c", &operator); // Space before %c to consume newline
printf("Enter second number: ");
scanf("%f", &num2);
switch(operator) {
case '+':
result = num1 + num2;
printf("%.2f + %.2f = %.2f\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("%.2f - %.2f = %.2f\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("%.2f * %.2f = %.2f\n", num1, num2, result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("%.2f / %.2f = %.2f\n", num1, num2, result);
} else {
printf("Error: Division by zero!\n");
}
break;
case '%':
if (num2 != 0) {
result = (int)num1 % (int)num2;
printf("%d %% %d = %d\n", (int)num1, (int)num2, (int)result);
} else {
printf("Error: Modulo by zero!\n");
}
break;
default:
printf("Invalid operator!\n");
}
return 0;
}
Unit 4: Concepts of Loopsâ
đ While Loopâ
/*
* Program: While Loop Examples
* Demonstrates while loop with different use cases
*/
#include <stdio.h>
int main() {
// Example 1: Print numbers 1 to 10
printf("=== Counting with While Loop ===\n");
int i = 1;
while (i <= 10) {
printf("%d ", i);
i++;
}
printf("\n\n");
// Example 2: Sum of digits
printf("=== Sum of Digits ===\n");
int number, temp, sum = 0;
printf("Enter a number: ");
scanf("%d", &number);
temp = number;
while (temp > 0) {
sum += temp % 10; // Add last digit to sum
temp = temp / 10; // Remove last digit
}
printf("Sum of digits of %d = %d\n\n", number, sum);
// Example 3: Factorial calculation
printf("=== Factorial Calculation ===\n");
int n, factorial = 1;
printf("Enter a number for factorial: ");
scanf("%d", &n);
int j = n;
while (j > 0) {
factorial *= j;
j--;
}
printf("%d! = %d\n", n, factorial);
return 0;
}
đ Do-While Loopâ
/*
* Program: Do-While Loop
* Menu-driven program demonstrating do-while
*/
#include <stdio.h>
int main() {
int choice;
float num1, num2;
do {
printf("\n=== MENU ===\n");
printf("1. Add two numbers\n");
printf("2. Multiply two numbers\n");
printf("3. Check even/odd\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Enter two numbers: ");
scanf("%f %f", &num1, &num2);
printf("Sum = %.2f\n", num1 + num2);
break;
case 2:
printf("Enter two numbers: ");
scanf("%f %f", &num1, &num2);
printf("Product = %.2f\n", num1 * num2);
break;
case 3:
printf("Enter a number: ");
int num;
scanf("%d", &num);
if (num % 2 == 0)
printf("%d is even\n", num);
else
printf("%d is odd\n", num);
break;
case 4:
printf("Exiting program. Goodbye!\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 4);
return 0;
}
đ For Loopâ
/*
* Program: For Loop Patterns
* Demonstrates for loops with pattern printing
*/
#include <stdio.h>
int main() {
int n;
printf("Enter number of rows: ");
scanf("%d", &n);
// Pattern 1: Right triangle
printf("\n=== Right Triangle Pattern ===\n");
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
// Pattern 2: Number pyramid
printf("\n=== Number Pyramid ===\n");
for (int i = 1; i <= n; i++) {
// Print spaces
for (int j = 1; j <= n - i; j++) {
printf(" ");
}
// Print numbers
for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
// Pattern 3: Multiplication table
printf("\n=== Multiplication Table ===\n");
printf("Enter a number: ");
int num;
scanf("%d", &num);
for (int i = 1; i <= 10; i++) {
printf("%d Ă %d = %d\n", num, i, num * i);
}
return 0;
}
đ Break and Continueâ
/*
* Program: Break and Continue Statements
* Shows control flow with break and continue
*/
#include <stdio.h>
int main() {
// Example 1: Break statement
printf("=== Break Statement ===\n");
printf("Finding first number divisible by 7 between 1 and 30:\n");
for (int i = 1; i <= 30; i++) {
if (i % 7 == 0) {
printf("Found: %d\n", i);
break; // Exit loop when first match found
}
}
// Example 2: Continue statement
printf("\n=== Continue Statement ===\n");
printf("Print all numbers from 1 to 10 except multiples of 3:\n");
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue; // Skip current iteration
}
printf("%d ", i);
}
printf("\n");
// Example 3: Prime number checker with optimization
printf("\n=== Prime Number Checker ===\n");
int num, isPrime = 1;
printf("Enter a number: ");
scanf("%d", &num);
if (num <= 1) {
isPrime = 0;
} else {
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
isPrime = 0;
break; // No need to check further
}
}
}
if (isPrime)
printf("%d is a prime number\n", num);
else
printf("%d is not a prime number\n", num);
return 0;
}
Unit 5: Concepts on Arraysâ
đŚ Single Dimensional Arraysâ
/*
* Program: Single Dimensional Arrays
* Array declaration, initialization, and operations
*/
#include <stdio.h>
int main() {
// Different ways to declare and initialize arrays
int numbers[5] = {10, 20, 30, 40, 50}; // Fully initialized
int scores[] = {85, 90, 78, 92, 88}; // Size determined by initializer
int values[10] = {1, 2, 3}; // Partially initialized (rest are 0)
int marks[5]; // Uninitialized array
// Input array elements
printf("=== Array Input ===\n");
printf("Enter 5 marks: ");
for (int i = 0; i < 5; i++) {
scanf("%d", &marks[i]);
}
// Display array elements
printf("\n=== Array Elements ===\n");
printf("Marks: ");
for (int i = 0; i < 5; i++) {
printf("%d ", marks[i]);
}
printf("\n");
// Array operations
int sum = 0, max = marks[0], min = marks[0];
for (int i = 0; i < 5; i++) {
sum += marks[i];
if (marks[i] > max)
max = marks[i];
if (marks[i] < min)
min = marks[i];
}
float average = (float)sum / 5;
printf("\n=== Array Statistics ===\n");
printf("Sum: %d\n", sum);
printf("Average: %.2f\n", average);
printf("Maximum: %d\n", max);
printf("Minimum: %d\n", min);
// Array reversal
printf("\n=== Array Reversal ===\n");
printf("Original: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
// Reverse the array
for (int i = 0; i < 5/2; i++) {
int temp = numbers[i];
numbers[i] = numbers[4 - i];
numbers[4 - i] = temp;
}
printf("\nReversed: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
đ Two-Dimensional Arraysâ
/*
* Program: Matrix Operations
* 2D arrays for matrix manipulation
*/
#include <stdio.h>
int main() {
int rows = 3, cols = 3;
int matrix1[3][3], matrix2[3][3], result[3][3];
// Input first matrix
printf("=== Enter First Matrix (3x3) ===\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix1[i][j]);
}
}
// Input second matrix
printf("\n=== Enter Second Matrix (3x3) ===\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix2[i][j]);
}
}
// Matrix addition
printf("\n=== Matrix Addition ===\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
printf("%3d ", result[i][j]);
}
printf("\n");
}
// Matrix multiplication
printf("\n=== Matrix Multiplication ===\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = 0;
for (int k = 0; k < cols; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
printf("%5d ", result[i][j]);
}
printf("\n");
}
// Transpose of first matrix
printf("\n=== Transpose of First Matrix ===\n");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
printf("%3d ", matrix1[j][i]);
}
printf("\n");
}
return 0;
}
Unit 6: Understanding Functions - Part 1â
đ Function Basicsâ
/*
* Program: Function Fundamentals
* Function definition, declaration, and calling
*/
#include <stdio.h>
// Function declarations (prototypes)
int add(int a, int b);
float calculateArea(float radius);
void printMessage(void);
int factorial(int n);
int main() {
// Calling functions with return values
int sum = add(10, 20);
printf("Sum of 10 and 20 = %d\n", sum);
float area = calculateArea(5.0);
printf("Area of circle with radius 5 = %.2f\n", area);
// Calling void function
printMessage();
// Factorial calculation
int num = 5;
int fact = factorial(num);
printf("Factorial of %d = %d\n", num, fact);
return 0;
}
// Function definitions
// Function with parameters and return value
int add(int a, int b) {
return a + b;
}
// Function with float return type
float calculateArea(float radius) {
const float PI = 3.14159;
return PI * radius * radius;
}
// Void function (no return value)
void printMessage(void) {
printf("Hello from a function!\n");
}
// Recursive function
int factorial(int n) {
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
đž Storage Classesâ
/*
* Program: Storage Classes
* auto, static, extern, register
*/
#include <stdio.h>
// Global variable (extern storage class)
int global_var = 100;
// Function to demonstrate static variable
void demonstrateStatic() {
static int static_var = 0; // Retains value between calls
int auto_var = 0; // Reinitialized each call
static_var++;
auto_var++;
printf("Static variable: %d, Auto variable: %d\n", static_var, auto_var);
}
// External variable declaration
extern int global_var;
int main() {
// Auto storage class (default for local variables)
auto int local_var = 10; // 'auto' keyword is optional
// Register storage class (suggestion for faster access)
register int counter = 0;
printf("=== Storage Classes Demo ===\n");
printf("Global variable: %d\n", global_var);
printf("Local variable: %d\n", local_var);
// Demonstrate static variable behavior
printf("\n=== Static vs Auto Variables ===\n");
for (int i = 0; i < 3; i++) {
demonstrateStatic();
}
// Scope demonstration
printf("\n=== Variable Scope ===\n");
{
int block_var = 50; // Block scope
printf("Inside block: block_var = %d\n", block_var);
printf("Can access global_var = %d\n", global_var);
}
// block_var is not accessible here
return 0;
}
Unit 7: Understanding Functions - Part 2â
đ Types of Functions and Argument Passingâ
/*
* Program: Function Types and Argument Passing
* Call by value, call by reference, function types
*/
#include <stdio.h>
// Call by value - original values not modified
void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
printf("Inside swapByValue: a = %d, b = %d\n", a, b);
}
// Call by reference using pointers - original values modified
void swapByReference(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
printf("Inside swapByReference: a = %d, b = %d\n", *a, *b);
}
// Function with no parameters and no return value
void greet() {
printf("Welcome to C Programming!\n");
}
// Function with parameters and no return value
void displaySum(int a, int b) {
printf("Sum of %d and %d = %d\n", a, b, a + b);
}
// Function with no parameters but return value
int getRandomNumber() {
return 42; // Simplified for demonstration
}
// Function with parameters and return value
float calculateAverage(float a, float b, float c) {
return (a + b + c) / 3.0;
}
int main() {
printf("=== Function Types ===\n");
// Type 1: No parameters, no return
greet();
// Type 2: Parameters, no return
displaySum(10, 20);
// Type 3: No parameters, with return
int random = getRandomNumber();
printf("Random number: %d\n", random);
// Type 4: Parameters and return
float avg = calculateAverage(10.5, 20.3, 15.7);
printf("Average: %.2f\n", avg);
printf("\n=== Call by Value vs Call by Reference ===\n");
int x = 10, y = 20;
printf("Before swap: x = %d, y = %d\n", x, y);
swapByValue(x, y);
printf("After swapByValue: x = %d, y = %d\n", x, y);
swapByReference(&x, &y);
printf("After swapByReference: x = %d, y = %d\n", x, y);
return 0;
}
đ Recursionâ
/*
* Program: Recursion Examples
* Multiple recursive function implementations
*/
#include <stdio.h>
// Factorial using recursion
int factorial(int n) {
if (n <= 1)
return 1;
return n * factorial(n - 1);
}
// Fibonacci using recursion
int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Tower of Hanoi
void towerOfHanoi(int n, char source, char destination, char auxiliary) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", source, destination);
return;
}
towerOfHanoi(n - 1, source, auxiliary, destination);
printf("Move disk %d from %c to %c\n", n, source, destination);
towerOfHanoi(n - 1, auxiliary, destination, source);
}
// Sum of digits using recursion
int sumOfDigits(int n) {
if (n == 0)
return 0;
return (n % 10) + sumOfDigits(n / 10);
}
// Power calculation using recursion
int power(int base, int exp) {
if (exp == 0)
return 1;
return base * power(base, exp - 1);
}
int main() {
printf("=== Recursion Examples ===\n\n");
// Factorial
int n = 5;
printf("Factorial of %d = %d\n", n, factorial(n));
// Fibonacci series
printf("\nFibonacci series (first 10 terms): ");
for (int i = 0; i < 10; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");
// Tower of Hanoi
printf("\nTower of Hanoi with 3 disks:\n");
towerOfHanoi(3, 'A', 'C', 'B');
// Sum of digits
int num = 12345;
printf("\nSum of digits of %d = %d\n", num, sumOfDigits(num));
// Power
printf("2^5 = %d\n", power(2, 5));
return 0;
}
đ Passing Arrays to Functionsâ
/*
* Program: Arrays and Functions
* Passing arrays to functions
*/
#include <stdio.h>
// Function to find sum of array elements
int arraySum(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
// Function to find maximum element
int findMax(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// Function to sort array (bubble sort)
void sortArray(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]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Function to reverse array
void reverseArray(int arr[], int size) {
for (int i = 0; i < size / 2; i++) {
int temp = arr[i];
arr[i] = arr[size - 1 - i];
arr[size - 1 - i] = temp;
}
}
// Function to work with 2D array
void print2DArray(int arr[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
printf("%3d ", arr[i][j]);
}
printf("\n");
}
}
int main() {
int numbers[] = {64, 34, 25, 12, 22, 11, 90};
int size = sizeof(numbers) / sizeof(numbers[0]);
printf("=== Array Operations with Functions ===\n");
printf("Original array: ");
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// Sum of elements
printf("Sum of elements: %d\n", arraySum(numbers, size));
// Maximum element
printf("Maximum element: %d\n", findMax(numbers, size));
// Sort array
sortArray(numbers, size);
printf("Sorted array: ");
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// Reverse array
reverseArray(numbers, size);
printf("Reversed array: ");
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// 2D array example
printf("\n=== 2D Array Example ===\n");
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
print2DArray(matrix, 2);
return 0;
}
Unit 8: Understanding Pointers - Introductionâ
đŻ Pointer Basicsâ
/*
* Program: Introduction to Pointers
* Understanding addresses and pointer declaration
*/
#include <stdio.h>
int main() {
// Variable declaration
int num = 42;
float salary = 50000.50;
char grade = 'A';
// Pointer declaration
int *ptr_int; // Pointer to integer
float *ptr_float; // Pointer to float
char *ptr_char; // Pointer to char
// Pointer initialization (storing addresses)
ptr_int = #
ptr_float = &salary;
ptr_char = &grade;
printf("=== Understanding Addresses ===\n");
printf("Variable\tValue\t\tAddress\n");
printf("----------------------------------------\n");
printf("num\t\t%d\t\t%p\n", num, (void*)&num);
printf("salary\t\t%.2f\t%p\n", salary, (void*)&salary);
printf("grade\t\t%c\t\t%p\n", grade, (void*)&grade);
printf("\n=== Pointer Variables ===\n");
printf("Pointer\t\tStored Address\t\tPointed Value\n");
printf("--------------------------------------------------------\n");
printf("ptr_int\t\t%p\t\t%d\n", (void*)ptr_int, *ptr_int);
printf("ptr_float\t%p\t\t%.2f\n", (void*)ptr_float, *ptr_float);
printf("ptr_char\t%p\t\t%c\n", (void*)ptr_char, *ptr_char);
// Null pointer
int *null_ptr = NULL;
printf("\n=== Null Pointer ===\n");
printf("null_ptr = %p\n", (void*)null_ptr);
// Pointer to pointer
int **ptr_to_ptr = &ptr_int;
printf("\n=== Pointer to Pointer ===\n");
printf("ptr_to_ptr stores: %p\n", (void*)ptr_to_ptr);
printf("ptr_to_ptr points to ptr_int which stores: %p\n", (void*)*ptr_to_ptr);
printf("Final value accessed: %d\n", **ptr_to_ptr);
// Size of pointers
printf("\n=== Pointer Sizes ===\n");
printf("Size of int pointer: %lu bytes\n", sizeof(int*));
printf("Size of float pointer: %lu bytes\n", sizeof(float*));
printf("Size of char pointer: %lu bytes\n", sizeof(char*));
printf("Size of void pointer: %lu bytes\n", sizeof(void*));
return 0;
}
Unit 9: Programming with Pointersâ
đ§ Pointer Arithmetic and Expressionsâ
/*
* Program: Pointer Arithmetic
* Operations on pointers
*/
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // Points to first element
printf("=== Pointer Arithmetic with Arrays ===\n");
printf("Array elements: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n\n");
// Different ways to access array elements
printf("Access methods:\n");
printf("Using array indexing: arr[2] = %d\n", arr[2]);
printf("Using pointer: *(ptr + 2) = %d\n", *(ptr + 2));
printf("Using pointer indexing: ptr[2] = %d\n", ptr[2]);
// Pointer increment
printf("\n=== Pointer Increment ===\n");
printf("Initial ptr points to: %d (address: %p)\n", *ptr, (void*)ptr);
ptr++;
printf("After ptr++: %d (address: %p)\n", *ptr, (void*)ptr);
ptr += 2;
printf("After ptr += 2: %d (address: %p)\n", *ptr, (void*)ptr);
// Pointer comparison
int *ptr1 = &arr[1];
int *ptr2 = &arr[3];
printf("\n=== Pointer Comparison ===\n");
printf("ptr1 points to arr[1] = %d\n", *ptr1);
printf("ptr2 points to arr[3] = %d\n", *ptr2);
if (ptr1 < ptr2) {
printf("ptr1 comes before ptr2 in memory\n");
}
// Pointer difference
printf("Number of elements between ptr2 and ptr1: %ld\n", ptr2 - ptr1);
// Pointer expressions
printf("\n=== Pointer Expressions ===\n");
int x = 10, y = 20;
int *p = &x, *q = &y;
printf("x = %d, y = %d\n", x, y);
printf("*p = %d, *q = %d\n", *p, *q);
printf("*p + *q = %d\n", *p + *q);
printf("*p * *q = %d\n", *p * *q);
// Modifying values through pointers
*p = 100;
*q = 200;
printf("After modification: x = %d, y = %d\n", x, y);
return 0;
}
đĄ Advanced Pointer Operationsâ
/*
* Program: Advanced Pointer Usage
* Function pointers and void pointers
*/
#include <stdio.h>
// Functions for function pointer demo
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
// Function that takes function pointer as parameter
int calculate(int x, int y, int (*operation)(int, int)) {
return operation(x, y);
}
int main() {
// Void pointer - can point to any data type
printf("=== Void Pointers ===\n");
void *void_ptr;
int num = 10;
float fnum = 3.14;
void_ptr = #
printf("Integer through void pointer: %d\n", *(int*)void_ptr);
void_ptr = &fnum;
printf("Float through void pointer: %.2f\n", *(float*)void_ptr);
// Function pointers
printf("\n=== Function Pointers ===\n");
int (*func_ptr)(int, int); // Declare function pointer
func_ptr = add;
printf("10 + 5 = %d\n", func_ptr(10, 5));
func_ptr = subtract;
printf("10 - 5 = %d\n", func_ptr(10, 5));
func_ptr = multiply;
printf("10 * 5 = %d\n", func_ptr(10, 5));
// Using function pointer as parameter
printf("\n=== Function Pointer as Parameter ===\n");
printf("Calculate(20, 10, add) = %d\n", calculate(20, 10, add));
printf("Calculate(20, 10, subtract) = %d\n", calculate(20, 10, subtract));
// Array of function pointers
printf("\n=== Array of Function Pointers ===\n");
int (*operations[3])(int, int) = {add, subtract, multiply};
char *op_names[] = {"Addition", "Subtraction", "Multiplication"};
for (int i = 0; i < 3; i++) {
printf("%s: 15 and 3 = %d\n", op_names[i], operations[i](15, 3));
}
return 0;
}
Unit 10: Characters and Stringsâ
đ String Operationsâ
/*
* Program: String Handling
* String declaration, initialization, and operations
*/
#include <stdio.h>
#include <string.h>
int main() {
// String declaration and initialization
char str1[20] = "Hello"; // Array initialization
char str2[] = "World"; // Size determined automatically
char str3[20]; // Uninitialized
char str4[20] = {'C', ' ', 'P', 'r', 'o', 'g', '\0'}; // Character array
printf("=== String Declaration Methods ===\n");
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);
printf("str4: %s\n", str4);
// String input
printf("\n=== String Input ===\n");
printf("Enter a string (single word): ");
scanf("%s", str3);
printf("You entered: %s\n", str3);
// Clear input buffer
while (getchar() != '\n');
// Gets alternative (safer)
char fullName[50];
printf("Enter your full name: ");
fgets(fullName, sizeof(fullName), stdin);
// Remove newline from fgets
fullName[strcspn(fullName, "\n")] = '\0';
printf("Your name: %s\n", fullName);
// String length
printf("\n=== String Operations ===\n");
printf("Length of '%s': %lu\n", str1, strlen(str1));
// String copy
char copy[20];
strcpy(copy, str1);
printf("Copied string: %s\n", copy);
// String concatenation
strcat(str1, " ");
strcat(str1, str2);
printf("Concatenated: %s\n", str1);
// String comparison
char pass1[] = "password";
char pass2[] = "password";
char pass3[] = "Password";
printf("\n=== String Comparison ===\n");
if (strcmp(pass1, pass2) == 0) {
printf("'%s' and '%s' are equal\n", pass1, pass2);
}
if (strcmp(pass1, pass3) != 0) {
printf("'%s' and '%s' are not equal (case sensitive)\n", pass1, pass3);
}
// Character operations
printf("\n=== Character Operations ===\n");
char ch = 'A';
printf("Character: %c\n", ch);
printf("ASCII value: %d\n", ch);
printf("Next character: %c\n", ch + 1);
printf("Lowercase: %c\n", ch + 32);
// String manipulation without library functions
printf("\n=== Manual String Operations ===\n");
char source[] = "Programming";
char destination[20];
int i;
// Manual string copy
for (i = 0; source[i] != '\0'; i++) {
destination[i] = source[i];
}
destination[i] = '\0';
printf("Manually copied: %s\n", destination);
// Manual string reversal
char reverse[20];
int len = 0;
while (source[len] != '\0') len++;
for (i = 0; i < len; i++) {
reverse[i] = source[len - 1 - i];
}
reverse[len] = '\0';
printf("Reversed string: %s\n", reverse);
return 0;
}