Problem Solving using C Notes
DSC course under University of Kerala (UoK FYUGP Regulations). Credits: 4 | 60 Hours (4 Hrs/Week).
Chapter-Wise Module Notes & PDF Downloads
Short Notes
All Modules IncludedComplete syllabus revision notes covering all modules in one single PDF
Module 1
Introduction to Programming
Module 2
Basic Concepts
Module 3
Functions & Pointers
Module 4
Structures and Files
Module 5
Preprocessor, Headers, CLI Arguments & Advanced Programs
Read Module Notes Online
Module I: Introduction to Programming
Chapter 1: Problem Solving, Algorithms, and Flowcharts
1.1 Computational Problem Solving Lifecycle
Computer programming is not merely the mechanical act of typing syntax into an editor; it is the disciplined engineering process of translating an ambiguous real-world requirement into an unambiguous sequence of machine-executable instructions. Before writing a single line of C code, a programmer systematically decomposes the task using the Input–Process–Output (IPO) model. First, the programmer identifies all valid inputs, their domains, and edge cases. Second, the programmer formulates the deterministic transformation steps required to convert inputs into desired outputs. Third, the programmer verifies correctness across boundary values (such as zero, negative numbers, or empty collections) before implementing and testing the program in C.
During the design stage, two complementary representations bridge human reasoning and source code: algorithms (textual, step-by-step finite specifications written in structured prose or pseudocode) and flowcharts (standardized geometric diagrams depicting control flow and branching). Pseudocode strips away compiler-specific punctuation while retaining control structures such as IF-THEN-ELSE and WHILE, allowing teams to verify logic independently of any programming language.
1.2 Characteristics of an Algorithm and Complexity Intuition
Formalized in computer science by Donald Knuth, an algorithm is a finite, unambiguous, step-by-step procedure for solving a well-defined computational problem. Every valid algorithm must satisfy five non-negotiable properties:
- Finiteness: An algorithm must always terminate after executing a finite number of steps for every valid input. A procedure that enters an endless loop for valid data is not an algorithm.
- Definiteness (Unambiguity): Each step must be precisely specified with exact mathematical or logical operations, leaving zero room for subjective interpretation.
- Input: An algorithm accepts zero or more well-defined inputs supplied externally before or during execution.
- Output: An algorithm must produce at least one observable output quantity having a specified relation to the inputs.
- Effectiveness: Every elementary step must be sufficiently basic that it can, in principle, be carried out accurately in finite time using pencil and paper or basic processor instructions.
When multiple valid algorithms solve the same problem, we evaluate them by time complexity (how execution steps grow with input size) and space complexity (how auxiliary memory grows with input size). Suppose an algorithm checks whether a number is prime by testing divisors up to the value itself versus testing divisors only up to its square root. The step counts scale differently as the input magnitude grows:
1.3 Flowcharts and ANSI/ISO Standard Symbols
A flowchart provides a visual blueprint of program logic using standardized ANSI/ISO geometric shapes joined by directional flowlines. Flowcharts reveal unreachable branches, missing loop exits, and nested decision paths immediately at a glance.
| Symbol Name | Geometric Shape | Semantic Role in Program Design | Typical C Construct Mapped |
|---|---|---|---|
| Terminal | Rounded oval / stadium | Marks entry (START) and exit (STOP / RETURN) points of an algorithm or subprogram. |
int main(void) { ... return 0; } |
| Input / Output | Parallelogram | Represents reading external data from keyboard/files or displaying computed results. | scanf(...), printf(...) |
| Process | Rectangle | Denotes internal computation, variable initialization, arithmetic assignment, or memory updates. | sum = a + b; count++; |
| Decision | Diamond | Tests a Boolean condition with one incoming line and two or more labeled outgoing branches (True/False). |
if (...), while (...), for (...) |
| Flowline | Solid line with arrowhead | Indicates exact chronological direction of control transfer between adjacent symbols. | Sequential execution / loop back-edge |
| On-Page Connector | Small circle with label | Joins distant points within the same page cleanly without crossing flowlines. | Structured block continuation |
| Off-Page Connector | Home-plate pentagon | Links a control path exiting one printed page to an identically labeled entry on another page. | Multi-page module flow |
| Predefined Process | Double-lined rectangle | Invokes an external subroutine or library procedure whose detailed logic is drawn separately. | sqrt(d), user-defined function call |
When constructing flowcharts, draw flow consistently top-to-bottom and left-to-right, ensure every diamond clearly labels all outgoing paths (Yes/No or True/False), avoid intersecting flowlines by employing connector circles, and guarantee that every path reaches a valid terminal STOP. While flowcharts excel for pedagogical clarity and small-to-medium control flows, they become cumbersome to redraw when complex multi-module programs undergo frequent refactoring—making modular C code and concise pseudocode preferable in large-scale systems.
1.4 Worked Algorithmic Walkthroughs
Algorithm 1.1: Roots of a Quadratic Equation. Consider finding the real or complex roots of a quadratic equation where the leading coefficient is non-zero:
- Step 1 (Start & Input): Read real values
a,b, andc. - Step 2 (Validate Domain): If
a == 0, report that the equation is linear rather than quadratic and terminate. - Step 3 (Compute Discriminant): Set
d = b * b - 4 * a * c. - Step 4 (Branch on Discriminant):
- If
d > 0, computer1 = (-b + sqrt(d)) / (2 * a)andr2 = (-b - sqrt(d)) / (2 * a), then print both real roots. - Else if
d == 0, computer1 = -b / (2 * a)and print repeated real root. - Else (
d < 0), computereal = -b / (2 * a)andimag = sqrt(-d) / (2 * a), then printreal + i*imagandreal - i*imag.
- If
- Step 5 (Stop): Terminate algorithm cleanly.
Worked Numerical Trace: Suppose a = 1, b = -5, c = 6. Then d = (-5)*(-5) - 4*1*6 = 25 - 24 = 1 > 0. Branch 1 executes: r1 = (5 + 1)/2 = 3.0 and r2 = (5 - 1)/2 = 2.0. Now suppose a = 1, b = 2, c = 5: then d = 4 - 20 = -16 < 0, triggering Branch 3 with real = -1.0 and imag = 4 / 2 = 2.0, yielding roots -1 + 2i and -1 - 2i.
Algorithm 1.2: Greatest Common Divisor (Euclidean Algorithm). Given two positive integers m and n, repeatedly replace (m, n) with (n, m mod n) until n becomes 0; the remaining m is the GCD. Tracing m = 48, n = 18: iteration 1 sets m = 18, n = 48 % 18 = 12; iteration 2 sets m = 12, n = 18 % 12 = 6; iteration 3 sets m = 6, n = 12 % 6 = 0; loop exits and outputs 6.
Chapter 2: Structure of a C Program and Compilation Architecture
2.1 Anatomy of a Standard C Program
Developed by Dennis Ritchie at Bell Laboratories in 1972 to re-implement the UNIX operating system, C is a general-purpose, procedural, middle-level structured programming language. Every well-organized C source file follows a clear six-part layout:
- Documentation Section: Multi-line (
/* ... */) or single-line (// ...) comments describing program purpose, author, inputs, and outputs. Comments are stripped completely by the compiler preprocessor and generate zero machine instructions. - Link Section: Preprocessor directives such as
#include <stdio.h>that instruct the compiler to embed library declarations (function prototypes, types, and standard constants) prior to compilation. - Definition Section: Symbolic constant and macro definitions using
#define(for example,#define PI 3.14159). - Global Declaration Section: Variables and user-defined function prototypes declared outside all functions so they remain visible across multiple functions in the translation unit.
main()Function Section: Mandatory execution entry point invoked by the C runtime startup stub. Every C executable contains exactly onemain()function partitioned into local variable declarations and executable statements inside braces{ ... }, ending withreturn 0;to notify the operating system of normal completion.- Subprogram Section: Definitions of user-defined helper functions called directly or indirectly from
main().
/* Documentation Section: Computes area and circumference of a circle */
#include <stdio.h> /* Link Section: Standard I/O header */
#define PI 3.14159265 /* Definition Section: Symbolic constant */
double circle_area(double r); /* Global Declaration: Function prototype */
int call_count = 0; /* Global variable initialized to 0 */
int main(void) { /* Entry point of execution */
double radius = 0.0; /* Declaration part */
double area = 0.0;
double circumference = 0.0;
printf("Enter circle radius: ");
if (scanf("%lf", &radius) != 1 || radius < 0.0) {
printf("Invalid non-negative radius required.\n");
return 1; /* Non-zero status indicates input error */
}
area = circle_area(radius); /* Executable statements */
circumference = 2.0 * PI * radius;
printf("Radius = %.2f\n", radius);
printf("Area = %.4f\n", area);
printf("Circumference = %.4f\n", circumference);
printf("Helper calls = %d\n", call_count);
return 0; /* Normal termination status */
}
double circle_area(double r) { /* Subprogram Section */
call_count++;
return PI * r * r;
}2.2 The Header File Concept and Standard Library Interfaces
A header file (extension .h) acts as an interface contract between compiled library implementations and client C source files. The core C language itself contains zero built-in keywords for keyboard input, screen output, string copying, or trigonometry; instead, those capabilities reside in precompiled standard libraries. When you write #include <stdio.h>, the preprocessor literally pastes the contents of stdio.h into your source file before syntax checking begins, supplying the exact parameter types and return types of printf() and scanf() so the compiler verifies type safety at every call site.
- Angle Brackets
#include <header.h>: Directs the preprocessor to search standard system include directories configured by the compiler toolchain. Used for standard C headers (stdio.h,stdlib.h,math.h,string.h,ctype.h,limits.h,float.h,time.h). - Double Quotes
#include "myheader.h": Searches the current directory of the source file first, falling back to system directories only if not found locally. Used for programmer-authored module headers.
2.3 File Extensions Across the C Build Ecosystem
Working effectively with C toolchains such as GCC, Clang, or MSVC requires recognizing the intermediate artifacts created while transforming human-readable source text into native binary machine code.
| Extension | File Category | Readable Format? | Stage Produced & Purpose |
|---|---|---|---|
.c |
C Source Code | Yes (Plain Text) | Authored by the programmer; contains preprocessor directives, declarations, and C function definitions. |
.h |
Header File | Yes (Plain Text) | Stores function prototypes, #define macros, struct/typedef definitions, and extern contracts. |
.i |
Preprocessed Source | Yes (Expanded C) | Produced after preprocessing (gcc -E); comments stripped, headers pasted, and macros expanded. |
.s / .asm |
Assembly Source | Yes (Mnemonics) | Produced by the compiler backend (gcc -S); target-CPU instructions (x86-64 or ARM mnemonics). |
.o / .obj |
Object Code | No (Binary) | Produced by the assembler (gcc -c); relocatable machine code with unresolved external symbol tables. |
.a / .lib |
Static Library Archive | No (Binary) | Bundled collection of object files linked directly into executables during static linking. |
.so / .dll |
Shared / Dynamic Library | No (Binary) | Dynamically loaded at program startup or runtime, saving disk space and memory across multiple processes. |
.exe / a.out |
Executable Binary | No (Binary) | Produced by the linker; complete OS-loadable image (PE format on Windows, ELF on Linux) ready to run. |
2.4 Compilation, Linking, and Execution Pipeline
Converting a .c file into a running process proceeds through four sequential toolchain phases followed by operating system loading:
- Preprocessing: Handles lines starting with
#. Removes comments, expands#includeheaders recursively, substitutes#definemacros, and evaluates conditional compilation guards (#ifdef/#endif). - Compilation: Translates expanded C code through lexical analysis (tokenizing), syntax parsing (building an abstract syntax tree), semantic type checking, intermediate optimization, and code generation into target assembly instructions.
- Assembly: Converts human-readable assembly mnemonics into binary machine opcodes stored inside an object file (
.oor.obj). Internal addresses are still relative rather than final memory locations. - Linking: The linker merges all project object files with referenced standard libraries (such as
libcorlibm), resolves every external symbol reference (linking your call toprintfwith the binary implementation in the C standard library), assigns final virtual address layout, and writes the executable file. - Loading and Execution: When you invoke the executable from a shell or IDE, the OS loader reads the binary header, maps code and data segments into RAM, initializes the runtime stack and heap, passes command-line arguments to the C startup routine (
_start), and transfers control tomain().
Understanding these stages clarifies why errors fall into four distinct categories: Syntax errors (missing semicolons, mismatched braces detected during compilation), Semantic errors (type mismatches or calling undeclared functions detected during compilation), Linker errors (misspelled function names, missing library flags like -lm, or absent main() detected during linking), and Runtime/Logical errors (division by zero, segmentation faults, or incorrect formulas emerging only after the binary executes).
Chapter 3: C Tokens, Identifiers, Variables, and Constants
3.1 C Character Set and Lexical Tokens
The C compiler breaks source text into atomic lexical units called tokens built from the C source character set: uppercase letters (A–Z), lowercase letters (a–z), decimal digits (0–9), special punctuation symbols (+ - * / % = < > & | ^ ~ ! ? : ; , . ( ) [ ] { } # " ' _), and whitespace characters (space, horizontal tab, newline, form feed). C classifies tokens into six categories:
- Keywords: Thirty-two reserved words defined by ANSI C89/C90 (plus five added in C99 such as
inlineandrestrict) having fixed compiler meaning:auto,break,case,char,const,continue,default,do,double,else,enum,extern,float,for,goto,if,int,long,register,return,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile, andwhile. - Identifiers: User-chosen names denoting variables, functions, array tags, structure tags, and typedef aliases.
- Constants: Fixed literal values (numeric, character, enumeration) that cannot be altered during execution.
- String Literals: Sequences of zero or more characters enclosed in double quotes (
"Kerala"), automatically terminated by an invisible null character. - Operators: Symbols instructing the CPU to perform arithmetic, logical, relational, bitwise, or memory operations.
- Punctuators / Separators: Structural delimiters including semicolons
;, commas,, parentheses(), brackets[], and curly braces{}.
3.2 Rules for Naming Variables and Identifiers
An identifier is valid in C if and only if it obeys every lexical rule enforced by the standard:
- Permitted Characters: Only alphabetic letters (
A–Z,a–z), digits (0–9), and the underscore character (_) may appear. Spaces, hyphens, currency symbols, and punctuation are strictly forbidden. - Mandatory First Character: The very first character must be either an alphabetic letter or an underscore (
_). Identifiers cannot begin with a digit. - Case Sensitivity: C strictly distinguishes uppercase and lowercase letters; therefore,
total,Total, andTOTALrepresent three completely distinct identifiers. - No Keyword Collisions: Reserved keywords (written in lowercase) cannot be reused as variable or function names.
- Significant Length and Reserved Underscores: ANSI C89 guarantees at least 31 significant characters for internal identifiers (63 in C99). Although leading underscores are syntactically allowed, identifiers starting with double underscores (
__) or an underscore followed by an uppercase letter (_X) are reserved for the compiler and standard library and should be avoided in application code.
| Candidate Identifier | Validity | Rule Explanation / Diagnostic |
|---|---|---|
student_marks |
Valid | Begins with a lowercase letter; contains only letters and underscore. |
_buffer2 |
Valid | Starts with underscore followed by letters and digit (though leading underscore is best reserved for system headers). |
2ndValue |
Invalid | Violates first-character rule: identifiers must not start with a digit. |
gross-salary |
Invalid | Contains hyphen (-), which the parser reads as subtraction operator between gross and salary. |
total marks |
Invalid | Embedded space separates the name into two adjacent tokens, triggering a syntax error. |
float |
Invalid | Collides with a reserved C keyword. |
Float |
Valid (Poor Style) | Permitted due to case sensitivity, but confusing and strongly discouraged. |
3.3 Variables: Declaration, Definition, and Memory Semantics
A variable is a named storage location in primary memory capable of holding a data value of a declared type that can change during execution. Every variable has three fundamental attributes: its name (identifier), its type (determining bit width and encoding rules), and its address (physical/virtual byte location in RAM). A declaration introduces an identifier and its type to the compiler (as with extern int count;), whereas a definition additionally reserves storage bytes (as with int count;). Every local automatic variable defined without an initializer (e.g., int x; inside a function) contains an uninitialized garbage value leftover from previous stack usage; reading it prior to assignment produces unpredictable runtime results. Always initialize variables at definition (int x = 0;).
Variables also illustrate the distinction between an lvalue (locator value—an expression designating an identifiable memory location that can validly appear on the left side of =, such as score) and an rvalue (the transient data value read from memory or computed by an expression, which can appear only on the right side, such as a + 5).
3.4 Constants in C
Constants represent immutable values known at compile time or protected against modification during execution:
- Integer Constants: Decimal literals use digits
0–9without a leading zero (42,-19). Octal literals begin with a leading0using digits0–7(075equals decimal 61). Hexadecimal literals begin with0xor0Xusing0–9andA–F(0x2Fequals decimal 47). SuffixesU/uandL/lspecify unsigned or long width (100000UL). - Floating-Point Constants: Written either in decimal form containing a decimal point (
3.14159,-0.005) or in scientific/exponential notation (6.022e23,1.6e-19). By default, floating literals have typedouble; appendingf/Fyieldsfloat, andl/Lyieldslong double. - Character Constants and Escape Sequences: A single character enclosed in single quotes (
'A','7','+') stores its numeric ASCII code (for instance,'A'is65,'a'is97,'0'is48) as an integer value. Non-printable or syntactically special characters are represented using backslash escape sequences. - Symbolic Constants (
#definevsconst): Preprocessor macro constants (#define TAX_RATE 0.18) perform pure textual substitution before compilation and occupy zero variable storage, whereas typedconstvariables (const double TAX_RATE = 0.18;) obey C type checking, scope rules, and have an addressable memory location. Enumeration constants declared viaenumassign sequential named integers starting from 0 unless overridden (enum Status { ERR = -1, OK = 0 };).
| Escape Sequence | ASCII Value | Control Action / Character Represented |
|---|---|---|
\n | 10 | Newline — moves cursor to beginning of next output line. |
\t | 9 | Horizontal tab — advances cursor to next tab stop column. |
\r | 13 | Carriage return — returns cursor to start of current line without advancing vertically. |
\0 | 0 | Null character — marks the mandatory end of every C string. |
\b | 8 | Backspace — moves cursor one column backward on supported terminals. |
\a | 7 | Audible alert / terminal bell. |
\\ | 92 | Literal backslash character inside character or string literals. |
\" and \' | 34 / 39 | Literal double quote or single quote character. |
Chapter 4: Basic Data Types, Ranges, and Storage Classes
4.1 Fundamental Data Types and Type Modifiers
C is a statically typed language: every variable and expression possesses a compile-time data type specifying how many bytes it occupies and how bit patterns are decoded. The four primary scalar types plus the empty type void form the foundation:
char: Smallest addressable integer unit (1 byte = 8 bits), designed to hold a single ASCII character or tiny signed/unsigned integer.int: Natural word-sized whole-number type used for counters, indices, flags, and discrete arithmetic.float: Single-precision IEEE 754 binary floating-point number supporting fractional real numbers with roughly 6–7 significant decimal digits.double: Double-precision IEEE 754 binary floating-point number providing roughly 15–16 significant decimal digits and wider exponent range; preferred for scientific calculation.void: Incomplete type denoting absence of a value—used to declare functions returning nothing (void greet(void)), empty parameter lists, and generic untyped pointers (void *).
Four keyword modifiers—signed, unsigned, short, and long—adjust sign interpretation and bit width of integral types (and long double extends precision for floating values).
4.2 Storage Capacity, Binary Range Mathematics, and Comparison
The numeric limits of any integral type follow directly from binary two's complement representation over its allocated bit width:
Worked Range Calculation: For an 8-bit signed char (n = 8), the range spans from to , whereas unsigned char spans from 0 to . For a 32-bit signed int (n = 32), the range spans from to . Exceeding the positive maximum on an unsigned integer wraps around modulo , whereas signed integer overflow produces unpredictable behavior and must be prevented via wider types such as long long or range validation.
| Data Type | Typical Size (Bytes) | Exact Value Range (Standard 32/64-bit Toolchain) | printf / scanf Specifier |
|---|---|---|---|
char / signed char |
1 (8 bits) | -128 to +127 | %c (char) or %hhd |
unsigned char |
1 (8 bits) | 0 to 255 | %c or %hhu |
short int |
2 (16 bits) | -32,768 to +32,767 | %hd |
unsigned short int |
2 (16 bits) | 0 to 65,535 | %hu |
int (signed) |
4 (32 bits) | -2,147,483,648 to +2,147,483,647 | %d or %i |
unsigned int |
4 (32 bits) | 0 to 4,294,967,295 | %u (%o oct, %x hex) |
long long int |
8 (64 bits) | -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 | %lld |
float |
4 (32 bits) | ±3.4 × 10-38 to ±3.4 × 10+38 (~6 decimal digits) | %f, %e, %g |
double |
8 (64 bits) | ±1.7 × 10-308 to ±1.7 × 10+308 (~15 decimal digits) | %lf (in scanf), %f/%lf |
long double |
12 or 16 | Up to ±1.1 × 10+4932 (~19 digits on x87 80-bit) | %Lf |
Note that in legacy 16-bit MS-DOS compilers (such as Turbo C), int occupied 2 bytes (-32,768 to +32,767), whereas modern 32-bit and 64-bit compilers (GCC, Clang, MSVC) allocate 4 bytes for int. Always use the compile-time sizeof(type) operator and constants inside <limits.h> (INT_MIN, INT_MAX) and <float.h> (FLT_DIG, DBL_MAX) rather than hardcoding sizes.
#include <stdio.h>
#include <limits.h>
#include <float.h>
int main(void) {
char grade = 'A';
int students = 120;
unsigned int port = 8080U;
long long population = 1428627663LL;
float cgpa = 8.75f;
double pi_precise = 3.141592653589793;
printf("char grade = %c (ASCII %d), size = %zu byte\n",
grade, grade, sizeof(char));
printf("int students = %d, size = %zu bytes, range = [%d, %d]\n",
students, sizeof(int), INT_MIN, INT_MAX);
printf("uint port = %u, size = %zu bytes, max = %u\n",
port, sizeof(unsigned int), UINT_MAX);
printf("llong population = %lld, size = %zu bytes\n",
population, sizeof(long long));
printf("float cgpa = %.2f, size = %zu bytes, digits = %d\n",
cgpa, sizeof(float), FLT_DIG);
printf("double pi = %.15f, size = %zu bytes, digits = %d\n",
pi_precise, sizeof(double), DBL_DIG);
return 0;
}4.3 Storage Classes in C
Beyond data type, every C variable possesses a storage class specifier defining four behavioral attributes: (1) where the variable is physically stored (RAM stack, CPU register, or static data segment), (2) its default initial value if uninitialized, (3) its lexical scope (regions where its name is visible), and (4) its runtime lifetime (duration across which its memory remains reserved).
auto(Automatic): Default storage class for all local variables declared inside blocks or functions. Allocated on the call stack upon block entry and destroyed immediately upon block exit. Holds an uninitialized garbage value unless explicitly initialized. The keywordautois almost always omitted in practice.register: Advises the compiler to store a frequently accessed local variable (such as a tight loop index) in a high-speed CPU register rather than RAM. Its scope, lifetime, and default garbage value matchauto. Crucially, because CPU registers have no RAM byte address, applying the address-of operator&to aregistervariable triggers a compile-time error in C.static: Exhibits two distinct roles depending on placement. When applied to a local variable inside a function,staticmoves storage from the transient stack to the persistent Data/BSS segment: it is initialized strictly once (defaulting to0) before program logic starts and retains its last modified value across repeated calls to that function, though its visibility stays strictly local to the block. When applied to a global variable or function outside all blocks,staticassigns internal linkage, restricting visibility exclusively to the current.csource file and preventing name clashes across multi-file projects.extern(External): Declares a global variable or function whose physical storage is defined elsewhere (usually earlier in the same file or inside another linked.cfile). It tells the compiler the variable's type without allocating redundant bytes. All global variables have static lifetime and default to0.
| Storage Class | Memory Segment | Default Initial Value | Lexical Scope | Runtime Lifetime |
|---|---|---|---|---|
auto |
Call Stack (RAM) | Uninitialized garbage | Local to enclosing block | Until enclosing block exits |
register |
CPU Register (or Stack) | Uninitialized garbage | Local to enclosing block | Until enclosing block exits |
static (local) |
Data / BSS Segment | 0 (or 0.0 / NULL) |
Local to enclosing block | Entire program execution |
static (global) |
Data / BSS Segment | 0 |
Current .c file only |
Entire program execution |
extern |
Data / BSS Segment | 0 (at defining site) |
Global across linked files | Entire program execution |
#include <stdio.h>
extern int shared_limit; /* Declaration referencing global definition below */
void track_calls(void) {
auto int local_auto = 1; /* Re-initialized to 1 on every call */
static int persist = 0; /* Initialized once to 0; preserved across calls */
local_auto++;
persist += 10;
printf("local_auto = %d | static persist = %d | shared_limit = %d\n",
local_auto, persist, shared_limit);
}
int main(void) {
register int i; /* Hint to hold loop counter in CPU register */
for (i = 0; i < 3; i++) {
track_calls();
}
return 0;
}
int shared_limit = 500; /* Actual global definition */Module II: Basic Concepts
Chapter 5: Operators, Type Conversions, and Expression Evaluation
5.1 Assignment and Arithmetic Operators
An operator is a lexical symbol specifying an operation to be applied to one (unary), two (binary), or three (ternary) operands, while an expression combines operators, variables, and constants to yield a computed value. The foundational state-mutating operator in C is the simple assignment operator (=), which evaluates the rvalue expression on its right-hand side and stores the resulting value into the addressable lvalue variable on its left-hand side. Because = itself is an operator that yields the assigned value and associates right-to-left, chained assignments such as a = b = c = 0; assign 0 to c, then to b, and finally to a. C also offers compound assignment operators (+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=), where x += y + 1 evaluates x = x + (y + 1) while evaluating x strictly once.
C provides five binary arithmetic operators—addition (+), subtraction (-), multiplication (*), division (/), and remainder/modulo (%)—plus unary plus (+) and unary negation (-). Two critical subtleties govern C arithmetic:
- Integer Division Truncation: Whenever both operands of
/have integral types, C discards the fractional remainder toward zero (truncation). Thus7 / 2evaluates to3(not3.5), and-7 / 2evaluates to-3in C99/C11. To retain fractional precision, at least one operand must be floating-point (e.g.,7.0 / 2or(double)a / b). - Modulo Restrictions and Sign Rule: The modulo operator
%computes the integer remainder of division and works exclusively on integer operands; applying%tofloatordoubletriggers a compile-time error (usefmod()from<math.h>for real remainders). In standard C99+, the sign ofa % bmatches the dividenda, preserving the identity(a / b) * b + (a % b) == a. - Increment (
++) and Decrement (--): Unary operators modifying an integer or pointer variable by1. Prefix form (++x) incrementsxfirst and yields the updated value; postfix form (x++) yields the original value ofxand incrementsxafterward. Never read and modify the same scalar variable multiple times within one expression without an intervening sequence point (avoid writing ambiguous expressions such asi = i++ + ++i;).
5.2 Relational, Logical, Bitwise, and Conditional Operators
Decision-making relies on relational operators (< less than, <= less than or equal, > greater than, >= greater than or equal, == equality, != inequality). Every relational expression evaluates strictly to the integer 1 when true or 0 when false. In C, any non-zero numeric or non-null pointer expression is treated as logically true inside conditions, whereas 0 (or NULL) represents false. A classic beginner defect is writing single equals if (x = 5) instead of double equals if (x == 5): the single-equals expression assigns 5 to x, yields 5 (non-zero, hence always true!), and silently corrupts program logic.
Compound truth conditions are constructed using three logical operators: logical AND (&&), logical OR (||), and unary logical NOT (!). Both && and || obey short-circuit evaluation left-to-right: in A && B, if A evaluates to 0 (false), B is never evaluated because the conjunction is guaranteed false; in A || B, if A is non-zero (true), B is skipped because the disjunction is guaranteed true. Programmers exploit short-circuiting for defensive checks such as if (denom != 0 && total / denom > 5), guaranteeing division by zero never executes.
Complementing logical operators, C offers bitwise operators that manipulate individual binary bits of integer operands: bitwise AND (&), bitwise OR (|), bitwise XOR (^), bitwise one's complement (~), left shift (<<, multiplying by powers of 2), and right shift (>>, dividing non-negative values by powers of 2). Additionally, C provides the ternary conditional operator (cond ? expr1 : expr2), which evaluates cond and returns only expr1 if true or expr2 if false; the compile-time sizeof operator returning storage bytes; and the sequential comma operator (,) evaluating operands left-to-right and yielding the rightmost operand's value.
5.3 Implicit Conversions and Explicit Type Casting
When an operator combines operands of differing scalar types (mixed-mode expressions), C performs automatic implicit type conversion following two rules: first, integer promotion widens char and short operands to int; second, usual arithmetic conversions promote the narrower operand up the type hierarchy toward the wider operand: int → unsigned int → long → unsigned long → long long → float → double → long double. Conversely, assigning a wider type into a narrower variable (such as int n = 9.87;) silently truncates the fractional part to 9. To explicitly force conversion—for example, avoiding integer division truncation—apply the unary type cast operator (target_type) expression, as in double avg = (double)sum / count;.
5.4 Operator Precedence, Associativity, and Evaluation Traces
When an unparenthesized expression contains multiple operators, precedence determines which operator binds tighter, while associativity breaks ties among operators sharing identical precedence. Notice how multiplicative operators bind tighter than additive operators, which bind tighter than shifts, relational, equality, bitwise, logical, conditional, assignment, and comma operators.
| Precedence Tier | Category | Operators | Associativity |
|---|---|---|---|
| 1 (Highest) | Postfix | () [] . -> ++ -- (postfix) | Left to Right |
| 2 | Unary | + - ! ~ ++ -- (prefix) (type) * & sizeof | Right to Left |
| 3 | Multiplicative | * / % | Left to Right |
| 4 | Additive | + - | Left to Right |
| 5 | Bitwise Shift | << >> | Left to Right |
| 6 | Relational | < <= > >= | Left to Right |
| 7 | Equality | == != | Left to Right |
| 8–10 | Bitwise Logic | & (Tier 8), ^ (Tier 9), | (Tier 10) | Left to Right |
| 11–12 | Logical Connectives | && (Tier 11), || (Tier 12) | Left to Right |
| 13 | Ternary Conditional | ?: | Right to Left |
| 14 | Assignment | = += -= *= /= %= &= |= ^= <<= >>= | Right to Left |
| 15 (Lowest) | Comma | , | Left to Right |
Worked Expression Trace 2.1: Given int a = 10, b = 3, c = 2, d = 5;, evaluate int res = a + b * c - d / 2 % 2 > 12 && !0;. Step 1 (Unary !): !0 becomes 1. Step 2 (Multiplicative left-to-right): b * c = 6, d / 2 = 2 (integer truncation), 2 % 2 = 0. Step 3 (Additive left-to-right): 10 + 6 - 0 = 16. Step 4 (Relational): 16 > 12 evaluates to 1. Step 5 (Logical AND): 1 && 1 evaluates to 1. Step 6 (Assignment): res receives 1.
Worked Expression Trace 2.2: Given int x = 4, y = 7;, evaluate int z = (++x > 4) && (y++ < 10);. Left side of && executes first: prefix ++x updates x to 5, and 5 > 4 is 1 (true). Because LHS is true, RHS runs: postfix y++ < 10 compares 7 < 10 (1, true) and then updates y to 8. Final values: x = 5, y = 8, z = 1. Had x initially been 2, ++x yields 3, 3 > 4 is 0 (false), short-circuiting prevents y++ from executing, leaving y = 7 and z = 0.
#include <stdio.h>
int main(void) {
int a = 15, b = 4, c = 0;
double exact_div = (double)a / b;
printf("Arithmetic: a+b=%d, a-b=%d, a*b=%d, a/b=%d, a%%b=%d\n",
a + b, a - b, a * b, a / b, a % b);
printf("Explicit cast (double)a/b = %.2f\n", exact_div);
/* Short-circuit prevents divide-by-zero when c == 0 */
if (c != 0 && (a / c) > 2) {
printf("Quotient exceeds 2.\n");
} else {
printf("Short-circuit guarded against division by zero (c = %d).\n", c);
}
int max_val = (a > b) ? a : b;
printf("Ternary max(%d, %d) = %d | Bitwise (a & b) = %d\n",
a, b, max_val, a & b);
return 0;
}Chapter 6: Control Structures — Decision Making and Looping
6.1 Branching Statements: if, if-else, Ladder, and Nested if
By default, C executes statements sequentially top-to-bottom. Decision-making statements alter execution dynamically based on runtime truth conditions:
- Simple
if: Executes a statement or compound{ ... }block only when the parenthesized condition evaluates non-zero. - Two-Way
if-else: Selects between two mutually exclusive branches—true branch when condition is non-zero, false branch when condition equals0. if-else ifLadder: Chains multiple mutually exclusive conditions top-to-bottom. The very first true branch executes and skips the remainder of the ladder; an optional trailingelsehandles default fallback cases.- Nested
ifand the DanglingelseRule: Placing oneif-elseinside another handles hierarchical conditions (such as leap year divisibility by 4, 100, and 400). Without braces, C always pairs anelsewith the nearest preceding unmatchedif. Always enclose multi-line bodies in explicit braces{ }to prevent dangling-elsebugs.
6.2 Multi-Way Selection with switch-case
The switch statement dispatches control directly to matching constant integral labels (int, char, or enum—never float, double, or string literals). Once control jumps to a matching case label, execution continues sequentially downward through subsequent cases (fall-through behavior) until encountering a break; statement or the closing brace of the switch. Intentional fall-through enables grouping multiple labels (such as case 'a': case 'e': case 'i': case 'o': case 'u':), while forgetting break; inadvertently executes unintended cases. The optional default: label runs if no case constant matches.
| Criterion | if-else if Ladder |
switch-case Statement |
|---|---|---|
| Test Expression Types | Any scalar or floating expression, ranges (x >= 50 && x < 80), strings via strcmp(). |
Strictly integral or char constant expressions (case 1:, case 'A':). |
| Evaluation Mode | Sequential top-down evaluation of arbitrary Boolean predicates. | Discrete equality matching against compile-time constants (often compiled to fast jump tables). |
| Execution Flow | Automatic exit after the first matching branch completes. | Falls through across labels unless terminated explicitly with break;. |
#include <stdio.h>
int main(void) {
char op;
double x, y;
int year;
printf("Enter expression (e.g. 12.5 * 4): ");
if (scanf("%lf %c %lf", &x, &op, &y) == 3) {
switch (op) {
case '+': printf("Result = %.2f\n", x + y); break;
case '-': printf("Result = %.2f\n", x - y); break;
case '*': printf("Result = %.2f\n", x * y); break;
case '/':
if (y != 0.0) {
printf("Result = %.2f\n", x / y);
} else {
printf("Error: Division by zero.\n");
}
break;
default:
printf("Unsupported operator '%c'.\n", op);
}
}
printf("Enter year to check leap year: ");
if (scanf("%d", &year) == 1) {
if (year % 4 == 0) {
if (year % 100 != 0 || year % 400 == 0) {
printf("%d is a Leap Year.\n", year);
} else {
printf("%d is NOT a Leap Year.\n", year);
}
} else {
printf("%d is NOT a Leap Year.\n", year);
}
}
return 0;
}6.3 Looping Statements and Jump Controls
Repetition structures execute a block repeatedly while a continuation predicate holds true. C distinguishes entry-controlled loops (condition tested before entering body: for and while, meaning zero iterations occur if initially false) from exit-controlled loops (condition tested after body runs: do-while, guaranteeing at least one execution regardless of initial condition):
while (cond) { body }: Ideal for sentinel-controlled or event-driven loops where the number of repetitions is unknown upfront (such as extracting digits viawhile (n > 0)or reading untilEOF).for (init; cond; update) { body }: Ideal for counter-controlled traversal across known bounds. Step 1 executesinitonce; Step 2 evaluatescond; if true, executesbody, then executesupdate, and repeats from Step 2. Any clause may be omitted (leaving semicolons intact);for (;;)expresses an infinite loop exited viabreak.do { body } while (cond);: Note the mandatory trailing semicolon afterwhile (cond);. Particularly suited for interactive menu validation loops that must display choices at least once before verifying user input.breakandcontinue: Inside any loop,break;immediately terminates the innermost enclosing loop and transfers control to the statement following it. Conversely,continue;skips only the remainder of the current iteration's body and jumps directly to the next loop condition check (or theupdateexpression inside aforloop). The unconditional jumpgoto label;transfers control directly within a function; although useful for breaking out of deeply nested error paths, disciplined structured programming avoids arbitrarygototo prevent spaghetti control flow.
| Loop Construct | Evaluation Point | Minimum Executions | Primary Use Case |
|---|---|---|---|
for | Entry-controlled (Top) | 0 | Fixed iteration ranges, array indexing, nested matrix traversals. |
while | Entry-controlled (Top) | 0 | Unknown iteration counts, digit extraction, input streams until sentinel. |
do-while | Exit-controlled (Bottom) | 1 | Menu-driven interfaces and post-execution input validation. |
#include <stdio.h>
int main(void) {
int n, original, digit, sum = 0;
printf("Enter a 3-digit positive integer: ");
if (scanf("%d", &n) != 1 || n < 0) {
return 1;
}
original = n;
while (n > 0) {
digit = n % 10;
sum += digit * digit * digit;
n /= 10;
}
printf("%d is %sArmstrong number.\n",
original, (sum == original) ? "an " : "NOT an ");
printf("Odd primes between 2 and 30:\n");
for (int num = 2; num <= 30; num++) {
if (num > 2 && num % 2 == 0) {
continue; /* Skip even composites immediately */
}
int is_prime = 1;
for (int d = 3; d * d <= num; d += 2) {
if (num % d == 0) {
is_prime = 0;
break; /* Exit inner divisor test early */
}
}
if (is_prime) {
printf("%d ", num);
}
}
printf("\n");
return 0;
}Chapter 7: Simple I/O Statements — Formatted and Unformatted I/O
7.1 Standard I/O Streams and Format Control
C models console interaction through buffered standard character streams opened automatically before main() begins: stdin (standard input, normally keyboard), stdout (standard output, normally console terminal), and stderr (unbuffered error output). Standard input/output calls fall into two groups defined in <stdio.h>: formatted I/O (converting internal binary representations to/from human-readable text using format specifiers) and unformatted I/O (transferring raw characters or entire text lines directly without format conversion).
7.2 Formatted Output (printf) and Formatted Input (scanf)
The prototype int printf(const char *format, ...); writes formatted text to stdout and returns the number of characters printed. Format placeholders follow the pattern %[flags][width][.precision]specifier: for example, %-10s left-aligns a string in a 10-column field, %05d zero-pads an integer to width 5, and %8.2f prints a floating-point number right-aligned in 8 columns with 2 decimal places.
The counterpart int scanf(const char *format, ...); parses whitespace-delimited tokens from stdin and stores converted values at the memory addresses passed via & (except array names such as strings, which naturally decay to addresses). Always inspect the integer return value of scanf()—it equals the count of variables successfully parsed, or EOF on stream termination. A common student pitfall occurs when mixing numeric scanf("%d", &n) with character scanf("%c", &ch): %d leaves the trailing Enter newline '\n' sitting in the input buffer, and %c immediately consumes that leftover newline! Prefixing a leading space inside the format string—scanf(" %c", &ch)—instructs scanf() to discard any pending whitespace before reading the character.
| Function | Category | Stream Target | Operational Behavior & Safety Notes |
|---|---|---|---|
printf() |
Formatted Output | stdout |
Interprets %d, %f, %c, %s, width/precision; returns char count printed. |
scanf() |
Formatted Input | stdin |
Requires variable addresses (&x); stops %s at whitespace; validate return count. |
getchar() / putchar() |
Unformatted Char I/O | stdin / stdout |
Reads/writes one character as an int (to hold EOF cleanly); line-buffered by OS. |
fgets(buf, sz, stdin) |
Unformatted String I/O | Any FILE* |
Safe bounded line reader; preserves spaces and retains trailing '\n' if room permits. |
puts(str) |
Unformatted String Output | stdout |
Prints null-terminated string followed automatically by a newline '\n'. |
gets(str) (Removed) |
Deprecated Unformatted | stdin |
Never checks buffer capacity; vulnerable to stack buffer overflows; removed in C11. |
7.3 Unformatted I/O and Buffer Hygiene
Unformatted functions execute faster and avoid format-string parsing overhead. Because getchar() returns an int rather than a char so it can distinguish valid byte values 0..255 from the negative sentinel EOF (usually -1), always store its result in an int ch; variable. For reading full lines containing spaces safely, use fgets(line, sizeof(line), stdin) and strip the trailing '\n' using strcspn(line, "\n") rather than ever calling removed gets() or non-standard DOS functions like getch()/getche() from <conio.h>.
Chapter 8: Single and Multi-Dimensional Arrays
8.1 One-Dimensional Arrays and Memory Address Calculus
An array is a fixed-size, homogeneous collection of elements stored in contiguous memory locations and accessed through a single base identifier plus zero-based integer subscripts. Declaring int marks[5]; reserves five consecutive int slots (20 contiguous bytes on 4-byte int platforms), indexed from marks[0] up to marks[4]. Accessing marks[5] or marks[-1] triggers out-of-bounds memory corruption because C prioritizes execution speed over runtime bounds checking.
[0] or [0][0]; i = 0-based row or element index; j = 0-based column index; C = total declared columns per row in row-major C order; w = sizeof(element_type) in bytes.Worked Address Calculation: Suppose double vec[10] begins at base address B = 2000 with w = 8 bytes. Element vec[6] resides at 2000 + 6 × 8 = 2048. Similarly, for a 2D array int grid[3][4] starting at B = 4000 with w = 4 bytes and C = 4 columns, element grid[2][1] sits at 4000 + (2 × 4 + 1) × 4 = 4000 + 36 = 4036.
One-dimensional arrays support compile-time full initialization (int a[4] = {10, 20, 30, 40};), partial initialization where remaining slots zero-fill automatically (int a[10] = {0};), unsized initialization where the compiler counts initializers (int a[] = {2, 4, 6};), or runtime loop population via scanf().
8.2 Core 1D Array Algorithms: Searching and Sorting
Mastery of 1D arrays centers on traversal, reduction (sum, mean, minimum, maximum), Linear Search (scanning sequentially in O(n) steps on unsorted arrays), Binary Search (halving the search interval in O(log2 n) steps on already-sorted arrays via mid = low + (high - low) / 2), Bubble Sort (adjacent swap passes bubbling largest elements rightward in O(n2)), and shifting elements right/left for array insertion and deletion.
#include <stdio.h>
int main(void) {
int arr[50], n, key;
printf("Enter element count (1..50): ");
if (scanf("%d", &n) != 1 || n < 1 || n > 50) return 1;
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
/* Bubble Sort (Ascending) with early-exit optimization */
for (int pass = 0; pass < n - 1; pass++) {
int swapped = 0;
for (int j = 0; j < n - 1 - pass; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
swapped = 1;
}
}
if (!swapped) break;
}
printf("Sorted array: ");
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\nEnter search key: ");
scanf("%d", &key);
/* Binary Search */
int low = 0, high = n - 1, found_idx = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == key) { found_idx = mid; break; }
else if (arr[mid] < key) low = mid + 1;
else high = mid - 1;
}
if (found_idx != -1) printf("%d found at sorted index %d.\n", key, found_idx);
else printf("%d not present in array.\n", key);
return 0;
}8.3 Multi-Dimensional Arrays and Matrix Algebra
A two-dimensional array int mat[R][C]; models a rectangular table of R rows and C columns stored sequentially in memory row by row (row-major order). Higher dimensions such as 3D arrays (int cube[2][3][4];) generalize naturally as arrays of 2D planes. When initializing a 2D array with braced rows, only the first dimension may be omitted (int m[][3] = {{1,2,3}, {4,5,6}};); column size must always be specified so the compiler knows the row stride.
Matrix multiplication of matrix A (dimension r1 × c1) by matrix B (dimension r2 × c2) is mathematically valid strictly when c1 = r2, yielding product matrix C of dimension r1 × c2 governed by the inner-product summation:
#include <stdio.h>
#define MAX 10
int main(void) {
int A[MAX][MAX], B[MAX][MAX], C[MAX][MAX];
int r1, c1, r2, c2;
printf("Enter rows & cols of A, then B: ");
if (scanf("%d %d %d %d", &r1, &c1, &r2, &c2) != 4) return 1;
if (c1 != r2 || r1 > MAX || c2 > MAX) {
printf("Incompatible dimensions for matrix multiplication.\n");
return 1;
}
printf("Enter elements of Matrix A (%dx%d):\n", r1, c1);
for (int i = 0; i < r1; i++)
for (int j = 0; j < c1; j++) scanf("%d", &A[i][j]);
printf("Enter elements of Matrix B (%dx%d):\n", r2, c2);
for (int i = 0; i < r2; i++)
for (int j = 0; j < c2; j++) scanf("%d", &B[i][j]);
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
C[i][j] = 0;
for (int k = 0; k < c1; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
printf("Product Matrix C (%dx%d):\n", r1, c2);
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) printf("%5d", C[i][j]);
printf("\n");
}
return 0;
}Chapter 9: String Management and Character Processing
9.1 Representation, Declaration, and Safe Input of Strings
Unlike high-level languages with dedicated string object types, C represents a string simply as a one-dimensional char array terminated by the ASCII null byte '\0' (numeric code 0). Every string function determines where a string ends solely by scanning sequentially until reaching '\0'. Consequently, storing an N-character word requires an array of length at least N + 1 bytes. Notice the stark structural contrast between a character constant 'A' (1 byte storing integer 65) and string literal "A" (2 bytes containing 'A' followed by '\0').
- Initialization Forms:
char lang[10] = "C99";automatically appends'\0'and zero-pads unused slots;char name[] = {'C', 'S', '\0'};explicitly specifies the terminator (omitting'\0'yields a plain char array rather than a valid C string!). - Safe Input Methods: Using bounded
scanf("%19s", word)reads a single whitespace-free token into a 20-byte buffer. To read multi-word lines safely without buffer overflow, callfgets(line, sizeof(line), stdin)and strip any trailing newline'\n'before processing.
9.2 Standard String Library Functions (<string.h> and <ctype.h>)
Standard headers <string.h> and <ctype.h> eliminate manual boilerplate for length computation, copying, concatenation, lexicographical comparison, and character classification.
| Library Function | Header | Semantic Behavior & Return Value |
|---|---|---|
strlen(s) | <string.h> | Returns character count (size_t) before '\0', excluding the null terminator itself. |
strcpy(dst, src) / strncpy() | <string.h> | Copies characters including '\0' into dst; bounded strncpy(dst, src, n) guards buffer size (ensure null termination manually). |
strcat(dst, src) / strncat() | <string.h> | Appends src starting at dst's original '\0'; requires sufficient trailing capacity in dst. |
strcmp(s1, s2) / strncmp() | <string.h> | Lexicographical unsigned-byte compare: returns 0 if equal, < 0 if s1 < s2, > 0 if s1 > s2. |
strchr(s, ch) / strstr(s, sub) | <string.h> | Returns pointer to first occurrence of character ch or substring sub, or NULL if absent. |
isalpha, isdigit, tolower, toupper | <ctype.h> | Tests character classes and performs ASCII case conversion cleanly (pass (unsigned char)c). |
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char word[100];
printf("Enter a string: ");
if (!fgets(word, sizeof(word), stdin)) return 1;
word[strcspn(word, "\n")] = '\0'; /* Strip trailing newline cleanly */
size_t len = strlen(word);
int is_pal = 1, vowels = 0;
for (size_t i = 0; i < len; i++) {
char ch = (char)tolower((unsigned char)word[i]);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
}
if (i < len / 2 && tolower((unsigned char)word[i]) !=
tolower((unsigned char)word[len - 1 - i])) {
is_pal = 0;
}
}
printf("Length = %zu | Vowels = %d | Palindrome = %s\n",
len, vowels, is_pal ? "Yes" : "No");
/* Lexicographical sorting of 4 names using strcmp and strcpy */
char names[4][20] = {"Zara", "Anand", "Meera", "Babu"};
char temp[20];
for (int i = 0; i < 3; i++) {
for (int j = i + 1; j < 4; j++) {
if (strcmp(names[i], names[j]) > 0) {
strcpy(temp, names[i]);
strcpy(names[i], names[j]);
strcpy(names[j], temp);
}
}
}
printf("Sorted names: ");
for (int i = 0; i < 4; i++) printf("%s ", names[i]);
printf("\n");
return 0;
}Module III: Functions & Pointers
Chapter 10: Modular Programming with Functions and Recursion
10.1 Modular Decomposition, Library Functions, and User-Defined Functions
Large software systems become unmanageable if written as a single monolithic main() function spanning hundreds of lines. Modular programming decomposes a complex task into compact, single-responsibility subprograms called functions using top-down refinement. This architecture delivers four enduring engineering benefits: (1) Abstraction—callers invoke a function via its interface without worrying about internal steps; (2) Reusability—tested logic such as matrix multiplication or prime verification is called repeatedly from multiple places without duplicating source code; (3) Maintainability and Debugging—defects are isolated cleanly inside small functional boundaries; and (4) Team Parallelism—distinct programmers implement separate module functions concurrently.
C categorizes functions into two broad classes. Library (Built-in) Functions ship precompiled inside the C standard library and are unlocked by including corresponding headers: <stdio.h> (printf, scanf), <math.h> (sqrt, pow, fabs, sin, ceil, floor), <stdlib.h> (abs, rand, srand, exit, atoi), <string.h> (strlen, strcmp), and <ctype.h> (isalpha, isdigit, toupper). User-Defined Functions are written directly by the programmer whenever application-specific logic is required.
10.2 Function Declaration, Definition, Invocation, and Categories
Every user-defined function involves three distinct syntactic elements:
- Function Declaration (Prototype): Placed before the first call (typically above
main()or inside a.hfile), informing the compiler of the function's return type, identifier name, and ordered parameter types:double power_val(double base, int exp);. Notice the mandatory trailing semicolon; parameter names inside prototypes are optional documentation. - Function Definition: Contains the actual implementation header (no trailing semicolon) and body enclosed in braces
{ ... }. Variables listed in the definition header are formal parameters receiving copies of caller expressions. - Function Call (Invocation): Transfers execution to the called function (callee), binding comma-separated actual arguments from the caller to the callee's formal parameters positionally. The
return expr;statement exits the callee immediately and delivers the computed value back to the call site (functions declared with return typevoidreturn no value).
| Function Category | Prototype Pattern | Data Transfer Direction | Typical Practical Role |
|---|---|---|---|
| No Arguments, No Return Value | void print_banner(void); |
Self-contained; caller passes nothing, receives nothing. | Displaying static menu banners, dividers, or copyright headers. |
| Arguments, No Return Value | void print_table(int n); |
One-way flow from caller into callee via parameters. | Printing formatted reports, arrays, or multiplication tables. |
| No Arguments, Return Value | int read_positive(void); |
One-way flow from callee back to caller via return. |
Validating user menu selection or generating random dice rolls. |
| Arguments and Return Value | long factorial(int n); |
Bidirectional flow: receives inputs and computes output value. | Pure mathematical computations, searches, and algorithmic helpers. |
10.3 Scope, Lifetime, and Call Stack Frames
Every identifier declared in C obeys strict visibility boundaries called scope and memory persistence intervals called lifetime. A variable declared inside a function body or compound block { ... } possesses block (local) scope: it is invisible outside that block, allowing independent functions to reuse variable names like i or sum without collision. When a function is called, the CPU pushes a dedicated memory record called a stack frame (activation record) onto the runtime call stack containing the return instruction address, local automatic variables, and formal parameters. Once return executes, that frame pops off the stack and its local memory is immediately reclaimed.
Conversely, variables declared outside all functions possess file (global) scope: they reside in the static data segment, default to 0, persist across the entire execution lifecycle, and are accessible by every function appearing after their declaration. While global variables simplify sharing read-only configuration tables, mutating globals indiscriminately couples unrelated functions and creates hard-to-trace side effects; passing explicit parameters is far cleaner software design. If a local variable shadows a global variable of the exact same name, the inner local definition wins inside that block.
10.4 Passing Arrays to Functions
When an array name is passed as an argument to a function, C does not copy every element onto the stack; instead, the array name automatically converts (decays) into a pointer to its very first element (&arr[0]). Consequently: (1) passing an array takes constant O(1) time regardless of whether it holds 10 or 100,000 items; (2) the callee loses knowledge of the array's total length, so programmers must explicitly pass the element count as a second int n argument; and (3) modifications made to arr[i] inside the callee directly modify the caller's original array! Prefixing the parameter with const (void print_arr(const int a[], int n)) protects read-only functions against accidental writes. For 2D arrays, the column dimension is mandatory in the formal parameter (void show_mat(int m[][10], int r, int c)) so the compiler knows each row's byte stride.
10.5 Recursion: Mechanics, Stack Unwinding, and Comparison with Iteration
Recursion is a problem-solving technique in which a function invokes itself directly (direct recursion) or through another helper function (indirect recursion) on progressively smaller subproblems. Every valid recursive definition relies on two essential clauses: a non-recursive base case that returns an answer immediately to halt calls, and a recursive step that simplifies the input strictly toward the base case.
Worked Stack Unwinding Trace for fact(4): Calling fact(4) pushes frame n=4 (waiting on 4 * fact(3)), which pushes n=3 (waiting on 3 * fact(2)), pushing n=2, pushing n=1, pushing base case n=0. Frame n=0 immediately returns 1; unwinding multiplies backward: 1*1=1, 2*1=2, 3*2=6, 4*6=24. If the base case is omitted or unreachable, calls accumulate endlessly until exhausting the stack segment (Stack Overflow). Another classic recursive problem, the Tower of Hanoi for n disks, requires exactly disk transfers by recursively moving n - 1 disks to an auxiliary peg, shifting disk n to the destination peg, and moving the n - 1 disks onto it.
| Design Dimension | Recursion | Iteration (for / while) |
|---|---|---|
| Termination Mechanism | Executes base-case conditional check to stop self-calls. | Terminates when loop continuation predicate evaluates false. |
| Memory Footprint | Allocates a fresh stack frame per nested call (O(depth) RAM). | Reuses single stack frame with constant auxiliary variables (O(1)). |
| Execution Speed | Slower due to repeated call-stack setup, parameter passing, and returns. | Faster because loop jumps execute purely inside registers without call overhead. |
| Failure Mode | Missing base case triggers fatal Stack Overflow crash. | Unchanging condition triggers non-terminating infinite loop. |
| Best Suitability | Tree/graph traversals, divide-and-conquer, Tower of Hanoi, quicksort. | Linear array scans, cumulative sums, tabular math, factorial/Fibonacci. |
#include <stdio.h>
long long fact_rec(int n) {
if (n <= 1) return 1LL; /* Base case */
return (long long)n * fact_rec(n - 1);
}
int gcd_rec(int a, int b) {
if (b == 0) return a; /* Base case */
return gcd_rec(b, a % b); /* Tail-recursive Euclidean step */
}
int fib_rec(int n) {
if (n <= 1) return n;
return fib_rec(n - 1) + fib_rec(n - 2);
}
int main(void) {
int num = 6, x = 84, y = 36, terms = 8;
printf("%d! = %lld\n", num, fact_rec(num));
printf("GCD(%d, %d) = %d\n", x, y, gcd_rec(x, y));
printf("First %d Fibonacci terms: ", terms);
for (int i = 0; i < terms; i++) {
printf("%d ", fib_rec(i));
}
printf("\n");
return 0;
}Worked Trace — Tower of Hanoi (n = 3 disks, Source A → Destination C using Auxiliary B): Invoking hanoi(3, 'A', 'B', 'C') expands recursively into seven exact physical moves satisfying : Move disk 1 from A to C; Move disk 2 from A to B; Move disk 1 from C to B; Move disk 3 from A to C; Move disk 1 from B to A; Move disk 2 from B to C; Move disk 1 from A to C. Notice how the largest disk shifts exactly once while smaller sub-towers migrate symmetrically. Tail recursion (as in gcd_rec above, where the recursive call is the very last operation before returning without pending multiplication) permits modern optimizing compilers to reuse the existing stack frame in O(1) space.
#include <stdio.h>
void hanoi(int n, char src, char aux, char dst) {
if (n == 1) {
printf("Move disk 1 from %c -> %c\n", src, dst);
return;
}
hanoi(n - 1, src, dst, aux);
printf("Move disk %d from %c -> %c\n", n, src, dst);
hanoi(n - 1, aux, src, dst);
}
int bsearch_rec(const int arr[], int low, int high, int key) {
if (low > high) return -1;
int mid = low + (high - low) / 2;
if (arr[mid] == key) return mid;
if (arr[mid] > key) return bsearch_rec(arr, low, mid - 1, key);
return bsearch_rec(arr, mid + 1, high, key);
}
int main(void) {
int sorted[] = {11, 23, 35, 47, 59, 72};
printf("Index of 47 = %d\n", bsearch_rec(sorted, 0, 5, 47));
printf("Tower of Hanoi moves for 3 disks:\n");
hanoi(3, 'A', 'B', 'C');
return 0;
}10.6 Standard Library Functions Reference (<math.h> and <stdlib.h>)
Before authoring custom algorithms, always inspect standard headers to avoid reinventing optimized numerical primitives. Note that on POSIX/GCC toolchains, compiling programs calling <math.h> functions requires linking the math library explicitly via -lm. Furthermore, trigonometric routines operate strictly in radians rather than degrees ().
| Library Function | Header | Operation & Return Value Domain |
|---|---|---|
sqrt(x) / pow(b, e) | <math.h> | Returns non-negative square root √x and exponentiation be as double. |
ceil(x) / floor(x) | <math.h> | Rounds upward to smallest integer ≥ x or downward to largest integer ≤ x. |
fabs(x) / abs(n) | <math.h> / <stdlib.h> | Computes absolute magnitude for floating-point double vs integer int. |
log(x) / log10(x) | <math.h> | Evaluates natural logarithm (base e) and common logarithm (base 10) for x > 0. |
rand() / srand(seed) | <stdlib.h> | Generates pseudo-random integer in [0, RAND_MAX] seeded by srand((unsigned)time(NULL)). |
exit(status) | <stdlib.h> | Flushes open output streams cleanly and terminates process immediately with OS exit code. |
Chapter 11: Pointers, Pointer Arithmetic, and Parameter Passing
11.1 Physical Memory Addressing, &, and * Operators
Computer RAM operates as a vast contiguous sequence of individually numbered 1-byte cells, each labeled by a unique hexadecimal numeric memory address. When you define int age = 21;, the compiler allocates 4 consecutive bytes (say addresses 0x1000 through 0x1003) and records that age refers to base address 0x1000. A pointer is simply a derived variable designed specifically to store the memory address of another variable or function rather than direct numeric/character data.
Two complementary unary operators bridge ordinary variables and pointers:
- Address-of Operator (
&): Applied to any addressable lvalue variable (not constants, expressions like&(a+b), orregistervariables),&varyields the starting RAM address ofvar. - Indirection / Dereference Operator (
*): Applied to a valid non-null pointer variableptr, the expression*ptrfollows the stored address to access or modify the target value residing there. In declarations (int *ptr;), the asterisk specifies thatptrhas type "pointer toint"; inside executable statements (*ptr = 99;),*performs dereferencing.
11.2 Pointer Declaration, Initialization, NULL, Wild, and Dangling Pointers
Syntax pitfalls abound when declaring multiple pointers on one line: in int *p, q;, the asterisk binds strictly to p, making p a pointer to int while q is a plain int! Always write int *p = NULL, *q = NULL; or place each pointer declaration on its own line. Notice an essential invariant of modern architectures: every pointer variable occupies identical size (typically 4 bytes on 32-bit systems and 8 bytes on 64-bit systems) whether it points to a 1-byte char, a 4-byte int, or an 8-byte double—because every RAM address has identical bit width. The pointer's declared base type tells the compiler how many bytes to read/write when dereferencing (*p) and what stride to multiply during pointer arithmetic!
NULLPointer: A pointer explicitly initialized to the standard constant macroNULL(address zero) defined in<stddef.h>/<stdio.h>, signifying it intentionally points nowhere. Always verifyif (p != NULL)before dereferencing; dereferencingNULLsafely crashes with a segmentation fault rather than silently corrupting adjacent data.- Wild (Uninitialized) Pointer: A local pointer declared without initialization (
int *p;) holds an arbitrary garbage address. Writing via*p = 5;causes severe memory corruption or crashes. Always initialize pointers immediately to&variableorNULL. - Dangling Pointer: A pointer still holding an address whose target storage was already deallocated (either because a local stack variable went out of scope upon function return, or because heap memory was released via
free()). Resetting pointers toNULLimmediately after release eliminates dangling-pointer misuse.
11.3 Pointer Assignment and Pointer Arithmetic
Two pointers sharing identical base types may be assigned directly (p2 = p1;), making both aliases refer to the same target memory location. Unlike ordinary integer addition, pointer arithmetic scales automatically by the byte width of the pointed-to base type:
char, 4 for int, 8 for double). Pointer subtraction yields the number of elements (not raw bytes) separating two pointers inside the same array.Worked Trace: Suppose int nums[5] = {10, 20, 30, 40, 50}; resides at base address 1000 with sizeof(int) = 4. Setting int *p = nums; gives p = 1000 and *p = 10. Executing p += 2; advances p by 2 × 4 = 8 bytes to address 1008, so *p now accesses 30. Subtracting &nums[4] - &nums[1] computes (1016 - 1004) / 4 = 3 elements. Beware precedence when combining increment and dereference: *p++ dereferences *p first and then increments pointer p (because postfix ++ shares tier precedence right-to-left with unary *, evaluating the pointer increment on p while yielding the old address to *), whereas (*p)++ increments the target integer stored at *p.
| Pointer Operation | Permitted in C? | Semantic Behavior & Restriction |
|---|---|---|
p + n, p - n, p++, p-- | Valid | Advances/retreats pointer by n * sizeof(*p) bytes within array bounds (+1 past end). |
p2 - p1 | Valid | Returns ptrdiff_t count of elements between pointers inside the same array. |
p1 == p2, p1 < p2 | Valid | Compares equality of any pointers or relative order within the same array. |
p1 + p2, p * 2, p / 2, p % 2 | Invalid (Syntax Error) | Adding, multiplying, or dividing absolute memory addresses is meaningless and forbidden. |
11.4 Pointers, Arrays, Strings, Generic Pointers, and Function Pointers
Arrays and pointers interact intimately in C: an array name a evaluates in almost all expressions (except sizeof(a) and &a) to a non-modifiable pointer constant equal to &a[0]. Therefore, the compiler literally translates array subscripting a[i] into pointer arithmetic *(a + i)! While a itself cannot be reassigned (a++ is illegal), a separate pointer variable int *p = a; can walk across elements with p++. Distinguish two easily confused declarations by reading operator precedence ([] binds tighter than *):
- Array of Pointers (
int *arr[5];): An array containing 5 independentint*addresses—frequently used to store ragged arrays of variable-length strings cleanly (char *days[] = {"Mon", "Tue", "Wednesday"};) without wasting rectangular matrix padding. - Pointer to an Array (
int (*ptr)[5];): Parentheses bind*first, makingptra single pointer capable of pointing to an entire 5-element integer row; incrementingptr++leaps forward by5 × sizeof(int) = 20bytes! - Pointer to Pointer (
int **pp;): Stores the address of another pointer variable, essential for mutating caller pointers inside functions or building dynamic 2D jagged matrices. - Generic Void Pointer (
void *vp;): Can hold the address of any data type without explicit cast, used bymalloc()andqsort(). Because the compiler has no base type width forvoid, avoid *cannot be dereferenced directly or used in pointer arithmetic until cast to a concrete pointer type like*(int *)vp. - Function Pointer (
int (*fp)(int, int);): Holds the entry address of executable code in the Text segment (fp = add;), allowing runtime callback dispatch (int ans = fp(4, 5);). Usingtypedef int (*BinaryOp)(int, int);lets arrays of function pointers drive extensible dispatch tables cleanly without nestedswitchblocks.
Applying const Qualification to Pointers: Placing const before or after the asterisk alters whether the pointed-to target data is read-only or the pointer variable itself is locked to one address (read declarations right-to-left around the asterisk):
| Declaration Syntax | Can Modify Target (*p = 5)? |
Can Reassign Pointer (p = &y)? |
Primary Usage Pattern |
|---|---|---|---|
const int *p = &x; | No (Read-only view) | Yes | Function input parameters reading caller arrays safely without mutation. |
int *const p = &x; | Yes | No (Fixed address) | Hardware memory-mapped I/O register aliases locked to one base address. |
const int *const p = &x; | No | No | Immutable lookup tables where neither pointer nor content may change. |
11.5 Call by Value vs Call by Reference (Simulated via Pointers)
Strictly speaking, C passes every argument by value—meaning the callee receives an independent local copy of each argument expression. When you pass plain integers to swap_val(int a, int b), modifying a and b only changes temporary variables inside swap_val's stack frame; the caller's originals stay untouched upon return.
To achieve Call by Reference semantics in C—allowing a callee to directly mutate caller variables or return multiple computed outputs simultaneously—the caller passes the addresses of its variables using & (swap_ref(&x, &y)), and the callee accepts pointer parameters (int *a, int *b) and modifies the caller's memory indirectly via *a and *b.
| Comparison Criterion | Call by Value | Call by Reference (Pointer Passing) |
|---|---|---|
| What is Passed | Copy of variable's rvalue data. | Memory address (&var) stored into formal pointer parameter. |
| Impact on Caller Data | Caller originals remain strictly immutable and isolated. | Callee dereferencing (*p = ...) mutates caller's actual variables. |
| Memory Overhead | Duplicates entire variable/struct on stack. | Passes single 4/8-byte pointer regardless of payload size. |
| Number of Outputs | Limited to single return value. | Can output multiple modified results back to caller simultaneously. |
#include <stdio.h>
void swap_by_value(int a, int b) {
int t = a; a = b; b = t; /* Modifies local copies only */
}
void swap_by_reference(int *a, int *b) {
int t = *a; *a = *b; *b = t;/* Modifies caller's memory via pointers */
}
void min_max_array(const int *arr, int n, int *out_min, int *out_max) {
*out_min = *out_max = *arr;
for (int i = 1; i < n; i++) {
if (*(arr + i) < *out_min) *out_min = *(arr + i);
if (*(arr + i) > *out_max) *out_max = *(arr + i);
}
}
int main(void) {
int x = 10, y = 25;
swap_by_value(x, y);
printf("After swap_by_value : x=%d, y=%d\n", x, y);
swap_by_reference(&x, &y);
printf("After swap_by_reference: x=%d, y=%d\n", x, y);
int data[5] = {42, 17, 93, 8, 61}, min_v, max_v;
min_max_array(data, 5, &min_v, &max_v);
printf("Array Min = %d | Max = %d\n", min_v, max_v);
/* Array of pointers holding 3 constant strings */
const char *subjects[3] = {"Algorithms", "Pointers", "Files"};
for (int i = 0; i < 3; i++) {
printf("subjects[%d] at %p -> %s\n", i, (const void *)subjects[i], subjects[i]);
}
return 0;
}Chapter 12: Dynamic Memory Allocation (Concepts and Architecture)
12.1 Static vs Dynamic Memory Allocation and C Process Memory Layout
Traditional array declarations such as int buf[1000]; employ Static (Compile-Time) Memory Allocation: their exact capacity must be fixed before runtime, risking either severe memory wastage if only 10 slots are needed or buffer overflow if 1,500 items arrive. Dynamic Memory Allocation (DMA) solves both limitations by requesting exact amounts of memory at runtime from the operating system's Heap segment via pointers and releasing that storage manually once no longer needed.
A compiled C program executing in virtual RAM occupies five conceptual memory segments from low address to high address: (1) Text / Code Segment (read-only compiled machine opcodes), (2) Initialized Data Segment (globals and static variables given explicit non-zero initial values), (3) BSS Segment (uninitialized or zero-initialized globals and static variables cleared by the loader), (4) Heap (large dynamic pool managed via <stdlib.h> growing upward toward higher addresses), and (5) Call Stack (automatic local variables and function activation frames growing downward toward lower addresses).
| Virtual Memory Segment | Stored Entities | Allocation & Deallocation | Access & Mutability |
|---|---|---|---|
| Text (Code) Segment | Compiled CPU machine instructions, string literals (on modern OS). | Loaded once at process launch. | Read-Only & Executable (sharable across processes). |
| Initialized Data | Globals and static locals with explicit non-zero initializers. | Reserved in binary image; persists until program exit. | Read-Write. |
| BSS (Block Started by Symbol) | Uninitialized or zero-initialized globals and static variables. | Zero-filled automatically by OS loader at launch. | Read-Write. |
| Heap Segment | Runtime buffers created by malloc, calloc, realloc. | Grows upward; manually managed by programmer via free. | Read-Write (via pointers only). |
| Call Stack | Function return addresses, formal parameters, auto locals. | Grows downward; LIFO push on call, automatic pop on return. | Read-Write (fast CPU cache locality). |
Conceptual Heap Allocator Mechanics and Fragmentation: Inside the runtime C library, the heap allocator maintains metadata headers just preceding every returned block recording the block's exact allocated size and status (allocated vs free)—which explains why calling free(ptr) needs only the base pointer without requiring the programmer to pass the byte count again! Repeatedly allocating and freeing blocks of wildly varying sizes creates external fragmentation (abundant total free bytes split into tiny non-contiguous holes unable to satisfy a large contiguous request), whereas rounding requests up to alignment multiples creates minor internal fragmentation inside each block.
| Characteristic | Static / Automatic Allocation | Dynamic Memory Allocation (Heap) |
|---|---|---|
| Allocation Timing | Fixed at compile time (or block entry on stack). | Requested dynamically at runtime based on live input sizes. |
| Memory Segment | Data/BSS segment or Call Stack. | Heap memory pool managed via <stdlib.h>. |
| Resizability | Fixed capacity; cannot shrink or expand in place. | Resizable seamlessly via realloc() during execution. |
| Lifetime Control | Bound rigidly to lexical block or entire process lifetime. | Persists across function returns until explicitly passed to free(). |
| Access Mechanism | Direct named identifier or array subscript. | Indirectly accessed exclusively through pointer variables. |
12.2 Conceptual Overview of Heap Functions (<stdlib.h>)
Four foundational standard library functions declared in <stdlib.h> govern dynamic heap blocks. Always compute byte counts portably with sizeof rather than hardcoding literals (4 or 8), and always verify that the returned pointer is non-NULL before using the block—because exhausted RAM causes allocation routines to return NULL cleanly.
| Function Prototype | Initial Byte Contents | Conceptual Behavior & Key Use Case |
|---|---|---|
void *malloc(size_t size); |
Uninitialized garbage bytes | Allocates one contiguous raw block of size bytes; fastest when caller overwrites immediately. |
void *calloc(size_t num, size_t size); |
All bits cleared to 0 |
Allocates contiguous space for an array of num elements of size bytes each and zero-initializes every byte. |
void *realloc(void *ptr, size_t new_size); |
Preserves old bytes up to min(old, new); new tail uninitialized | Grows or shrinks an existing heap block, moving and copying contents automatically if adjacent heap space is unavailable. |
void free(void *ptr); |
N/A (Deallocates block) | Returns a previously allocated heap block back to the memory manager; safe no-op if passed NULL. |
12.3 Common Heap Defects and Defensive Practices
Because C delegates heap bookkeeping directly to the programmer rather than using an automatic garbage collector, four classic memory bugs must be guarded against conceptually:
- Memory Leak: Repeatedly allocating heap memory with
malloc/callocand losing the pointer or skippingfree()—gradually exhausting system memory in long-running services. - Dangling Pointer After Free: Continuing to read or write through
ptrafter callingfree(ptr). Immediately resettingptr = NULL;directly after everyfree(ptr);turns accidental reuse into a detectableNULLcheck rather than silent heap corruption. - Double Free: Calling
free(ptr)twice on the identical non-null address corrupts the allocator's internal free-list metadata. Settingptr = NULL;after freeing prevents double-free bugs completely becausefree(NULL)is guaranteed harmless. - Losing Original Pointer on
reallocFailure: Never writep = realloc(p, big_size);directly! Ifreallocruns out of memory, it returnsNULLwhile keeping the old block allocated—overwritingpleaks the original block. Always capture into a temporary pointertmp = realloc(p, big_size);and updatep = tmp;only whentmp != NULL.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 4;
int *scores = (int *)calloc((size_t)n, sizeof(int));
if (scores == NULL) {
printf("Initial allocation failed.\n");
return 1;
}
for (int i = 0; i < n; i++) scores[i] = (i + 1) * 10;
/* Safely expand dynamic capacity from 4 to 6 integers */
int new_n = 6;
int *resized = (int *)realloc(scores, (size_t)new_n * sizeof(int));
if (resized == NULL) {
printf("Reallocation failed; original block retained safely.\n");
free(scores);
return 1;
}
scores = resized;
scores[4] = 50;
scores[5] = 60;
printf("Dynamic scores: ");
for (int i = 0; i < new_n; i++) printf("%d ", scores[i]);
printf("\n");
free(scores);
scores = NULL; /* Eliminates dangling-pointer hazard */
return 0;
}Module IV: Structures and Files
Chapter 13: User-Defined Composite Types — Structures
13.1 Motivation, Declaration, Definition, and typedef Aliasing
Whereas an array binds multiple items sharing the identical data type under a single name, real-world records typically bundle heterogeneous attributes of varying types—for example, representing a student by an integer roll number, a character array name, a single-character division code, and a floating-point CGPA. Keeping separate parallel arrays (rolls[60], names[60][40], cgpas[60]) quickly becomes error-prone when sorting or deleting entries. C solves this cleanly through a structure (struct), a user-defined composite aggregate grouping heterogeneous fields (called members) under one coherent record type.
A structure declaration introduces a blueprint template without immediately reserving variable memory unless variable identifiers follow the closing brace (notice the mandatory trailing semicolon after };). Combining typedef with struct creates a concise alias (such as Student) so callers omit repeating the keyword struct everywhere:
- Tagged Template + Separate Variables:
struct Student { int roll; char name[40]; float cgpa; };followed bystruct Student s1, s2;. typedefAlias Style:typedef struct { int day; int month; int year; } Date;allowing declarations likeDate dob = {15, 8, 2005};.- Self-Referential Structures (Recursive Types): Although a structure cannot contain an instance of itself directly (which would require infinite bytes), it can validly hold a pointer to its own structure type:
struct Node { int data; struct Node *next; };. Self-referential structures form the backbone of linked lists, stacks, queues, and binary trees.
13.2 Member Access, Initialization, Copying, and Structure Padding
Individual members of a structure variable are accessed using the dot (member selection) operator (.), written s1.roll = 101;. When working with a pointer to a structure (struct Student *ptr = &s1;), you can write (*ptr).roll (parentheses required because . binds tighter than *) or far more cleanly use the arrow operator (->): ptr->roll = 101;.
Structures support positional initialization (struct Student s1 = {101, "Ananya", 9.15f};), partial initialization (omitted trailing members automatically zero-fill), C99 designated initialization (struct Student s2 = {.name = "Rohan", .roll = 102};), and direct whole-structure assignment (s2 = s1; copies every byte including embedded arrays cleanly, unlike bare arrays!). Note that equality comparison s1 == s2 is invalid in C because padding bytes between fields can contain arbitrary leftover values; compare individual members field-by-field instead.
Because modern CPUs read 4-byte integers and 8-byte doubles fastest when stored at memory addresses divisible by their word size (natural alignment), the compiler inserts invisible unused padding bytes between structure members and at the tail end:
Worked Alignment Trace: Consider struct Packet { char tag; int id; char flag; }; on a 32-bit aligned compiler. tag (1 byte) sits at offset 0; 3 padding bytes follow (offsets 1–3) so 4-byte id aligns at offset 4 (bytes 4–7); flag sits at offset 8; and 3 trailing padding bytes round total structure size from 6 up to 12 bytes (a multiple of largest alignment 4). Simply reordering members from largest to smallest (int id; char tag; char flag;) shrinks padding to 2 trailing bytes, reducing total footprint from 12 bytes to 8 bytes!
| Declaration Order | Byte Offset Map | Total Size | Wasted Padding Bytes |
|---|---|---|---|
char tag; int id; char flag; |
[0:tag] [1..3:pad] [4..7:id] [8:flag] [9..11:pad] |
12 bytes | 6 bytes (50% wasted!) |
int id; char tag; char flag; |
[0..3:id] [4:tag] [5:flag] [6..7:pad] |
8 bytes | 2 bytes (33% RAM saved) |
13.3 Array of Structures
When processing an entire class register, employee payroll, or product inventory, programmers declare an array of structures: struct Student cls[60];. Each element cls[i] stores one complete record in contiguous memory, and individual fields are addressed cleanly as cls[i].roll or cls[i].name. Sorting records by CGPA or alphabetical name swaps entire struct Student elements cleanly via a single temporary structure variable. Searching an array of structures iterates linearly over keys (e.g., comparing cls[i].roll == target or strcmp(cls[i].name, query) == 0), or runs binary search once sorted by that key field.
13.4 Nested Structures (Structures within Structures) and Function Passing
Real entities exhibit hierarchical composition—for instance, an Employee record embeds a joining Date structure and a residential Address structure. C supports nested structures either by defining a separate inner structure type first (struct Date doj; inside struct Employee) or by embedding an inner struct block directly inside the outer definition. Accessing inner fields chains the dot operator left-to-right: emp.doj.year = 2024; (or emp_ptr->doj.year with pointers).
Structures pass to functions in three ways: passing a single field (display_mark(s.cgpa)), passing the whole structure by value (copies all bytes onto the stack, isolating caller state), or passing a structure pointer (void update(struct Student *p) or read-only const struct Student *p)—strongly preferred for large records because passing an 8-byte pointer eliminates copying hundreds of bytes onto the stack.
13.5 Enumerations (enum), typedef Aliases, and Bit-Fields
Two companion constructs frequently accompany structures in clean system code. First, an enumeration (enum) assigns readable symbolic names to discrete integer constants starting at 0 by default (enum Weekday { MON = 1, TUE, WED, THU, FRI }; automatically assigns 2, 3, 4, 5 to subsequent items), eliminating cryptic magic numbers inside switch blocks. Second, bit-fields inside a structure specify exact bit widths after a colon (unsigned int is_admin : 1; unsigned int level : 3;), allowing hardware drivers and network protocols to pack multiple Boolean or small integer flags inside a single 4-byte word. Note that because bit-fields need not align on byte boundaries, applying the address-of operator & to a bit-field is prohibited in C.
#include <stdio.h>
#include <string.h>
struct Date {
int day, month, year;
};
struct Student {
int roll;
char name[32];
struct Date dob; /* Nested structure */
float marks[3];
float average;
};
void compute_avg(struct Student *s) {
float sum = 0.0f;
for (int j = 0; j < 3; j++) sum += s->marks[j];
s->average = sum / 3.0f; /* Arrow operator updates caller struct */
}
int main(void) {
struct Student cls[3] = {
{101, "Arjun", {12, 4, 2006}, {85.0f, 90.0f, 88.0f}, 0.0f},
{102, "Diya", {25, 9, 2005}, {94.0f, 92.0f, 96.0f}, 0.0f},
{103, "Kiran", { 3, 1, 2006}, {78.0f, 82.0f, 80.0f}, 0.0f}
};
for (int i = 0; i < 3; i++) compute_avg(&cls[i]);
/* Sort descending by average mark */
for (int i = 0; i < 2; i++) {
for (int j = i + 1; j < 3; j++) {
if (cls[j].average > cls[i].average) {
struct Student tmp = cls[i];
cls[i] = cls[j];
cls[j] = tmp;
}
}
}
printf("Merit List:\n");
for (int i = 0; i < 3; i++) {
printf("%d. %-10s (Roll %d, DOB %02d/%02d/%04d) Avg: %.2f\n",
i + 1, cls[i].name, cls[i].roll,
cls[i].dob.day, cls[i].dob.month, cls[i].dob.year,
cls[i].average);
}
return 0;
}Passing Structures by Value vs Pointer to Functions: Notice in Listing 4.1 above how compute_avg(&cls[i]) transmits solely an 8-byte pointer rather than copying the entire 56-byte student record onto the stack, enabling direct in-place updates via s->average. Conversely, read-only reporting functions such as void print_employee(const Employee *e) prevent accidental member mutation at compile time while preserving zero-copy pointer speed. Listing 4.1B illustrates returning a computed structure directly from a factory helper alongside searching an array of employee records.
#include <stdio.h>
#include <string.h>
typedef struct {
int emp_id;
char name[30];
double basic_pay;
double net_pay;
} Employee;
Employee create_employee(int id, const char *name, double basic) {
Employee e;
e.emp_id = id;
strncpy(e.name, name, sizeof(e.name) - 1);
e.name[sizeof(e.name) - 1] = '\0';
e.basic_pay = basic;
e.net_pay = basic + 0.25 * basic - 0.10 * basic; /* +25% allowance - 10% tax */
return e; /* Returns copy of initialized struct */
}
const Employee *find_by_id(const Employee staff[], int count, int target_id) {
for (int i = 0; i < count; i++) {
if (staff[i].emp_id == target_id) return &staff[i];
}
return NULL;
}
int main(void) {
Employee team[3];
team[0] = create_employee(501, "Meenakshi", 40000.0);
team[1] = create_employee(502, "Suresh", 52000.0);
team[2] = create_employee(503, "Lakshmi", 46000.0);
const Employee *hit = find_by_id(team, 3, 502);
if (hit != NULL) {
printf("Record Found -> %s (ID %d): Net Pay = Rs. %.2f\n",
hit->name, hit->emp_id, hit->net_pay);
}
return 0;
}Chapter 14: Unions and Memory Overlay Semantics
14.1 Declaration, Definition, and Shared Memory Layout
Syntactically identical to a structure except for replacing the keyword struct with union, a union overlays all of its declared members onto the exact same starting memory address (byte offset 0). Instead of allocating separate independent bytes for every member, the compiler allocates only enough space to accommodate the single largest member (rounded up to alignment boundaries):
&u. Consequently, writing to one member overwrites the shared bytes occupied by all other members.Because members overlap physically, a union can validly hold only one active member at any instant. Reading member b immediately after storing a value into member a reinterprets a's raw binary bit pattern according to b's type encoding (a technique occasionally used in embedded systems for inspecting IEEE 754 floating-point bytes or hardware registers). Furthermore, an initializer list for a union initializes strictly its first declared member unless using C99 designated initializers (e.g., union Data d = {.f = 3.5f};).
14.2 Tagged Unions, Endianness Inspection, and Structure vs Union Comparison
In production software, programmers avoid guessing which union member is currently valid by pairing an enum discriminator tag alongside a union payload wrapped inside an outer struct (known as a tagged union or variant record). For instance, a billing record stores either a numeric GST percentage or a flat cess fee without wasting bytes for mutually exclusive fields. Similarly, compilers and network stacks construct Abstract Syntax Trees (ASTs) and IP/TCP protocol frames where an instruction or packet payload holds one of several mutually exclusive variants—saving over 60% of heap memory compared to keeping separate unused fields inside a flat structure.
Low-level systems engineers also employ unions containing an integer alongside a fixed byte array (union EndianCheck { unsigned int word; unsigned char bytes[4]; };) to inspect individual memory bytes safely: storing 0x01020304 into word and printing bytes[0] reveals 0x04 on little-endian CPUs (such as x86-64, storing least-significant byte at lowest RAM address) versus 0x01 on big-endian network/mainframe layouts.
| Comparison Dimension | Structure (struct) |
Union (union) |
|---|---|---|
| Keyword & Concept | struct; aggregates heterogeneous members simultaneously. | union; overlays mutually exclusive members onto shared RAM. |
| Memory Footprint | Sum of all member sizes plus alignment padding. | Size of the single largest member plus alignment padding. |
| Member Base Offsets | Each member receives a distinct, non-overlapping offset. | Every member begins at identical offset 0 (&u.a == &u.b). |
| Active Storage | All members retain independent values concurrently. | Strictly one member holds a meaningful valid value at a time. |
| Initialization | Brace list initializes all members sequentially. | Brace list initializes only the first declared member. |
| Primary Engineering Use | Database records, packets, trees, student/employee entities. | Memory-constrained embedded devices, tagged variants, byte unpacking. |
#include <stdio.h>
union Value {
int i_val;
double d_val;
char code[8];
};
enum Tag { TYPE_INT, TYPE_DOUBLE };
struct TaggedItem {
enum Tag kind; /* Discriminator recording active union field */
union Value payload;
};
int main(void) {
union Value v;
printf("sizeof(union Value) = %zu bytes (max member size)\n", sizeof(v));
printf("Addresses equal? &v.i_val=%p, &v.d_val=%p\n",
(void *)&v.i_val, (void *)&v.d_val);
v.i_val = 42;
printf("Active i_val = %d\n", v.i_val);
v.d_val = 98.75; /* Overwrites shared bytes previously holding i_val */
printf("Active d_val = %.2f\n", v.d_val);
struct TaggedItem item = {TYPE_DOUBLE, {.d_val = 273.15}};
if (item.kind == TYPE_INT) {
printf("Tagged int: %d\n", item.payload.i_val);
} else {
printf("Tagged double: %.2f\n", item.payload.d_val);
}
return 0;
}Chapter 15: File Handling — Text and Binary Stream Processing
15.1 Persistent Storage, FILE Streams, Text vs Binary Files
Variables, arrays, and structures reside in volatile RAM and vanish instantaneously when a program exits or power drops. File handling stores and retrieves persistent datasets on secondary storage (SSDs, hard drives, flash drives) through buffered I/O channels called streams defined in <stdio.h>. When a program opens a disk file, the C runtime allocates a control structure of opaque type FILE tracking the internal RAM buffer, current read/write cursor offset, mode flags, and error/EOF indicators, returning a FILE *fp handle.
C classifies disk streams into two fundamentally different storage formats:
| Feature | Text Files ("r", "w", "a") |
Binary Files ("rb", "wb", "ab") |
|---|---|---|
| Data Encoding | Human-readable ASCII/UTF-8 character sequences (e.g., 12345 takes 5 bytes). | Exact raw binary RAM bit pattern (e.g., int 12345 always takes 4 bytes). |
| Newline Translation | Translates internal '\n' to OS convention (e.g., \r\n on Windows) automatically. | Zero character translation; bytes are copied verbatim bit-for-bit. |
| Numeric Precision & Speed | Requires decimal formatting/parsing (fprintf/fscanf); slight rounding possible on floats. | Zero formatting overhead; exact IEEE 754 preservation; ideal for struct records. |
| Portability | Directly viewable in any text editor across operating systems. | Depends on CPU endianness and compiler structure padding layout. |
15.2 File Opening Modes and Lifecycle Safety
Calling FILE *fopen(const char *filename, const char *mode); requests the OS to open or create the named file under an explicit permission mode. Always guard immediately with if (fp == NULL)—for example, if opening a missing file for reading or lacking directory write permissions—and always close every opened handle via fclose(fp); to flush buffered bytes safely to disk and release OS file descriptors.
| Text Mode | Binary Mode | Permitted Ops | If File Exists | If File Does Not Exist |
|---|---|---|---|---|
"r" | "rb" | Read only | Opens at byte 0; preserves content. | Returns NULL (fails). |
"w" | "wb" | Write only | Truncates to 0 bytes (erases old content!). | Creates new empty file. |
"a" | "ab" | Append only | Opens with all writes forced to end-of-file. | Creates new empty file. |
"r+" | "rb+" | Read & Write | Opens at byte 0; preserves content for updates. | Returns NULL (fails). |
"w+" | "wb+" | Write & Read | Truncates to 0 bytes, allows read after write/seek. | Creates new empty file. |
"a+" | "ab+" | Read & Append | Reads anywhere; writes always append at EOF. | Creates new empty file. |
15.3 Character, Line, and Formatted File Operations
Sequential text processing relies on four pairs of standard functions:
- Character I/O (
fgetc/fputc):int fgetc(FILE *fp)reads the next byte cast asunsigned charconverted toint, or returnsEOFupon end-of-file or error. Store the return value strictly in anint ch;(neverchar, because unsigned char loses negativeEOFand signed char confuses byte0xFFwithEOF!).fputc(ch, fp)writes one character. - String Line I/O (
fgets/fputs):fgets(buf, size, fp)safely reads up tosize - 1characters stopping at'\n'or EOF and appends'\0', returningNULLat EOF.fputs(str, fp)writes a null-terminated string without injecting extra newlines. - Formatted I/O (
fprintf/fscanf): Work identically toprintfandscanfexcept for takingFILE *fpas their first argument. Avoid looping onwhile (!feof(fp))directly becausefeof()activates only after a read attempt fails past EOF—instead loop directly on the input function's return status:while (fscanf(fp, ...) == 2)orwhile ((ch = fgetc(fp)) != EOF). - Filesystem Utilities & Error Checks:
ferror(fp)checks I/O hardware/stream failures,clearerr(fp)resets error/EOF flags,remove("old.txt")deletes a file, andrename("a.txt", "b.txt")renames or moves it.
#include <stdio.h>
#include <ctype.h>
int main(void) {
FILE *src = fopen("notes.txt", "r");
if (src == NULL) {
perror("Cannot open notes.txt");
return 1;
}
FILE *dst = fopen("backup.txt", "w");
if (dst == NULL) {
perror("Cannot create backup.txt");
fclose(src);
return 1;
}
int ch, in_word = 0;
long chars = 0, words = 0, lines = 0;
while ((ch = fgetc(src)) != EOF) {
fputc(ch, dst);
chars++;
if (ch == '\n') lines++;
if (isspace((unsigned char)ch)) {
in_word = 0;
} else if (!in_word) {
in_word = 1;
words++;
}
}
fclose(src);
fclose(dst);
printf("Copied successfully: %ld chars, %ld words, %ld lines.\n",
chars, words, lines);
return 0;
}15.4 Binary Block I/O and Random Access Positioning
To store fixed-size structures or numeric arrays directly onto disk without decimal conversion overhead, use binary block transfers:
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp);Writescountitems each of widthsizebytes from RAM addressptrinto streamfp, returning items successfully written.size_t fread(void *ptr, size_t size, size_t count, FILE *fp);Reads up tocountitems ofsizebytes into memory atptr, returning items successfully read.
Because fixed-width binary records sit sequentially at predictable byte offsets, C allows instant random access (jumping directly to record k in O(1) without scanning preceding records) via three cursor positioning functions:
int fseek(FILE *fp, long offset, int whence);Moves file cursor relative toSEEK_SET(beginning of file, byte 0),SEEK_CUR(current cursor location), orSEEK_END(end of file—offset typically negative or 0).long ftell(FILE *fp);Returns the current byte offset from file start (useful for determining file size by seeking toSEEK_END).void rewind(FILE *fp);Resets the file cursor immediately back to byte 0 and clears error flags (equivalent tofseek(fp, 0L, SEEK_SET)plusclearerr(fp)).
#include <stdio.h>
struct Item {
int id;
char name[24];
double price;
};
int main(void) {
struct Item stock[3] = {
{1, "Keyboard", 750.0},
{2, "Mouse", 420.0},
{3, "Monitor", 8900.0}
};
FILE *fp = fopen("inventory.dat", "wb+");
if (fp == NULL) return 1;
fwrite(stock, sizeof(struct Item), 3, fp);
/* Random access: jump directly to 2nd record (index 1) and update price */
long rec_pos = 1L * (long)sizeof(struct Item);
fseek(fp, rec_pos, SEEK_SET);
struct Item target;
if (fread(&target, sizeof(struct Item), 1, fp) == 1) {
target.price = 499.0;
fseek(fp, rec_pos, SEEK_SET); /* Rewind back to same record slot */
fwrite(&target, sizeof(struct Item), 1, fp);
}
/* Read all records back from byte 0 */
rewind(fp);
printf("Updated Binary Inventory:\n");
while (fread(&target, sizeof(struct Item), 1, fp) == 1) {
printf("ID: %d | %-10s | Rs. %.2f\n", target.id, target.name, target.price);
}
printf("File byte size via ftell: %ld bytes\n", ftell(fp));
fclose(fp);
return 0;
}15.5 Stream Buffering, Error Diagnostics, and Logical Record Deletion
Standard streams employ three distinct buffering policies: full buffering (disk files accumulate chunks such as 4 KB in RAM before writing to hardware, dramatically minimizing expensive OS system calls), line buffering (stdout when attached to an interactive terminal flushes immediately upon '\n'), and unbuffered (stderr writes error messages instantly so diagnostic traces are never lost during crashes). Calling fflush(fp) forces buffered output bytes onto disk immediately; never pass an input stream such as fflush(stdin) in portable ISO C, as flushing an input stream causes non-standard behavior outside Windows MSVC.
Because deleting a record physically from the middle of a disk file leaves a hole, file-based databases delete records using either logical deletion (marking an active = 0 flag byte inside the struct and overwriting via fseek/fwrite) or compaction (copying all active records sequentially into a temporary file "temp.dat", closing both handles, invoking remove("inventory.dat"), and renaming via rename("temp.dat", "inventory.dat")). Whenever a file call fails, inspect errno via perror("Context") to print the human-readable OS error message (such as No such file or directory or Permission denied).
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("grades.txt", "w");
if (!fp) { perror("Write open failed"); return 1; }
fprintf(fp, "101 Asha 88.50\n102 Manu 91.25\n103 Riya 79.00\n");
fclose(fp);
fp = fopen("grades.txt", "r");
if (!fp) { perror("Read open failed"); return 1; }
int roll, query_roll = 102, found = 0;
char name[32];
double mark;
while (fscanf(fp, "%d %31s %lf", &roll, name, &mark) == 3) {
if (roll == query_roll) {
printf("Found Roll %d -> Name: %s, Marks: %.2f\n", roll, name, mark);
found = 1;
break;
}
}
if (!found) printf("Roll %d not found in grades.txt.\n", query_roll);
fclose(fp);
return 0;
}Module V: Preprocessor, Headers, CLI Arguments & Advanced Programs
Chapter 16: The C Preprocessor and Directive Architecture
16.1 Preprocessor Execution Phase and Syntax Rules
Before the C compiler ever parses a single variable declaration, loop, or semicolon, every source file passes through a specialized textual macro processor called the C Preprocessor (CPP). Operating strictly on lexical tokens and lines prior to syntax checking, the preprocessor strips comments, substitutes macros, merges header files, and selectively keeps or omits source code blocks. Every preprocessor directive begins with the hash symbol # as the first non-whitespace character on a line and never ends with a semicolon (appending a trailing semicolon accidentally becomes part of a macro's expansion text, breaking expressions!). Directives spanning multiple physical lines use a trailing backslash \ directly before the newline.
16.2 File Inclusion, Macros, and Side-Effect Hygiene
File inclusion directives assemble program interfaces cleanly: #include <filename.h> searches compiler system include paths, whereas #include "filename.h" checks the local source directory first before falling back to system directories.
Macro Substitution (#define and #undef): Object-like macros define symbolic constants (#define BUFFER_SIZE 1024), replacing every unquoted occurrence of BUFFER_SIZE before compilation. Function-like macros accept parameters (#define SQUARE(x) ((x) * (x))). Observe two non-negotiable defensive macro disciplines:
- Full Parenthesization: Always wrap both every macro parameter
(x)and the entire replacement expression((x) * (x))in parentheses. Without inner parentheses,#define BAD_SQR(x) (x * x)expandsBAD_SQR(2 + 3)textually to(2 + 3 * 2 + 3), yielding11instead of25! Without outer parentheses,100 / BAD_SQR(5)expands to100 / 5 * 5, yielding100instead of4! - Side-Effect Trap with Increment Arguments: Because macro arguments undergo blind textual substitution rather than pass-by-value evaluation, passing an increment expression like
SQUARE(i++)expands into((i++) * (i++)), incrementingitwice unpredictably! Preferstatic inlinefunctions when arguments have side effects. - Stringification (
#) and Token Pasting (##): Inside a macro body,#argwraps an argument token inside string quotes (e.g.,#define PRINT_VAR(v) printf(#v " = %d\n", v)), whilea ## bglues two identifiers into one token.#undef NAMEcancels an active macro definition cleanly.
| Standard Predefined Macro | Data Type | Expanded Value & Diagnostic Role |
|---|---|---|
__FILE__ | const char * | String literal containing current source file path/name for error logging. |
__LINE__ | int | Current source line number; ideal for assertion diagnostics. |
__DATE__ | const char * | Compilation date string formatted "Mmm dd yyyy". |
__TIME__ | const char * | Compilation timestamp string formatted "hh:mm:ss". |
__STDC__ | int | Expands to 1 when compiled strictly conforming to ISO C standard. |
16.3 Conditional Compilation Directives
Conditional directives control which code segments reach the compiler proper—indispensable for toggling debug traces, switching between Windows/Linux system calls, or disabling deprecated modules without deleting source lines:
#ifdef MACRO/#ifndef MACRO: Compiles enclosed lines only ifMACROis currently defined (or not defined).#if expr/#elif expr/#else/#endif: Evaluates constant integer preprocessor expressions (supportingdefined(MACRO)checks).#error messageand#pragma:#errorhalts compilation immediately with a clear diagnostic message (e.g., rejecting incompatible platforms);#pragmaconveys compiler-specific directives such as packing hints or#pragma once.
#include <stdio.h>
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define SQR(x) ((x) * (x))
#define TRACE(var) printf("[DEBUG %s:%d] " #var " = %d\n", __FILE__, __LINE__, (var))
#define DEBUG_MODE 1
int main(void) {
int p = 3, q = 7;
int top = MAX(p + 2, q);
int sq = SQR(p + 1);
#if DEBUG_MODE
TRACE(top);
TRACE(sq);
#else
printf("Release build output: top=%d, sq=%d\n", top, sq);
#endif
printf("Built on %s at %s (ANSI C flag = %d)\n", __DATE__, __TIME__, __STDC__);
return 0;
}16.4 Multi-Statement Macros, Preprocessor Reference, and Macro Alternatives
When writing multi-statement macros, wrapping statements inside plain braces { stmt1; stmt2; } breaks if-else parsing: writing if (err) LOG_ERR(x); else recover(); expands the trailing semicolon after } into an empty statement, causing a syntax error before else! Standard C systems code solves this universally using the do { ... } while (0) idiom (with no trailing semicolon): #define LOG_ERR(x) do { fprintf(stderr, "Err: %d\n", (x)); err_count++; } while (0). This guarantees single-execution semantics while absorbing the caller's semicolon cleanly inside any if-else branch.
| Directive | Syntax Pattern | Preprocessor Role |
|---|---|---|
#include | #include <stdio.h> / "my.h" | Embeds system or local header file text into translation unit. |
#define / #undef | #define PI 3.14 / #undef PI | Defines object/function-like macros or removes an existing macro name. |
#ifdef / #ifndef | #ifndef GUARD_H | Tests whether macro identifier is defined; backbone of header include guards. |
#if / #elif / #else / #endif | #if VER >= 2 | Evaluates constant integer expressions at preprocessing time. |
#error | #error Unsupported target | Aborts compilation with custom diagnostic message on invalid builds. |
#line / #pragma | #line 100 "gen.c" / #pragma once | Overrides line/file diagnostics (used by code generators) or supplies compiler hints. |
| Mechanism | Type Safety? | Scope Obeyed? | Addressable in RAM? | Recommended Use |
|---|---|---|---|---|
#define NAME val | No (textual) | File-wide from line downward | No | Array sizes in C89, conditional flags, stringification macros. |
const variable | Yes | Block / File scope | Yes | Typed physical constants and read-only pointer parameters. |
enum { ... } | Integral int | Block / File scope | No | Related named integer states, error codes, menu options. |
static inline fn | Yes | Block / File scope | Yes (if address taken) | Replacing function-like macros safely without double-evaluation bugs. |
Chapter 17: Custom Header File Creation and Multi-File Program Design
17.1 Separating Interface (.h) from Implementation (.c)
Real-world C software never jams thousands of lines into one file. Instead, developers partition reusable subsystems into paired modules: a header file (module.h) declaring the public interface contract, and an implementation file (module.c) holding the actual function definitions and private static helpers. Multiple client files (main.c, reports.c) simply include "module.h", compile independently into object files (.o), and let the linker join them cleanly.
17.2 Include Guards and Linker Hygiene
Suppose main.c includes both "analytics.h" and "reports.h", and both headers internally include "stats.h". Without protection, stats.h gets pasted twice into main.c, triggering duplicate struct or typedef compilation errors! Every custom header file prevents double inclusion using an include guard wrapping its entire body:
- Canonical Portable Include Guard:
#ifndef STATS_H→#define STATS_H→ header contents →#endif /* STATS_H */. On first inclusion,STATS_His absent, so the body expands and definesSTATS_H; on every subsequent inclusion within the same translation unit,STATS_His already defined so the preprocessor skips the entire file silently. (Most modern compilers also support#pragma onceas a concise extension.)
| Construct Type | Place in .h Header? |
Place in .c Source? |
Reason / Linker Consequence |
|---|---|---|---|
| Function Prototypes | Yes (Public API) | Only private static ones | Enables cross-file compile-time parameter/return type checking. |
| Function Bodies | No (unless static inline) | Yes | Putting non-inline function bodies in headers causes multiple-definition linker errors. |
struct / union / enum / typedef | Yes | Only file-private types | Types allocate zero RAM and must match identically across all modules. |
| Global Variables | extern int g_var; only | int g_var = 0; (exact once) | Placing definitions without extern in .h breaks linking with duplicate symbols. |
#define Constants & Guards | Yes | Local constants | Preprocessor macros expand safely per translation unit without symbol export. |
/* -------- File 1: vecstats.h -------- */
#ifndef VECSTATS_H
#define VECSTATS_H
#include <stddef.h>
typedef struct {
double min_val;
double max_val;
double mean_val;
} StatsSummary;
extern int g_stats_runs; /* External linkage declaration only */
StatsSummary compute_summary(const double *arr, size_t n);
#endif /* VECSTATS_H */
/* -------- File 2: vecstats.c -------- */
#include "vecstats.h"
int g_stats_runs = 0; /* Single global definition in implementation file */
StatsSummary compute_summary(const double *arr, size_t n) {
StatsSummary res = {0.0, 0.0, 0.0};
if (arr == NULL || n == 0) return res;
res.min_val = res.max_val = arr[0];
double sum = 0.0;
for (size_t i = 0; i < n; i++) {
if (arr[i] < res.min_val) res.min_val = arr[i];
if (arr[i] > res.max_val) res.max_val = arr[i];
sum += arr[i];
}
res.mean_val = sum / (double)n;
g_stats_runs++;
return res;
}
/* -------- File 3: main.c (Compile: gcc -Wall main.c vecstats.c -o app) -------- */
#include <stdio.h>
#include "vecstats.h"
int main(void) {
double samples[] = {12.5, 45.0, 19.25, 31.0, 22.25};
StatsSummary s = compute_summary(samples, 5);
printf("Min=%.2f | Max=%.2f | Mean=%.2f | Runs=%d\n",
s.min_val, s.max_val, s.mean_val, g_stats_runs);
return 0;
}17.3 Multi-File Build Pipeline and Header Coupling Best Practices
In larger applications, recompiling all source files after editing one function wastes build time. Separating compilation from linking permits incremental builds: compiling gcc -c vecstats.c -o vecstats.o and gcc -c main.c -o main.o generates independent binary object files, followed by gcc main.o vecstats.o -o stats_app to link them. Whenever a header uses only a pointer to another structure (struct Node *next;), use a forward declaration (struct Node;) rather than nested #include chains to minimize compile-time coupling. Keep headers self-contained—every .h should explicitly include any standard headers (such as <stddef.h> for size_t) that its own prototypes require—so clients never suffer hidden ordering bugs.
Chapter 18: Command Line Arguments in C
18.1 Signature and Memory Layout of argc and argv
Interactive scanf() prompts fail whenever programs must be automated inside shell scripts, cron jobs, or batch pipelines. Instead, standard command-line utilities receive configuration flags and file paths directly at launch via command line arguments passed by the operating system into main():
argv[0] holds the program invocation name, argv[1] .. argv[argc-1] hold user arguments, and argv[argc] is guaranteed to be NULL.For example, launching ./mycopy report.txt backup.txt supplies argc = 3 with argv[0] = "./mycopy", argv[1] = "report.txt", argv[2] = "backup.txt", and argv[3] = NULL. Always inspect argc before indexing argv[1] or argv[2]—accessing absent arguments crashes with a segmentation fault! Because every argv[i] arrives purely as text strings (even numeric inputs like "250"), choose conversion routines carefully based on validation requirements:
| Conversion Function | Header | Invalid Input Handling & Base Support |
|---|---|---|
atoi(s) / atof(s) | <stdlib.h> | Base 10 only; silently returns 0 on "xyz" with zero overflow diagnostics. |
strtol(s, &end, base) | <stdlib.h> | Supports base 2–36 (or auto 0 for hex/octal), sets end to reject partial garbage, sets errno = ERANGE on overflow. |
strtod(s, &end) | <stdlib.h> | Parses floating-point strings safely while exposing trailing non-numeric characters via end. |
18.2 Option Flag Parsing and Command-Line File Searching
Real UNIX/Linux CLI tools iterate over for (int i = 1; i < argc; i++) checking whether argv[i][0] == '-' to parse option flags (such as -n for line numbering or -v for verbose logging) before reading positional filename arguments. Listing 5.3B combines flag inspection, fopen(), bounded line reading via fgets(), and substring matching via strstr() to build a compact command-line pattern finder modeled after grep.
#include <stdio.h>
#include <stdlib.h>
/* Usage: ./cli_util copy <src> <dst> OR ./cli_util add <num1> <num2> */
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <add n1 n2 | copy src dst>\n", argv[0]);
return 1;
}
if (argv[1][0] == 'a' && argc == 4) {
char *end1 = NULL, *end2 = NULL;
double x = strtod(argv[2], &end1);
double y = strtod(argv[3], &end2);
if (*end1 != '\0' || *end2 != '\0') {
fprintf(stderr, "Error: non-numeric operand supplied.\n");
return 1;
}
printf("Sum = %.3f\n", x + y);
return 0;
}
if (argv[1][0] == 'c' && argc == 4) {
FILE *in = fopen(argv[2], "rb");
FILE *out = fopen(argv[3], "wb");
if (!in || !out) {
perror("File open failure");
if (in) fclose(in);
if (out) fclose(out);
return 1;
}
unsigned char buf[4096];
size_t nread;
while ((nread = fread(buf, 1, sizeof(buf), in)) > 0) {
fwrite(buf, 1, nread, out);
}
fclose(in);
fclose(out);
printf("Copied '%s' -> '%s' cleanly.\n", argv[2], argv[3]);
return 0;
}
fprintf(stderr, "Invalid command syntax.\n");
return 1;
}#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
int show_lines = 0, arg_idx = 1;
if (argc >= 2 && strcmp(argv[1], "-n") == 0) {
show_lines = 1;
arg_idx = 2;
}
if (argc - arg_idx != 2) {
fprintf(stderr, "Usage: %s [-n] <pattern> <filename>\n", argv[0]);
return 1;
}
const char *pattern = argv[arg_idx];
FILE *fp = fopen(argv[arg_idx + 1], "r");
if (!fp) { perror("Open error"); return 1; }
char line[512];
int line_no = 0, matches = 0;
while (fgets(line, sizeof(line), fp) != NULL) {
line_no++;
if (strstr(line, pattern) != NULL) {
if (show_lines) printf("%d: %s", line_no, line);
else printf("%s", line);
matches++;
}
}
fclose(fp);
printf("Total matching lines: %d\n", matches);
return 0;
}Chapter 19: Advanced Integrated Programs Using Pointers and Files
19.1 Dynamic 2D Matrices Using Double Pointers (int **)
When matrix dimensions rows × cols are unknown until runtime, allocating an array of rows integer row pointers (int **mat = malloc(rows * sizeof(int *));) and allocating each row vector individually yields full 2D indexing syntax mat[i][j] over dynamically sized matrices. Always deallocate in reverse order—free(mat[i]) for every row first, then free(mat)—and handle partial allocation failures cleanly to prevent memory leaks.
#include <stdio.h>
#include <stdlib.h>
int **alloc_matrix(int r, int c) {
int **m = (int **)malloc((size_t)r * sizeof(int *));
if (!m) return NULL;
for (int i = 0; i < r; i++) {
m[i] = (int *)calloc((size_t)c, sizeof(int));
if (!m[i]) {
for (int k = 0; k < i; k++) free(m[k]);
free(m);
return NULL;
}
}
return m;
}
void free_matrix(int **m, int r) {
if (!m) return;
for (int i = 0; i < r; i++) free(m[i]);
free(m);
}
int main(void) {
int r1 = 2, c1 = 3, c2 = 2;
int **A = alloc_matrix(r1, c1);
int **B = alloc_matrix(c1, c2);
int **C = alloc_matrix(r1, c2);
if (!A || !B || !C) { free_matrix(A, r1); free_matrix(B, c1); free_matrix(C, r1); return 1; }
int val = 1;
for (int i = 0; i < r1; i++) for (int j = 0; j < c1; j++) A[i][j] = val++;
for (int i = 0; i < c1; i++) for (int j = 0; j < c2; j++) B[i][j] = i + j + 1;
for (int i = 0; i < r1; i++)
for (int j = 0; j < c2; j++)
for (int k = 0; k < c1; k++)
C[i][j] += A[i][k] * B[k][j];
printf("Dynamic Product Matrix:\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) printf("%4d", C[i][j]);
printf("\n");
}
free_matrix(A, r1); free_matrix(B, c1); free_matrix(C, r1);
return 0;
}19.2 Dynamic Record Buffer, Function-Pointer Comparator, and Binary Persistence
Real-world data engines combine file sizing via fseek/ftell, dynamic heap arrays via malloc, generic sorting using function pointer callbacks (qsort from <stdlib.h>), and binary persistence via fread/fwrite. Because qsort() accepts a user callback int (*cmp)(const void *, const void *), the identical sort call orders records either by salary or alphabetically by name simply by passing a different comparator function pointer.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int id;
char name[28];
double salary;
} Employee;
int cmp_by_salary_desc(const void *a, const void *b) {
const Employee *ea = (const Employee *)a;
const Employee *eb = (const Employee *)b;
if (eb->salary > ea->salary) return 1;
if (eb->salary < ea->salary) return -1;
return 0;
}
int main(void) {
Employee seed[3] = {{101, "Neha", 54000.0}, {102, "Vivek", 72000.0}, {103, "Asha", 63500.0}};
FILE *fp = fopen("emp.bin", "wb");
if (!fp) return 1;
fwrite(seed, sizeof(Employee), 3, fp);
fclose(fp);
/* Dynamically inspect record count via fseek/ftell and load into heap */
fp = fopen("emp.bin", "rb");
if (!fp) return 1;
fseek(fp, 0L, SEEK_END);
long bytes = ftell(fp);
size_t count = (size_t)bytes / sizeof(Employee);
rewind(fp);
Employee *list = (Employee *)malloc(count * sizeof(Employee));
if (!list) { fclose(fp); return 1; }
fread(list, sizeof(Employee), count, fp);
fclose(fp);
qsort(list, count, sizeof(Employee), cmp_by_salary_desc);
fp = fopen("emp_sorted.bin", "wb");
if (fp) { fwrite(list, sizeof(Employee), count, fp); fclose(fp); }
printf("Employees Sorted by Salary (Descending):\n");
for (size_t i = 0; i < count; i++) {
printf("ID: %d | %-10s | Rs. %.2f\n", list[i].id, list[i].name, list[i].salary);
}
free(list);
list = NULL;
return 0;
}19.3 Command-Line Buffered XOR Cipher and Text Search Utility
Combining command-line arguments (argc, argv), pointer traversal over dynamic buffers, and binary stream chunking yields a fast file utility capable of searching patterns or applying reversible XOR byte transformations across files of arbitrary size using constant RAM.
#include <stdio.h>
#include <stdlib.h>
void transform_buffer(unsigned char *buf, size_t len, unsigned char key) {
unsigned char *end = buf + len;
for (unsigned char *p = buf; p < end; p++) {
*p = (unsigned char)(*p ^ key); /* Pointer traversal & bitwise XOR */
}
}
int main(int argc, char *argv[]) {
if (argc != 4) {
fprintf(stderr, "Usage: %s <input_file> <output_file> <key_byte>\n", argv[0]);
return 1;
}
unsigned char key = (unsigned char)strtol(argv[3], NULL, 10);
FILE *fin = fopen(argv[1], "rb");
FILE *fout = fopen(argv[2], "wb");
if (!fin || !fout) {
perror("Stream error");
if (fin) fclose(fin);
if (fout) fclose(fout);
return 1;
}
const size_t CHUNK = 4096;
unsigned char *buffer = (unsigned char *)malloc(CHUNK);
if (!buffer) { fclose(fin); fclose(fout); return 1; }
size_t bytes_read;
while ((bytes_read = fread(buffer, 1, CHUNK, fin)) > 0) {
transform_buffer(buffer, bytes_read, key);
fwrite(buffer, 1, bytes_read, fout);
}
free(buffer);
fclose(fin);
fclose(fout);
printf("Processed '%s' -> '%s' with key %u.\n", argv[1], argv[2], key);
return 0;
}19.4 Dynamic Linked List Persistence Across Binary Files
Combining self-referential structures, heap allocation via malloc(), pointer traversal, and binary files requires understanding a foundational systems rule: raw RAM pointer addresses must never be persisted verbatim to disk! When a program restarts, the operating system assigns completely different virtual heap addresses, making saved next pointers invalid garbage. Instead, serialize solely the payload data fields sequentially using fwrite(); upon reload, allocate fresh nodes on the heap using malloc(), read each payload record using fread(), and re-link the next pointers dynamically in memory.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int id;
char title[32];
} CoursePayload;
typedef struct Node {
CoursePayload data;
struct Node *next;
} Node;
Node *push_front(Node *head, int id, const char *title) {
Node *fresh = (Node *)malloc(sizeof(Node));
if (!fresh) return head;
fresh->data.id = id;
strncpy(fresh->data.title, title, sizeof(fresh->data.title) - 1);
fresh->data.title[sizeof(fresh->data.title) - 1] = '\0';
fresh->next = head;
return fresh;
}
void save_list(const Node *head, const char *fname) {
FILE *fp = fopen(fname, "wb");
if (!fp) return;
for (const Node *cur = head; cur != NULL; cur = cur->next) {
fwrite(&cur->data, sizeof(CoursePayload), 1, fp);
}
fclose(fp);
}
Node *load_list(const char *fname) {
FILE *fp = fopen(fname, "rb");
if (!fp) return NULL;
Node *head = NULL, *tail = NULL;
CoursePayload tmp;
while (fread(&tmp, sizeof(CoursePayload), 1, fp) == 1) {
Node *n = (Node *)malloc(sizeof(Node));
if (!n) break;
n->data = tmp;
n->next = NULL;
if (!head) head = tail = n;
else { tail->next = n; tail = n; }
}
fclose(fp);
return head;
}
void free_list(Node *head) {
while (head != NULL) {
Node *nxt = head->next;
free(head);
head = nxt;
}
}
int main(void) {
Node *roster = NULL;
roster = push_front(roster, 102, "Data Structures");
roster = push_front(roster, 101, "Problem Solving in C");
save_list(roster, "courses.bin");
free_list(roster);
Node *reloaded = load_list("courses.bin");
for (const Node *p = reloaded; p != NULL; p = p->next) {
printf("[%d] %s\n", p->data.id, p->data.title);
}
free_list(reloaded);
return 0;
}University of Kerala FYUGP Academic Framework
Syllabus details for BCA Semester 1 under official University of Kerala regulations.
Assessment comprises a 70-mark End-Semester Examination (2.5 Hours) and 30-mark Continuous Internal Evaluation.
About Problem Solving using C (University of Kerala BCA Sem 1)
Problem Solving using C (UK1DSCCAP101 • 4 Credits • 60 Hours (4 Hrs/Week)) is a DSC offering under the Bachelor of Computer Applications (BCA) Four-Year Undergraduate Programme (UoK FYUGP Regulations 2024 / 2025) at the University of Kerala. Structured across five sequentially integrated instructional modules, the course builds solid theoretical foundations and hands-on technical proficiency in problem solving using c. Students engage with core computing principles, structured problem-solving, implementation techniques, and modern industry practices aligned with Kerala State Higher Education Council outcome-based education standards.
Problem Solving using C Module-by-Module Curriculum Breakdown
Official syllabus unit modules prescribed by the University of Kerala FYUGP framework:
Introduction to Programming
Computer programming is not merely the mechanical act of typing syntax into an editor; it is the disciplined engineering process of translating an ambiguous real-world requirement into an unambiguous sequence of machine-executable instructions. Before writing a single line of C code, a programmer systematically decomposes the task using the Input–Process–Output (IPO) model. First, the programmer identifies all valid inputs, their domains, and edge cases.
Basic Concepts
An operator is a lexical symbol specifying an operation to be applied to one (unary), two (binary), or three (ternary) operands, while an expression combines operators, variables, and constants to yield a computed value. The foundational state-mutating operator in C is the simple assignment operator ( = ), which evaluates the rvalue expression on its right-hand side and stores the resulting value into the addressable lvalue variable on its left-hand side.
Functions & Pointers
Large software systems become unmanageable if written as a single monolithic main() function spanning hundreds of lines. Modular programming decomposes a complex task into compact, single-responsibility subprograms called functions using top-down refinement.
Structures and Files
Whereas an array binds multiple items sharing the identical data type under a single name, real-world records typically bundle heterogeneous attributes of varying types—for example, representing a student by an integer roll number, a character array name, a single-character division code, and a floating-point CGPA. Keeping separate parallel arrays ( rolls[60], names[60][40], cgpas[60] ) quickly becomes error-prone when sorting or deleting entries.
Preprocessor, Headers, CLI Arguments & Advanced Programs
Before the C compiler ever parses a single variable declaration, loop, or semicolon, every source file passes through a specialized textual macro processor called the C Preprocessor (CPP). Operating strictly on lexical tokens and lines prior to syntax checking, the preprocessor strips comments, substitutes macros, merges header files, and selectively keeps or omits source code blocks.
Core Curriculum & Key Topics
- Problem Solving, Algorithms, and Flowcharts
- 1 Computational Problem Solving Lifecycle
- 2 Characteristics of an Algorithm and Complexity Intuition
- 3 Flowcharts and ANSI/ISO Standard Symbols
- 4 Worked Algorithmic Walkthroughs
- Structure of a C Program and Compilation Architecture
- 1 Anatomy of a Standard C Program
- 2 The Header File Concept and Standard Library Interfaces
Learning Outcomes
- Demonstrate authoritative comprehension of the foundational concepts, architectures, and principles of problem solving using c.
- Apply algorithmic, programming, or analytical techniques to design and evaluate practical computing solutions.
- Analyze system trade-offs, security considerations, and industry standards relevant to modern software and IT environments.
- Implement, test, and document structured technical workflows aligned with professional computing practices.
- Achieve exam-ready mastery of University of Kerala FYUGP BCA question patterns across short concepts, technical comparisons, and comprehensive essays.
University of Kerala Examination Scheme for Problem Solving using C
The evaluation framework for Problem Solving using C (UK1DSCCAP101) under University of Kerala FYUGP regulations combines Continuous Internal Evaluation (30 Marks) with the university End-Semester Examination (70 Marks) for a total of 100 Marks (2.5 Hours duration):
10 Questions × 3 Marks (Maximum ceiling 24 Marks). Short definitional and conceptual questions covering all 5 syllabus modules.
8 Questions × 6 Marks (Maximum ceiling 36 Marks). Paragraph questions, comparative evaluations, and analytical problems.
2 Questions × 10 Marks (Answer any 1 for 10 Marks). Long-form essay or comprehensive numerical workout problem.
Exam Preparation Strategy:
To score top marks in the University of Kerala UK1DSCCAP101 (Problem Solving using C) examination: 1. Write Clean, Traceable Code Snippets: Always include well-indented syntax examples with sample input and expected output for programming questions. 2. Explain Logic & Control Flow Step-by-Step: Before writing full programs, briefly outline the algorithm, key functions, or class hierarchy so examiners can award full step marks. 3. Highlight Edge Cases & Syntax Rules: Mention common runtime pitfalls, data type constraints, or security/validation practices where relevant. 4. Manage Time Across Sections: For the 2.5-hour 70-mark external paper, allocate 25 minutes to Part A definitions, 50 minutes to Part B short programs and comparisons, and 75 minutes to Part C full code-backed essays.
Exam Preparation & Study Guides — Problem Solving using C
What is Problem Solving, Algorithms, and Computational Decomposition and why is it important in Problem Solving using C?
Programming transforms an operational specification into deterministic machine instructions through the Input-Process-Output (IPO) model, breaking complex logic into unambiguous pseudocode and algorithmic procedures verified on boundary cases prior to coding.
What is Preprocessed (.i) → Assembly (.s /.asm) and why is it important in Problem Solving using C?
The compiler performs lexical scanning, syntax parsing, semantic type checks, optimization, and emits CPU assembly mnemonics.
What is Worked Expression Trace and why is it important in Problem Solving using C?
With int a=10, b=3, c=2, d=5, evaluating a + b * c − d / 2 % 2 > 12 &&!0 computes!0=1, b*c=6, d/2=2, 2%2=0, 10+6−0=16, 16>12=1, and 1&&1=1.
What is Scope, Lifetime, and Passing Arrays and why is it important in Problem Solving using C?
Local variables live inside call-stack frames pushed on call and popped on return; global variables live in Data/BSS across execution. Passing an array decays automatically to &arr[0] in O(1) time without copying, so pass length n explicitly (and use const int a[] when read-only); 2D array parameters require explicit column width (int m[][10]).
What is the key distinction in Structure vs Union Comparison?
Structures allocate disjoint offsets and retain all members simultaneously (total size ≥ sum); Unions overlay all members at offset 0 and hold one active member (size = largest member).
What is the official course code and credit structure for Problem Solving using C at University of Kerala?
Problem Solving using C carries the official course code UK1DSCCAP101 under the University of Kerala FYUGP BCA framework. It is awarded 4 credits (60 Hours (4 Hrs/Week)), evaluated through 30 marks Continuous Internal Evaluation (CIE) and 70 marks End-Semester Examination (ESE).
Where can students download free PDF notes for Problem Solving using C?
Students can read all 5 module notes online and download verified chapter-wise PDFs, combined exam notes, and quick revision sheets for Problem Solving using C (UK1DSCCAP101) directly from DegreeLive (degreelive.in) with zero paywalls or sign-ups.
Course outlines and study notes follow official University of Kerala curricula. Curated by Anoop (Thiruvananthapuram).
For feedback or corrections, contact [email protected].
Related Study Resources & Student Support
Related Semester 1 Subjects
Browse study notes for other courses in BCA Sem 1:
Financial Aid & Grants 2026-27
Check eligibility criteria and deadlines for Kerala government and merit scholarships (e-Grantz 3.0, KSHEC, DCE).
Request Notes
Can't find what you're looking for? Let us know which subject notes you need.