Welcome to the C Programming learning repository! This workspace tracks core programming concepts, daily progress, and problem-solving exercises in C.
- Day 1: Datatypes & Variables
- Day 2: Functions & Basic Concepts
- Day 3: Loops, Increment/Decrement, & Strings
- Day 4: Loops & Logical Reasoning
- Day 5: Arrays & Pointers
- Day 6: Searching Techniques
- Day 7: Sorting Techniques
- Day 8: Pattern Printing
- Day 9: Structures
- Day 10: File Handling
- Day 11: Data Structures & Algorithms
- Practice Problems: Loops & Number Theory
- Comprehensive Solved Practice Problems
This folder (00_Datatypes) covers basic and composite datatypes in C, their sizes in memory, and type conversions.
C supports several built-in datatypes representing integers, floating-point numbers, and characters:
char: Character type, typically occupies 1 byte.short: Short integer, typically 2 bytes.int: Standard integer, typically 4 bytes.long: Long integer, typically 4 or 8 bytes.float: Single-precision floating point, typically 4 bytes.double: Double-precision floating point, typically 8 bytes.unsigned int: Unsigned standard integer, holds non-negative numbers, typically 4 bytes.
Derived types are constructed from the basic types:
- Arrays: Fixed-size sequences of elements of the same type.
- Pointers: Variables that store the memory address of another variable.
- Structure (
struct): Group of variables of different types under a single name. The size is equal to or greater than the sum of its members due to memory alignment padding. - Union (
union): Similar to structures but all members share the same memory location. The total size is equal to the size of its largest member. - Enumeration (
enum): User-defined type consisting of a set of named integer constants.
- Implicit Conversion (Type Promotion): Automatic conversion by the compiler (e.g. promoting a
chartointin arithmetic). - Explicit Conversion (Type Casting): Manual conversion of type using the cast operator (e.g.
(int)double_var).
- Concepts: Declaring basic numeric variables (
int,float,double) and displaying them usingprintf. - Code Highlight:
int val = 50; float soumik = 20.0; double sourav = 2.0; printf("%d \n", val); printf("%f \n", soumik);
- Concepts: Comprehensive implementation demonstrating sizes of basic types, arrays/pointers, structs, unions, enums, and implicit/explicit type casting.
- Code Highlight (Structure, Union & Enum declaration):
struct Point { int x; int y; }; union Data { int integer_val; float float_val; char char_val; }; enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY };
This folder explores the core concepts of functions, user input/output, working with the standard math library, translating mathematical formulas into code, and using conditional statements to verify arithmetic relationships.
printf(): Used to print formatted output to the console. It utilizes placeholders called format specifiers (e.g.,%dfor integers,%ffor floats/doubles, and%lffor double precision floating-point numbers).scanf(): Used to read formatted input from the console. It requires:- A format specifier string (e.g.,
"%d%d"to read two integers). - The address-of operator (
&) prefixed to variable names (e.g.,&a,&b). The&operator tellsscanfwhere the variable is located in memory so it can directly store the user's input there.
- A format specifier string (e.g.,
-
Variables and Initialization: Variables must be declared with a data type (such as
int,float, ordouble) before they can be used. They can be initialized at declaration or assigned a value later. -
<math.h>Standard Library: Provides common mathematical operations.-
pow(base, exponent): Returns the value of$base^{exponent}$ . Note thatpowexpects arguments of typedoubleand returns adouble.
-
Important Note on Types: Assigning the return value of
pow()(which is adouble) to anintvariable (e.g.,int sum = pow(...)) will cause implicit type conversion, truncating any fractional part.
-
-
Basic Operators:
- Assignment operator:
= - Arithmetic operators:
+(addition),-(subtraction),*(multiplication),/(division).
- Assignment operator:
Functions break down complex problems into smaller, reusable blocks of code.
- Function Structure:
return_type function_name(parameter_type1 parameter1, parameter_type2 parameter2) { // function body // return statement (if return_type is not void) }
- Return Type: If a function does not return any value, its return type is declared as
void. - Parameters vs. Arguments:
- Parameters: The variables defined in the function's declaration/definition (e.g.,
double a, double b). - Arguments: The actual values passed to the function when calling it (e.g.,
addition(10.25, 52.63)).
- Parameters: The variables defined in the function's declaration/definition (e.g.,
- Float Precision Formatting: In
printf(), we can limit the decimal places of a floating-point number using%.NfwhereNis the number of decimal digits (e.g.,%.4fprints a float with 4 decimal places).
Functions make it easy to evaluate mathematical expressions at different data points. Instead of duplicating math formulas, we pass the independent variables as function parameters, calculate the expression value using library calls like pow(), and print or return the result. This simplifies evaluating expressions like
-
if-elseStatements: Allow decision-making in programs based on conditions.if (condition) { // executes if condition is true } else { // executes if condition is false }
-
Comparison Operator (
==): Used to check equality between two values. Do not confuse it with the assignment operator (=). -
Division Verification (Remainder Theorem / Division Algorithm):
$$\text{Dividend} = (\text{Divisor} \times \text{Quotient}) + \text{Remainder}$$ We can use standard variables to store each component, compute the right-hand side, and use anif-elsecondition to verify if the relation holds true.
- Concepts: Declaring integer variables, reading multiple variables using
scanf(), performing addition, and displaying results. - Code Summary:
int a, b; scanf("%d%d", &a, &b); int sum = a + b; printf("Sum is : %d", sum);
- Concepts: Using the
<math.h>library, variables initialization, thepow()function, and printing integer types using format specifiers. - Code Summary:
int sum = 0; sum = pow(23, 6); // Note: pow returns double, converted implicitly to int printf("%d", sum);
- Concepts: Declaring arithmetic functions (
addition,sub,multiplication,div), using parameter typesfloatanddouble, usingvoidreturn types, and formatting output precision using%.4f. - Code Summary:
void div(double a, double b) { printf("%.4f", a / b); // Output formatted to 4 decimal places }
-
Concepts: Translating polynomials/equations into C expressions using the
pow()library function, and evaluating the equations with different argument inputs. -
Equations Covered:
-
eqn1(x):$2x^2 + 3x - 2$ -
eqn2(x):$2x^2 - x + 1$ -
eqn3(x):$2x^3 + 2x^2 + 3x - 10$
-
- Concepts: Passing multiple arguments to a verification function, calculating expressions, and comparing results using
if-elsecontrol flow to verify division math. - Code Summary:
void reminder_theorem(double actual_divisable, double divisor, double res, double rem) { double divisable = (divisor * res) + rem; if (actual_divisable == divisable) { printf("The division is true"); } else { printf("The division is false"); } }
This folder (01_practice_problems) contains practical implementations and solutions demonstrating functions, mathematics in C, and pointer/memory addressing.
- Concepts: Character data types, type casting, and ASCII values.
- Summary: Converts a character variable
a(initialized to'R') to its corresponding integer ASCII representation using(int)type casting, then prints the output. - Code Highlight:
char a = 'R'; printf("%d", (int)a); // Prints ASCII value (82)
-
Concepts: Translating algebraic expressions, using
<math.h>'spow()function, and modular function design. -
Summary: Evaluates the quadratic expression
$x^2 - 2x + 3$ using a custom functionvoid equation(double x)and prints the result for input parameters$3$ and$2.0$ . -
Code Highlight:
void equation (double x ) { double sol = pow(x,2) - (2*x) + 3 ; printf("The solution of the equation is : %f\n", sol); }
- Concepts: Pointers, addresses, and variable storage in RAM.
- Summary: Prints the physical memory address where the integer variable
ais stored, using the address-of operator&and the%pformat specifier. - Code Highlight:
int a = 10; printf("%p", (void*)&a); // Prints the memory address of variable a
- Concepts: Right-angle triangle calculations, Pythagorean theorem formulas, and
<math.h>functions (sqrt,pow). - Summary: Implements three separate functions to calculate the hypotenuse, height, or base of a right-angled triangle, given the other two dimensions.
- Code Highlight:
void hypotenuse (double a, double b) { double hyp = sqrt(pow(a,2) + pow(b,2)); printf("The length of the hypotenuse is : %f\n", hyp); }
- A)
5.67 - B)
5.68 - C)
5.678900 - D)
5.7
- A)
*(dereference) - B)
%(modulo) - C)
&(address-of) - D)
&&(logical AND)
- A)
<stdio.h> - B)
<stdlib.h> - C)
<conio.h> - D)
<math.h>
- A) It returns
0by default. - B) It does not return any value.
- C) It can only accept integer parameters.
- D) It returns a null pointer.
- A)
=is used for comparison,==is used for assignment. - B)
=is used for assignment,==is used for equality comparison. - C) They are interchangeable.
- D)
=is for integer comparison,==is for float comparison.
void multiply(int a, int b) {
int result = a * b;
return result;
}int num;
printf("Enter a number: ");
scanf("%d", num);-
Custom Polynomial Evaluator: Write a program with a function named
evaluate_expression(double x)that computes and returns the value of:$$y = 5x^3 - 4x^2 + 2x - 15$$ In themainfunction, prompt the user for a value ofx, call the function, and print the resulting value ofyrounded to 3 decimal places. -
Calculator Extensions: Extend the program in calc.c by adding a remainder function
void find_remainder(int a, int b)using the modulo operator%that prints the remainder whenais divided byb. Remember that modulo operator only works with integers. -
Odd or Even Verifier: Write a custom function
void check_odd_even(int number)that prints whether a number isEvenorOddusing conditional statements (if-else) and the modulo operator%. Call this function insidemainusing values entered by the user.
💡 Click here to show Answers for Day 2 Exercises
- B (
%.2frounds the value to two decimal places, so5.6789becomes5.68). - C (The address-of operator
&passes the memory address of the variable toscanf). - D (
<math.h>declares mathematical functions likepow()). - B (
voidmeans the function does not return a value). - B (
=is assignment,==checks for equality).
- Error: The function has a return type of
void, but it contains areturn result;statement. Fix: Change the return type fromvoidtoint.int multiply(int a, int b) { return a * b; }
- Error: The
scanf()statement is missing the address-of operator&fornum. Fix: Add the&operator beforenum.scanf("%d", &num);
This directory (02_Strings) explores iterating control flows (while loops), pre- and post-increment/decrement operators, string input parsing, and custom print functions.
In C, the unary increment (++) and decrement (--) operators modify variables by 1. They can be applied in two ways:
- Prefix (
++x,--x): Increments or decrements the variable first, then evaluates the expression. - Postfix (
x++,x--): Evaluates the expression with the current value first, then increments or decrements the variable.
Warning
Sequence Points & Undefined Behavior (UB):
Writing expressions like res = i + ++i; or res = i++ + ++i; results in Undefined Behavior under the ISO C standard because a single variable is modified multiple times (or read and modified) without an intervening sequence point. Different compilers, optimization levels, or CPU architectures can produce different values. Always separate modifications into distinct instructions to ensure portability.
A while loop runs code blocks repeatedly as long as a condition evaluates to true.
- Loop Variable Update: To prevent an infinite loop, the control variable must be modified within the loop body such that the loop condition eventually evaluates to
false(e.g., counting down using--ior incrementing usingi++).
- Standard
scanf("%s", ...): Stops reading input at the first space, tab, or newline character. - Scanset
scanf("%[^\n]", name): Instructsscanfto read all characters (including spaces) until a newline (\n) is encountered. - Buffer Overflow Protection:
[!CAUTION] Using
scanf("%99[^\n]", name)whennameis declared aschar name[20]is unsafe! If the user inputs more than 19 characters, it overflows the array boundary, corrupting adjacent stack memory. Always restrict the scanset width tosizeof(buffer) - 1. Forchar name[20], use:scanf("%19[^\n]", name);
- Concepts: Unary prefix/postfix operator evaluation inside expressions.
- Summary: Demonstrates compound expression arithmetic using pre-increment, post-increment, and pre-decrement operators.
- Code Highlight:
int i = 0, j = 5, k = 9; int res = (i++) + (++j) + (--k); // 0 + 6 + 8 = 14 printf("%d", res); // Prints: 14
- Concepts: String arguments (character arrays) in function parameters.
- Summary: Passes multiple strings and an integer to a details displayer function
info(). - Code Highlight:
void info ( char name[], char college [], int roll ) { printf("Student's Name : %s\n", name); printf("Student's college name : %s \n", college); printf("Student's Roll no : %d \n", roll); }
- Concepts: Reading string inputs containing spaces using scansets.
- Summary: Demonstrates how to fetch an input line containing spaces using
[^\n]insidescanf. - Code Highlight:
char name[20]; scanf("%99[^\n]", name); // Note: Safe practice is to use %19[^\n] to prevent stack overflow printf("%s", name);
int x = 5;
int res = ++x + 2;- A)
7 - B)
8 - C)
6 - D) Undefined
- A)
%s - B)
%c - C)
%[^\n] - D)
%lf
3. To securely read a string into a buffer declared as char str[50], what is the best practice scanset call?
- A)
scanf("%49[^\n]", str); - B)
scanf("%50[^\n]", str); - C)
scanf("%[^\n]", str); - D)
scanf("%s", str);
int count = 5;
while (count > 0) {
printf("%d\n", count);
// Missing step?
}char major[15];
printf("Enter your major: ");
scanf("%29[^\n]", major);-
Robust Details Reader: Create a program that prompts the user for their name (up to 30 characters), college name (up to 50 characters), and roll number. Store these in variables, and print them out using the
info()format fromdetails.c. Make sure the input scan limits prevent buffer overflows. -
Sum of Natural Numbers: Write a program that prompts the user for a positive integer
$N$ , and calculates the sum of all natural numbers from$1$ to$N$ using awhileloop (e.g.$\text{sum} = 1 + 2 + \dots + N$ ).
💡 Click here to show Answers for Day 3 Exercises
- B (Prefix
++xchangesxto6first, then computes6 + 2 = 8). - C (Scanset
%[^\n]reads everything until a newline, which includes space characters). - A (Use
sizeof(buffer) - 1to leave room for the terminating null character\0).
- Error: The control variable
countis never updated inside the loop, creating an infinite loop. Fix: Decrementcountinside the loop body.int count = 5; while (count > 0) { printf("%d\n", count); count--; }
- Error: The format specifier
%29[^\n]allows reading up to 29 characters, but the target buffermajorhas a size of only 15 bytes. This causes a buffer overflow. Fix: Restrict the scan width to%14[^\n].char major[15]; scanf("%14[^\n]", major);
This directory (03_loops_and_logical_reasoning) focuses on loop logic (while and for loops), controlling iteration to prevent infinite executions, evaluating conditional operations, and parsing user input to run numeric calculations.
- Nested Conditional Statements (
if-else if-else): Evaluates a grade bounds range step-by-step. - Logical AND (
&&): Ensures multiple constraints are satisfied concurrently (e.g., checking if marks are between 10 and 15:marks < 15 && marks >= 10). - Input Range Validation: Handling unexpected user inputs gracefully by utilizing fallback
elseblocks for out-of-bound errors.
- Dynamic Table Ranges: Printing custom multiplication tables (
1to10) dynamically usingwhileloops based on user-supplied parameters. - Logical Loop Conditions: Using combined conditions like
num <= 10 && num < 11to reinforce loop invariant logic.
- Accumulators: Accumulating values across loop iterations (e.g.,
Factorial = fact * Factorial). - Loop Variable Decaying: Decreasing loop control variables inside the loop scope (e.g.,
fact = fact - 1or--fact) to ensure loop termination.
- Loop Structure: A compact loop notation with initialization, condition, and increment/decrement all defined in the header.
for (int i = 0; i <= 10; i++) { // Loop body }
- Concepts: Grading logic, boundary limits, conditional branches.
- Summary: Implements grading system boundaries from 0 to 15 (e.g. 15 = A, 10 to 14 = B, 5 to 9 = P, 0 to 4 = Fail).
- Code Highlight:
if (marks == 15) { printf("A"); } else if (marks < 15 && marks >= 10) { printf("B"); } else if (marks >= 5 && marks < 10) { printf("P"); } else if( marks < 5 && marks >= 0) { printf("Fail"); } else { printf("Enter the marks with in range (0-15)"); }
- Concepts: Multiplicative progression, iteration steps.
- Summary: Calculates the multiplication table of a user-entered number using a
whileloop from 1 to 10. - Code Highlight:
while (num <= 10 && num < 11) { cal = num * num_user; printf("%d * %d = %d \n", num, num_user, cal); ++num; }
- Concepts: Compact iteration framework,
forloops. - Summary: Demonstrates the framework of a basic
forloop, printing integers from 0 to 10. - Code Highlight:
for (int i = 0; i <= 10; i++) { printf("%d\n ", i); }
- Concepts: Countdown loop iteration, counter updates.
- Summary: Runs a countdown from 9 to 0, showing how updating the variable via
--iprevents the infinite loop issue. - Code Highlight:
int i = 9; while (i >= 0) { printf("I am running current val : %d \n ", i); --i; }
- Concepts: Factorial math, accumulator update logic.
- Summary: Implements a factorial calculation algorithm for a user-entered number using iteration.
- Code Highlight:
while (fact > 0) { Factorial = fact * Factorial; fact = fact - 1; }
This folder (04_Arrays_pointers) covers the declaration, initialization, indexing, and manipulation of single-dimensional (1D) and two-dimensional (2D) arrays in C.
- Declaration and Initialization: An array is a collection of elements of the same datatype stored in contiguous memory locations. An array can be pre-defined with size and initial values inside
{}brackets (e.g.int num[10] = {7,8,9,0,7,3,8,9,1,7};). - Indexing: Elements are accessed via 0-based indices. The maximum valid index of an array of length
lenislen - 1. - Passing Arrays to Functions: Arrays are passed to functions by reference (meaning the address of the first element is passed). Changes made to the array elements inside the function affect the original array.
- Declaration: Declared with row and column dimensions (e.g.,
int arr[3][3];creates a 3x3 grid). - Nested Loops: Iterating through a 2D array requires nested loops: the outer loop controls the rows, and the inner loop controls the columns.
- Concepts: Array declaration, loops for user input, and passing arrays to functions.
- Code Highlight:
void arr_print(int arr[], int len) { for (int i = 0; i < len ; i ++) { printf("%d\n", arr[i]); } }
- Concepts: Declaring a multi-dimensional array and reading elements using nested loops.
- Code Highlight:
int arr [3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("Enter the whole array"); scanf("%d", &arr[i][j]); } }
This folder (05_Searching_techniques) covers standard searching algorithms in C, used to locate target elements within arrays.
-
Logic: Iterates sequentially through each element of the array from index
0ton - 1and compares each element with the target. Returns the index if a match is found, or-1if the loop completes without finding the target. -
Complexity: Time complexity is
$O(N)$ in the worst and average cases. Requires$O(1)$ auxiliary space. Works on both sorted and unsorted arrays.
- Logic: A highly efficient search algorithm that works on already sorted arrays by using a divide-and-conquer strategy. It repeatedly divides the search interval in half by comparing the middle element with the target. If the target is smaller, the search continues in the left half; if larger, it continues in the right half.
-
Complexity: Time complexity is
$O(\log N)$ in the worst and average cases. Requires$O(1)$ auxiliary space for the iterative version.
- Concepts: Sequential traversal of arrays, target boundary checking, returning index or failure codes.
- Code Highlight:
for (int i = 0; i < n; i++) { if (arr[i] == target) { return i; } }
- Concepts: Binary search interval halving (
low,high,mid), handling overflow when calculating indices. - Code Highlight:
while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) return mid; if (arr[mid] < target) low = mid + 1; else high = mid - 1; }
This folder (05_Sorting_techhniques) implements six fundamental comparison-based sorting algorithms in C: Bubble Sort, Insertion Sort, Selection Sort, Merge Sort, Quick Sort, and Heap Sort. It also demonstrates variable swapping techniques.
-
With a Temporary Variable: Stores the value of
aintemp, copiesbtoa, and then copiestemptob. -
Without a Temporary Variable (Arithmetic Method): Uses mathematical addition and subtraction:
$$a = a + b; \quad b = a - b; \quad a = a - b;$$
- Logic: Iteratively steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This pass is repeated until no swaps are needed.
- Optimization: A boolean/flag variable
swappedis set to0at the start of each pass. If a swap occurs,swappedis set to1. If an entire pass completes withswapped == 0, the array is already sorted, and we break early.
- Logic: Divides the array into sorted and unsorted parts. Elements from the unsorted part are picked and placed at the correct position in the sorted part by shifting elements.
- Complexity: Efficient for small datasets or nearly sorted arrays.
- Logic: Divides the array into sorted and unsorted parts. Repeatedly finds the minimum element from the unsorted part and swaps it with the first element of the unsorted part.
- Optimization: Swaps only if the minimum element's index is different from the current position.
- Logic: A divide-and-conquer algorithm. It recursively splits the array in half, recursively sorts each half, and merges the sorted halves back together.
-
Complexity: Guarantees a time complexity of
$O(N \log N)$ in all cases (worst, average, best), but requires$O(N)$ auxiliary memory for merging.
- Logic: A divide-and-conquer algorithm that selects a "pivot" element and partitions the array such that elements smaller than the pivot are moved to its left, and larger elements are moved to its right. It then recursively sorts the sub-arrays.
-
Complexity: Average time complexity of
$O(N \log N)$ , worst-case complexity of$O(N^2)$ (when partitioning is highly unbalanced), but performs in-place sorting without requiring extra memory like Merge Sort.
- Logic: A comparison-based sorting technique based on Binary Heap data structure. It builds a Max Heap from the input data, then repeatedly extracts the maximum element and restores the heap property.
-
Complexity: Guarantees a time complexity of
$O(N \log N)$ in all cases and sorts in-place (requires$O(1)$ auxiliary space).
- Concepts: Swapping two numbers using a third helper variable vs direct arithmetic expressions.
- Code Highlight (Swapping without a third variable):
a = a + b; b = a - b; a = a - b;
-
Concepts: Optimization using a
swappedflag, array bounds, and edge case handling (checking forNULLarray or size$\le 1$ ). -
Code Highlight (Optimization Check):
for (i = 0; i < n - 1; i++) { swapped = 0; for (j = 0; j < n - 1 - i; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = 1; } } if (swapped == 0) // Break early if already sorted break; }
- Concepts: Shifting elements to insert a key element in its sorted location.
- Code Highlight:
for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; while (j >= 0 && key < arr[j]) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; }
- Concepts: Finding the minimum index and performing at most one swap per outer loop iteration.
- Code Highlight:
for (i = 0; i < n - 1; i++) { minIndex = i; for (j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } if (minIndex != i) { temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } }
- Concepts: Divide-and-conquer recursive sorting, memory management (dynamic allocation with
malloc), sub-array boundary merging. - Code Highlight (Merging logic):
void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int *L = (int *)malloc(n1 * sizeof(int)); int *R = (int *)malloc(n2 * sizeof(int)); // ... Copy and merge sub-arrays ... free(L); free(R); }
- Concepts: Divide-and-conquer recursive partitioning, in-place index sorting, helper swapping using pointers.
- Code Highlight (Partitioning function):
int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low - 1); for (int j = low; j < high; j++) { if (arr[j] <= pivot) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); }
- Concepts: Heap tree structures, Max Heap building, recursive heapify algorithm.
- Code Highlight (Heapify structure):
void heapify(int arr[], int n, int i) { int largest = i; int left = 2 * i + 1; int right = 2 * i + 2; if (left < n && arr[left] > arr[largest]) largest = left; if (right < n && arr[right] > arr[largest]) largest = right; if (largest != i) { swap(&arr[i], &arr[largest]); heapify(arr, n, largest); } }
This folder (06_pattern_printing) explores dynamic pattern design in C. Pattern printing helps build logical reasoning by mapping mathematical formulas to nested coordinate loops (rows and columns) to print alignment characters like *.
- Half Pyramid: Outer loop tracks row
i, inner loop printsistars. - Inverted Half Pyramid: Outer loop decrements from
rowsdown to1, printingistars per row. - Full Pyramid: Centers stars by first printing
rows - ileading spaces, then printingistar-space blocks (*).
-
Hollow Full Pyramid: Same alignment as full pyramid, but prints a star
*only if it is the first or last column, or the last row (j == 1 || j == i || i == rows). Otherwise, prints spaces. - Floyd's Triangle: A right-angled triangle filled with sequentially increasing numbers starting from 1.
-
Pascal's Triangle: A centered triangle where each number is the sum of the two directly above it. Calculated using the binomial coefficient formula:
$$\text{val} = \frac{\text{val} \times (i - j)}{j + 1}$$
- Uses conditionals on row/column coordinates to paint specific glyph letters. For example, printing 'H' and 'I' by checking column boundaries (
j == 0 || j == 4) or row bounds (i == 2ori == 0).
- Concepts: Comprehensive pattern printing library containing half, inverted half, full, hollow full pyramids, Floyd's triangle, and Pascal's triangle.
- Code Highlight (Pascal's Triangle Val calculation):
int val = 1; for (int j = 0; j <= i; j++) { printf("%d ", val); val = val * (i - j) / (j + 1); }
- Concepts: Dynamic rows based on user input, rendering a standard dense star pyramid using spaces and stars.
- Code Highlight:
for(i = 1; i <= n; i++) { for(j = 1; j <= n - i; j++) { printf(" "); } for(j = 1; j <= (2 * i - 1); j++) { printf("*"); } printf("\n"); }
- Concepts: Printing coordinates-based letters 'H' and 'I' on a 5x5 grid.
- Code Highlight (Printing H):
for(i = 0; i < 5; i++) { for(j = 0; j < 5; j++) { if(j == 0 || j == 4 || i == 2) printf("*"); else printf(" "); } printf("\n"); }
This folder (07_Structures) covers structure declaration, initialization, pointer reference manipulation, passing structural records to functions, structural arrays, and nested structures in C.
typedef struct: Declares a template structure under a simplified alias type (e.g.Bookinstead ofstruct Book), reducing syntax overhead.- Designated Initializers: Explicitly maps initial values to specific members by name, e.g.
Book b2 = {.title = "Data Structures", .author = "Reema Thareja", .price = 420.00f};.
- Standard dereferencing requires parentheses around the pointer dereference:
(*ptr).member. - The arrow operator (
->) is a cleaner syntactic shortcut:ptr->member.
- Pass by Value: Passes a complete copy of the structure. Changes made to the copy inside the function do not affect the original variable in
main. - Pass by Reference (Pointers): Passes the memory address of the structure. Allows direct modification of original structure members inside functions, and avoids copying overhead (making it highly efficient).
- Array of Structures: Organizes multiple structural instances (e.g.,
Book library[2]) in contiguous memory. - Nested Structures: Nesting structures within structures (e.g., nesting a
struct Addressinsidestruct Employee) to represent complex hierarchical data.
- Concepts: Declaring basic structures, structure pointers, pass-by-value vs pass-by-reference updates, structured arrays, and nested records.
- Code Highlight (Pass by reference and arrow operator usage):
void update_book_price_by_ref(Book *b, float new_price) { b->price = new_price; // Arrow operator updates the price of structural pointer }
This folder (08_File_Handelling) covers file stream input/output operations in C. It details reading, writing, and appending text files, copying file streams byte-by-byte, and serializing complex structure objects into binary files.
- Files are accessed via a
FILE *pointer which manages the stream buffer. - Modes:
"w"(Write text): Opens a file for writing. Overwrites existing contents or creates the file if it doesn't exist."r"(Read text): Opens a file for reading. The file must exist, orfopenreturnsNULL."a"(Append text): Opens a file to append new records to the end without destroying existing data."wb"/"rb"(Binary Write/Read): Opens a file in raw binary stream format (non-plain text).
fprintf(file_ptr, "format", ...): Formatted writing to a file stream.fgets(buffer, sizeof(buffer), file_ptr): Reads a line (up tosizeof(buffer) - 1bytes) from a text file, keeping the trailing newline character, and stops at EOF.
fgetc(src): Reads a single character/byte from the input stream. ReturnsEOFwhen the end of the file is reached.fputc(ch, dest): Writes a single character/byte to the destination file stream.
fwrite(&var, sizeof(type), count, file_ptr): Direct block-based writing of binary data (like arrays or structs) from RAM onto the disk.fread(&var, sizeof(type), count, file_ptr): Direct block-based reading from disk into variable memory.
- Concepts: Full demonstrations of opening, processing, checking for
NULLerrors, closing file pointers usingfclose, copying text files, and binary structures serialization. - Code Highlight (Binary structure write):
struct Student s1 = {101, "Alice Smith", 3.92}; FILE *file_ptr = fopen("student.bin", "wb"); if (file_ptr != NULL) { fwrite(&s1, sizeof(struct Student), 1, file_ptr); fclose(file_ptr); }
This folder (09_DSA) tracks basic to advanced data structures and algorithm design patterns implemented in Jupyter Notebook format. It is a comprehensive algorithmic companion to C development.
- Singly Linked List (
singly_linkedlist.ipynb): Node pointers chaining in one direction, inserting/deleting elements at start/end/middle. - Doubly Linked List (
doublyLL.ipynb): Bidirectional node pointers linking (prev/next) for forward and backward traversal. - Circular Linked List (
circularLL.ipynb): Last node points back to the first node forming a loop. - Stack (
stack.ipynb): Last-In-First-Out (LIFO) abstract data type with push, pop, and peek functions. - Queue (
queue.ipynb): First-In-First-Out (FIFO) structure with enqueue and dequeue operations. - Circular Queue (
circular_queue.ipynb): Queue optimizations utilizing modulo arithmetic to reuse empty slots at the front.
- Tree (
tree.ipynb): Hierarchical node structures, traversal techniques (Preorder, Inorder, Postorder). - Binary Search Tree (
BST.ipynb): Sorted binary trees where left subtree is smaller and right subtree is larger than the parent. - Graph (
graph.ipynb): Node vertices linked by edges, representation matrices, and traversal algorithms (DFS, BFS).
- Quick Sort (
quick_sort.ipynb): Divide-and-conquer algorithm using pivot partitioning. - Selection, Bubble, and Insertion Sort: Notebook-based visual step guides for sorting arrays.
- Recursion (
recursion.ipynb): Solving mathematical sub-problems by calling functions recursively (e.g. Fibonacci, Factorial).
- Concepts: Chaining structure elements together dynamically. Demonstrates head reference tracking and node pointer updates.
- Concepts: Optimizing array storage capacity to prevent queue overflows by wrapping index pointers utilizing
%modulo operations.
This section documents standard loop practice exercises and arithmetic operations present in poblems.txt.
| # | Problem | Description | Input Example | Output Example |
|---|---|---|---|---|
| 1 | Reverse a Number | Reverse a given integer using a while loop. |
12345 |
54321 |
| 2 | Check Palindrome Number | Check whether a number is equal to its reverse using a while loop. |
121 |
Palindrome |
| 3 | Sum of Digits | Find the sum of digits of a given integer. | 456 |
15 |
| 4 | Count Digits | Count the total number of digits in an integer. | 123456 |
6 |
| 5 | Find Largest Digit | Identify the largest digit present in a number. | 58321 |
8 |
| 6 | Decimal to Binary Conversion | Convert a base-10 decimal number to base-2 binary format using a while loop. |
10 |
1010 |
| 7 | Armstrong Number Check | Check whether a 3-digit number is an Armstrong number ( |
153 |
Armstrong Number |
| 8 | GCD of Two Numbers | Calculate the Greatest Common Divisor (GCD) of two numbers using a while loop. |
24 36 |
12 |
| 9 | Print Fibonacci Series | Print the first while loop. |
7 |
0 1 1 2 3 5 8 |
| 10 | Number Guessing Game | A guessing game that requests input until the user guesses a secret number (e.g. 25) correctly. |
104025
|
Too LowToo HighCorrect!
|
The folder Problem_Statements_and_solution/01_practice_problems contains a collection of 28 solved C programs covering a wide range of topics, including arrays, pointers, matrices, recursion, sorting, bitwise operations, and structures.
| # | Program | Description / Core Concepts | Key Highlights / Functions |
|---|---|---|---|
| 1 | ans.c | Character type casting and ASCII lookup. | Prints character integer values. |
| 2 | array_length_pointer.c | Using pointer subtraction to determine array length. | Pointer arithmetic calculation. |
| 3 | bitwise_left_shift.c | Demonstrates the left shift (<<) bitwise operator. |
Bitwise multiplication by powers of 2. |
| 4 | calculator_switch.c | Menu-driven arithmetic calculator. | Utilizes switch-case statements. |
| 5 | circle_area_circumference.c | Calculations using float values and math formulas. | Area ( |
| 6 | concat_strings.c | Appending two string arrays without standard library calls. | Pointer/indexing-based manual string copy. |
| 7 | count_even_odd.c | Counts number of even and odd integers inside an array. | Iteration and % modulo check. |
| 8 | diagonal_matrix.c | Checks properties of diagonal matrices. | Nested loop checks for non-diagonal elements. |
| 9 | equation_solve.c | Algebraic quadratic polynomial evaluation. | Solves |
| 10 | even_odd_check.c | Basic branch verification of even/odd status. | Simple conditional if-else modulo checks. |
| 11 | factorial_iterative.c | Computes |
Prevents infinite loop, handles bounds. |
| 12 | factorial_recursion.c | Computes |
Base case and recursive stack definition. |
| 13 | fibonacci_series.c | Prints Fibonacci sequence terms using variables updating. | Iterative series calculation. |
| 14 | gcd_recursion.c | Evaluates GCD of two numbers recursively. | Euclidean algorithm recursive logic. |
| 15 | max_min_array.c | Scan array to track current minimum and maximum values. | Linear search tracking. |
| 16 | memory.c | Address-of operator lookup demonstration. | Prints RAM variables locations using %p. |
| 17 | palindrome_range.c | Finds palindrome numbers in a user-defined numeric range. | Reverses digits and compares. |
| 18 | practice.c | Basic execution testing environment. | Simple test structure. |
| 19 | prime_check.c | Evaluates prime status by testing divisor limits. | Checks divisors up to |
| 20 | prime_range.c | Finds all prime numbers within a range. | Nested logic checking divisor ranges. |
| 21 | pythagores.c | Solves right triangle sides length. | Uses sqrt and pow standard math routines. |
| 22 | quadratic_roots.c | Solves quadratic equation roots |
Handles real, equal, and complex roots. |
| 23 | sort_array.c | Elements sorting using basic sorting loops. | Ascending numerical ordering logic. |
| 24 | sort_student_names.c | Sorts list of strings (names) alphabetically. | Uses strcmp and nested sorting loops. |
| 25 | student_records_struct.c | Declares student record struct structures and tracks array records. | Querying data, printing report stats. |
| 26 | swap_call_by_value.c | Demonstrates that swapping parameters by value doesn't alter main variables. | Proves scope separation of value parameters. |
| 27 | vowel_consonant.c | Evaluates whether character is a vowel or consonant. | Supports both lowercase and uppercase characters. |