Original BCA Nepal study material. Units and topic order follow the approved 2025 BCA102 outline. All explanations, code examples, worked examples, and diagrams are original BCA Nepal material; they are not reproduced TU text. Official syllabus facts (unit titles, topic titles, teaching hours, credits, references) come from the course outline.

Course overview

BCA102 teaches structured programming using the C language. The course runs 6 hours per week: 3 hours theory and 3 hours practical, for 3 credits. Theory covers language fundamentals, the compilation model, control flow, functions, arrays, strings, structures, unions, pointers, dynamic memory, file handling, command-line arguments, and basic graphics. The practical hours are where understanding forms: write every example, break it deliberately, and read the compiler's error messages.

Examination typically expects you to (a) write short complete programs, (b) trace execution and state output, (c) explain a concept in 4–6 sentences, and (d) differentiate related constructs such as call by value vs call by reference, while vs do-while, and structure vs union. This guide covers every numbered topic in the approved TOC, in order, with worked examples, self-checks, and exam pointers.

Learning outcomes

Derived from the approved 2025 TOC only. After completing this course, you can:

  • Outline the evolution of programming languages and state the history, characteristics, and applications of C.
  • Describe the structure of a C program and its compilation and execution process.
  • Identify C tokens, declare variables, and use data types with implicit and explicit type casting.
  • Use operators and expressions with correct precedence and associativity.
  • Write formatted and unformatted input/output programs.
  • Control flow with if, if-else, nested if-else, else-if ladder, switch, loops, and jump statements.
  • Define and call functions, pass arguments by value and reference, and use recursion.
  • Declare, initialize, and process one-dimensional and two-dimensional arrays.
  • Handle strings using library functions and arrays of strings.
  • Define structures, unions, and enumerations; use typedef; pass structures to functions.
  • Use pointers with arrays, strings, functions, and structures; perform pointer arithmetic.
  • Allocate and free dynamic memory with malloc, calloc, realloc, and free.
  • Read and write text and binary files, use random-access functions, and parse command-line arguments.
  • Write basic C graphics programs with drawing primitives, colors, text, and simple animation.

Unit 1: Introduction to C Programming Language and Basics

Teaching hours: 5

1.1 Evolution of programming languages

Programming languages evolved through five generations. Each generation moved farther from hardware details and closer to human problem-solving.

Generation Name Characteristics Example
1GL Machine language Pure binary; directly executed by the CPU; hardware-specific Binary instructions
2GL Assembly language Mnemonics such as MOV, ADD; one-to-one with machine code; needs an assembler Assembly
3GL High-level language Problem-oriented, portable within a family, needs a compiler/interpreter C, FORTRAN, Pascal, COBOL
4GL Very high-level Closer to natural language; hides implementation details SQL, MATLAB
5GL Constraint/logic-based Specify what to solve, not how; used in AI Prolog

Swipe to see all columns

Why it matters: C is a third-generation language designed by Dennis Ritchie at Bell Labs in 1972 to rewrite the UNIX operating system. It combines high-level control structures with low-level memory access, which is why it remains central to systems programming.

Self-check: Which generation is C, and what program translates assembly into machine code? Answer: C is a 3GL (high-level language); an assembler translates assembly into machine code.

Exam pointers: Name all five generations with one example each; state that C was developed at Bell Labs by Dennis Ritchie (1972) for UNIX.

1.2 History, characteristics and applications of C

History: Dennis Ritchie developed C at Bell Labs in 1972, evolving it from Ken Thompson's B and Martin Richards's BCPL. It was used to write UNIX. ANSI standardized C as C89/C90; ISO later published C99, C11, and C17.

Characteristics of C:

  • Middle-level: mixes high-level structured constructs with low-level access to memory through pointers.
  • Procedural: programs are built from functions that execute step by step.
  • Portable: source code compiles on different platforms with a conforming compiler.
  • Efficient: small runtime overhead and direct hardware access; still used in OS kernels and embedded firmware.
  • Structured: uses if, for, while, switch; goto is not mandatory.
  • Rich operator set: arithmetic, relational, logical, bitwise, assignment, and pointer operators.

Applications: operating systems and device drivers, compilers and language runtimes, embedded systems and microcontroller firmware, database engines (parts of SQLite and PostgreSQL), networking utilities, game engines, scientific computing.

Self-check: Name two characteristics that make C suitable for operating-system development. Answer: Direct low-level memory access via pointers, and small runtime overhead/efficient code generation.

Exam pointers: State C's origin (Bell Labs, Dennis Ritchie, 1972, from BCPL/B), list at least four characteristics, and name two application areas.

1.3 Structure of a C program

A C program consists of preprocessor directives, optional global declarations, function prototypes, main(), local declarations, executable statements, and user-defined function definitions.

/* 1. Preprocessor directives */
#include <stdio.h>
#include <stdlib.h>

/* 2. Global declaration */
int globalCount = 0;

/* 3. Function prototype */
int add(int a, int b);

/* 4. main — program entry point */
int main(void) {
    /* 5. Local declarations */
    int x = 10, y = 20;
    int result;

    /* 6. Executable statements */
    result = add(x, y);
    printf("Sum = %d\n", result);

    return 0; /* 7. Return status to the operating system */
}

/* 8. User-defined function definition */
int add(int a, int b) {
    return a + b;
}

Section-by-section:

  1. #include <stdio.h> copies the standard input/output header into the source before compilation.
  2. Global declarations are visible to every function in the file; use them sparingly.
  3. A prototype tells the compiler a function's return type, name, and parameter types before its definition.
  4. main() is where execution begins; it returns int to the OS.
  5. Local variables live in the block where they are declared. 6–7. Executable statements do the work; return 0 reports success to the OS.
  6. A function defined after main() needs its prototype declared earlier.

Self-check: What does return 0 in main() communicate to the operating system? Answer: It reports successful program execution (0 = success).

Exam pointers: Draw/label the sections of a C program; state the role of the prototype, main(), and return 0.

1.4 Compilation and execution process

flowchart LR
    A[Source file hello.c] -->|Preprocessor cpp| B[Expanded source hello.i]
    B -->|Compiler cc1| C[Assembly code hello.s]
    C -->|Assembler as| D[Object file hello.o]
    D -->|Linker ld| E[Executable hello.exe]
    F[Library files libc] --> E

Stages:

  1. Preprocessor: expands #include, #define, and conditional directives; removes comments. Output: .i file.
  2. Compiler: translates preprocessed source into assembly; performs syntax and semantic checks. Output: .s file.
  3. Assembler: converts assembly into machine code in an object file. Output: .o file.
  4. Linker: combines object files and resolves library function calls into a single executable.
  5. Loader: the OS loads the executable into memory and starts execution at main().

GCC commands: gcc hello.c -o hello (all stages); gcc -E hello.c -o hello.i (preprocess only); gcc -S hello.c -o hello.s (compile to assembly); gcc -c hello.c -o hello.o (assemble); gcc hello.o -o hello (link only).

Self-check: Which tool converts assembly code (.s) into an object file (.o)? Answer: The assembler.

Exam pointers: List the five stages in order with their input/output files; give the gcc flag for each individual stage.

1.5 C tokens

A token is the smallest meaningful unit the compiler recognizes. C has six categories:

Token Meaning Examples
Keywords Reserved words with fixed meaning int, if, for, return, void
Identifiers User-defined names main, sum, studentName
Constants Fixed literal values 42, 3.14, 'A', "hello"
String literals Null-terminated character sequences "BCA Nepal"
Operators Symbols that perform operations +, -, *, &&, ?:
Special characters Punctuation with syntactic meaning {, }, ;, ,, (, )

Identifier rules: begin with a letter or _; continue with letters, digits, _; case-sensitive; cannot be a keyword; C89 guarantees significance of the first 31 characters. studentName and StudentName are different identifiers.

Self-check: Classify each: while, x1, 3.14, &, ;. Answer: while keyword; x1 identifier; 3.14 constant; & operator; ; special character.

Exam pointers: List the six token categories with one example each; state identifier naming rules and case sensitivity.

1.6 Variables: declaration, initialization, scope, and lifetime

int age;            /* declared only; holds garbage until assigned */
int marks = 85;     /* declared and initialized */

Scope is the region where a variable is visible:

  • Local (block scope): declared inside {}; visible only within that block.
  • Global (file scope): declared outside all functions; visible throughout the file.
  • Function scope: applies to labels used with goto.

Lifetime (storage duration):

  • Automatic (auto): default for locals; created on block entry, destroyed on exit.
  • Static (static): created once at program start; retains its value between calls.
  • External (extern): shares a global variable across multiple source files.
  • Register (register): hints the compiler to keep the variable in a CPU register; usually ignored by modern compilers.
#include <stdio.h>
void counter(void) {
    static int count = 0;   /* initialized only once */
    count++;
    printf("Count = %d\n", count);
}
int main(void) {
    counter(); /* Count = 1 */
    counter(); /* Count = 2 */
    counter(); /* Count = 3 */
    return 0;
}

Self-check: What is the difference between scope and lifetime? Answer: Scope is where a name is visible; lifetime is how long the storage exists during program execution.

Exam pointers: Contrast local vs global scope; contrast automatic vs static lifetime; show output of a static-counter program.

1.7 Data types

Basic types (typical sizes on a 32/64-bit GCC system):

Type Typical size Range Format specifier
char 1 byte −128 to 127 (signed) %c, %d
unsigned char 1 byte 0 to 255 %u
int 4 bytes −2,147,483,648 to 2,147,483,647 %d
unsigned int 4 bytes 0 to 4,294,967,295 %u
short int 2 bytes −32,768 to 32,767 %hd
long int 4 or 8 bytes system-dependent %ld
long long int 8 bytes about ±9.2 × 10¹⁸ %lld
float 4 bytes ~6–7 significant digits %f
double 8 bytes ~15–16 significant digits %lf
long double 10/12/16 bytes system-dependent %Lf
void 0 no value —

Swipe to see all columns

Derived types: arrays, pointers, functions. User-defined types: structures, unions, enumerations, typedef aliases.

Use case: use float/double for measurements (height, weight), int for counts, char for single characters, void for functions that return nothing.

Self-check: Which format specifier prints a double with printf? Answer: %lf.

Exam pointers: Write a table of basic types with sizes, ranges, and format specifiers; distinguish basic, derived, and user-defined types.

1.8 Type casting

Implicit conversion: the compiler automatically converts a smaller type to a larger one in an expression (integer promotion, usual arithmetic conversions). Widening does not lose data.

Explicit conversion (cast): the programmer forces a conversion with (type)expression.

int a = 7, b = 2;
double result;

result = a / b;            /* integer division: 3, stored as 3.0 */
printf("%f\n", result);    /* 3.000000 */

result = (double)a / b;    /* cast a to double first: 3.5 */
printf("%f\n", result);    /* 3.500000 */

Narrowing risk: casting a large int to char keeps only the low 8 bits; casting double to int truncates the fractional part (it does not round).

Self-check: What is (double)7 / 2, and what is 7 / 2 stored in a double? Answer: 3.5; 3.0 (integer division happens first, then conversion).

Exam pointers: Show code demonstrating implicit vs explicit casting; explain the truncation risk of narrowing casts.

1.9 Operators and expressions: precedence and associativity

Operator categories:

Category Operators Example
Arithmetic +, -, *, /, % 7 % 3 → 1
Relational ==, !=, <, >, <=, >= 5 > 3 → 1 (true)
Logical &&, `
Bitwise &, ` , ^, ~, <<, >>`
Assignment =, +=, -=, *=, /=, %= x += 5
Increment/decrement ++, -- (prefix/postfix) i++
Conditional (ternary) condition ? e1 : e2 max = a > b ? a : b
Special sizeof, ,, & (address-of), * (dereference) sizeof(int) → 4

Precedence (high → low, simplified): parentheses → unary (!, ~, ++, -- prefix, sizeof, &, *) → multiplicative (*, /, %) → additive (+, -) → shift → relational → equality → bitwise AND & → bitwise XOR ^ → bitwise OR | → logical AND && → logical OR || → conditional ?: → assignment → comma. Operators at the same level associate left to right, except unary and assignment (right to left).

Prefix vs postfix:

int a = 5;
int b = ++a;   /* a becomes 6, then b = 6 */
int c = a++;   /* c = 6, then a becomes 7 */

Comparison of increment forms: prefix returns the updated value; postfix returns the value before updating.

Self-check: Evaluate int a = 3, b = 4; a++ + ++b; Answer: a++ yields 3 then a = 4; ++b makes b = 5 and yields 5; result 3 + 5 = 8; final a = 4, b = 5.

Exam pointers: State precedence order; predict output of prefix/postfix expressions; explain associativity.

Key terms — Unit 1

Token · keyword · identifier · constant · operator · scope · lifetime · storage class · implicit/explicit cast · operator precedence · associativity · object file · preprocessor · linker

Unit 1 summary

This unit covered how programming languages evolved, where C fits (3GL systems language from Bell Labs), the sections of a C program, the five-stage compilation pipeline, tokens, variables and their scope/lifetime, basic and derived data types, implicit and explicit casting, and operators with precedence. Every later unit builds on these basics: tokens form expressions, expressions drive control flow, and variables hold the data that programs manipulate.

Expanded chapter notes

Computer hardware understands only electrical states, represented mathematically as ones and zeros. Human beings understand language, logic, and abstract mathematics. A programming language is the necessary bridge between these two realities, and few languages have served as that bridge as effectively or as enduringly as C. When you write a program in C, you are not merely giving instructions to a machine; you are managing its resources. Unlike higher-level languages that hide the physical reality of the computer behind layers of abstraction, C forces the programmer to confront memory allocation, data representation, and the sequential execution of instructions. This unit establishes the foundational architecture of the C language. It traces how source code is written, how the compiler breaks that text down into recognizable tokens, and how those tokens are translated into executable machine code. By understanding the primitive data types, the rules of variable scope, and the precise mechanics of operators, you build the vocabulary necessary to control the hardware directly.

1.1 Evolution of programming languages

To understand why C was created and why it operates the way it does, one must trace the evolution of how humans have communicated with computing hardware. The history of programming languages is a trajectory of increasing abstraction, moving from hardware-specific binary codes to human-readable syntax.

Machine-Level Languages (First Generation)

At the lowest level, a central processing unit (CPU) only executes machine code: raw binary instructions specific to its architecture. In the earliest days of computing, programmers wrote software directly in machine language. Every instruction, memory address, and data point was manually encoded as a sequence of bits. If a programmer wanted to add two numbers, they had to know the exact binary opcode for the "ADD" hardware instruction on that specific processor, as well as the binary addresses of the hardware registers involved. Writing in machine language was excruciatingly slow and highly prone to error. Furthermore, machine code is strictly tied to the hardware architecture. A program written in machine code for an Intel processor is entirely incomprehensible to an ARM processor. This lack of portability meant that software had to be completely rewritten from scratch for every new machine.

Unit 2: Input/Output and Control Structures

Teaching hours: 11

2.1 Standard input and output functions

C programs interact with the user through standard input (keyboard) and standard output (screen). The <stdio.h> library provides formatted functions (printf, scanf) and unformatted character/string functions (getchar, putchar, gets, puts, and the non-standard getch, getche, putch from <conio.h>). Output goes to stdout (diagnostics to stderr); input is read from stdin; reading functions wait for input until the buffer or terminating character arrives.

Self-check: Which header declares printf and scanf? Answer: <stdio.h>.

Exam pointers: State the role of standard input/output and name the header that declares the I/O functions.

2.1.1 Formatted I/O: printf() and scanf()

printf(format_string, ...) writes formatted data to standard output. scanf(format_string, ...) reads formatted data from standard input and stores it in variables; the & address-of operator is required before each variable so scanf can store at its address.

int roll = 101;
float gpa = 3.75;
printf("Roll: %d, GPA: %.2f\n", roll, gpa);
scanf("%d %f", &roll, &gpa);

Common format specifiers: %d int, %f float, %lf double, %c char, %s string, %ld long, %u unsigned, %x hexadecimal, %o octal, %e scientific notation.

Width and precision modifiers:

printf("%8d", 42);     /* right-aligned: "      42" */
printf("%-8d", 42);    /* left-aligned:  "42      " */
printf("%08d", 42);    /* zero-padded:   "00000042" */
printf("%.2f", 3.14159); /* two decimals: "3.14" */
printf("%10.3f", 3.1);   /* width 10, 3 decimals */

Pitfall: scanf("%s", name) stops at whitespace, so it cannot read a name with spaces; use fgets(name, sizeof(name), stdin) for full lines. name needs no & because an array name already decays to a pointer.

Worked example — reading and printing student data:

#include <stdio.h>
int main(void) {
    int roll;
    char name[50];
    float marks;
    printf("Enter roll, name, marks: ");
    scanf("%d", &roll);
    scanf(" %[^\n]%*c", name);   /* read a line with spaces */
    scanf("%f", &marks);
    printf("Roll = %d\nName = %s\nMarks = %.2f\n", roll, name, marks);
    return 0;
}
/* Input:
   101
   Sita Sharma
   87.5
   Output:
   Roll = 101
   Name = Sita Sharma
   Marks = 87.50 */

Self-check: Why does scanf need & before an integer variable but printf does not? Answer: scanf must store a value at the variable's address, so it needs the address; printf only reads the value.

Exam pointers: Write printf/scanf with format specifiers and width/precision modifiers; state the scanf("%s") whitespace limitation and its remedy.

2.1.2 Unformatted I/O functions

Unformatted I/O reads or writes single characters or strings without format specifiers:

Function Header Action
getchar() <stdio.h> Read one character from stdin (waits for Enter)
putchar(c) <stdio.h> Write one character to stdout
getch() <conio.h> Read one character without echo; no Enter needed
getche() <conio.h> Like getch() but echoes the character
putch(c) <conio.h> Write one character (Turbo C)
gets(s) <stdio.h> Read a whole line; deprecated — buffer overflow risk
puts(s) <stdio.h> Write a string followed by a newline

Note: getch(), getche(), and putch() are non-standard Turbo C functions in <conio.h>; on Linux/GCC use getchar() and putchar(). gets() is unsafe because it does not limit input length — prefer fgets().

#include <stdio.h>
int main(void) {
    char ch;
    printf("Press any key: ");
    ch = getchar();
    putchar(ch);
    putchar('\n');
    return 0;
}

Self-check: Name one risk of using gets() and its safer replacement. Answer: Buffer overflow (no length limit); use fgets(s, size, stdin).

Exam pointers: List unformatted I/O functions with headers; state which are non-standard and why gets() is deprecated.

2.2 Control structures

Control structures change the normal sequential flow of execution. Three categories:

  • Selection (branching): if, if-else, nested if-else, else-if ladder, switch, conditional operator ?:.
  • Iteration (looping): while, do-while, for, nested loops.
  • Jump: break, continue, goto.

Self-check: Name one statement from each control-structure category. Answer: if (selection), for (iteration), break (jump).

Exam pointers: List the three categories and one example statement from each.

2.3 Decision making statements

Decision statements choose among alternative actions based on a condition. C evaluates any non-zero value as true and zero as false.

2.3.1 if statement

The if statement executes its body only when the condition is true.

if (marks >= 40) {
    printf("Pass\n");
}

If the condition is false, the body is skipped and execution continues after the if.

Self-check: Does the body of if (0) printf("x"); run? Answer: No — condition 0 is false, so the body is skipped.

Exam pointers: Write an if statement and state its execution rule.

2.3.2 if-else statement

if-else provides two alternative bodies: one for true, one for false.

if (age >= 18) {
    printf("Eligible to vote\n");
} else {
    printf("Not eligible\n");
}

Exactly one of the two bodies executes.

Self-check: For age = 16, which branch of the example runs? Answer: The else branch ("Not eligible").

Exam pointers: Contrast if vs if-else; state how many bodies execute.

2.3.3 Nested if-else statement

A nested if-else places an if or else inside another if or else body, allowing multi-level decisions.

if (marks >= 50) {
    if (attendance >= 75) {
        printf("Allowed to appear in exam\n");
    } else {
        printf("Debarred due to attendance\n");
    }
} else {
    printf("Failed internally\n");
}

Dangling-else problem: in if (a) if (b) S1; else S2; the else binds to the nearest unmatched if (if (b)). Braces remove the ambiguity.

Self-check: To which if does an else belong when it follows nested ifs without braces? Answer: To the nearest unmatched if (dangling-else rule).

Exam pointers: Show nested if-else code; explain the dangling-else problem and the brace fix.

2.3.4 else-if ladder

An else-if ladder checks conditions in order and executes the first body whose condition is true; the final else is the default.

if (marks >= 90) printf("Grade A\n");
else if (marks >= 80) printf("Grade B\n");
else if (marks >= 70) printf("Grade C\n");
else printf("Grade D or below\n");

Only one branch runs; order matters because earlier conditions take priority.

Self-check: For marks = 85, which branch runs in the ladder above? Answer: else if (marks >= 80) → "Grade B".

Exam pointers: Write an else-if ladder for grading; state that only the first true branch executes and order matters.

2.3.5 switch statement

switch selects among multiple discrete constant values:

switch (expression) {
    case constant1:
        statements;
        break;
    case constant2:
        statements;
        break;
    default:
        statements;
}

The expression must be integral (int, char, enum). Without break, execution falls through into the next case.

switch vs else-if: switch is cleaner for many discrete constants; else-if handles ranges and non-integral conditions.

Worked example — menu:

#include <stdio.h>
int main(void) {
    int choice;
    printf("1. Check balance  2. Withdraw  3. Exit\nChoice: ");
    scanf("%d", &choice);
    switch (choice) {
        case 1: printf("Balance: Rs 5000\n"); break;
        case 2: printf("Withdrawal processed\n"); break;
        case 3: printf("Goodbye\n"); break;
        default: printf("Invalid choice\n");
    }
    return 0;
}

Pitfall: forgetting break causes fall-through — execution continues into subsequent cases, usually a bug, occasionally intentional.

Self-check: What happens if break is omitted in a matching case? Answer: Fall-through: execution continues into the next case body.

Exam pointers: Write a switch menu program; state the fall-through rule and the default role.

2.3.6 Conditional operator (?:)

The ternary operator is a compact if-else expression:

int max = (a > b) ? a : b;

It evaluates the condition; if true, yields a, otherwise b. Useful for short assignments; avoid nesting ternaries, which hurts readability.

Self-check: Rewrite if (a > b) max = a; else max = b; using ?:. Answer: max = (a > b) ? a : b;

Exam pointers: State the syntax of ?:; give an example and its if-else equivalent.

2.4 Looping statements

Loops repeat a body while (or until) a condition holds. while and for are pre-test (condition first); do-while is post-test (body first).

Self-check: Which loop guarantees at least one execution of its body? Answer: do-while.

Exam pointers: Name the three loop types and their test position.

2.4.1 while loop

while is a pre-test loop: the condition is checked before every iteration, so the body may run zero times.

/* Print 1 to 5 */
int i = 1;
while (i <= 5) {
    printf("%d ", i);
    i++;
}
/* Output: 1 2 3 4 5 */

Self-check: How many times does the body run if the condition is false initially? Answer: Zero times (pre-test loop).

Exam pointers: Write a while loop; state when the body may never execute.

2.4.2 do-while loop

do-while is a post-test loop: the body runs at least once, then the condition is checked.

int choice;
do {
    printf("1. Continue  2. Exit\nChoice: ");
    scanf("%d", &choice);
} while (choice != 2);

Use case: menu-driven programs where the menu must display at least once.

Self-check: How many times does a do-while body execute at minimum? Answer: Once.

Exam pointers: Contrast while vs do-while with an example where output differs.

2.4.3 for loop

for suits known iteration counts:

for (initialization; condition; update) {
    body;
}

All three parts are optional; for (;;) is an infinite loop.

/* Sum 1 to n */
int n, sum = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++) sum += i;
/* n = 5 → sum = 15 */

Self-check: Write the three parts of a for loop in order. Answer: Initialization; condition; update.

Exam pointers: Write a for loop to sum 1 to n; state output for n = 5.

2.4.4 Nested loops

A loop inside another loop is a nested loop; the inner loop completes all its iterations for each outer iteration.

/* Multiplication table 1x1 to 3x3 */
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        printf("%3d", i * j);
    }
    printf("\n");
}
/* Output:
    1  2  3
    2  4  6
    3  6  9 */

Two loops of size n each give O(n²) iterations.

Self-check: How many times does the innermost statement run in two nested loops of size 3 each? Answer: 9 times.

Exam pointers: Trace a nested loop; state its output and iteration count.

2.5 Jump statements

Jump statements transfer control unconditionally: break exits a loop/switch, continue skips to the next iteration, goto jumps to a label.

2.5.1 break statement

break exits the innermost enclosing for, while, do-while, or switch; execution resumes after it.

for (int i = 0; i < 10; i++) {
    if (i == 5) break;
    printf("%d ", i);
}
/* Output: 0 1 2 3 4 */

Self-check: What does break exit — the innermost loop or all loops? Answer: The innermost enclosing loop or switch only.

Exam pointers: Trace a loop with break; state its scope.

2.5.2 continue statement

continue skips the rest of the current iteration and jumps to the loop's update/test.

for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) continue;
    printf("%d ", i);
}
/* Output: 1 3 5 7 9 */

Self-check: For i = 4 in the example above, what happens? Answer: 4 % 2 == 0, so continue skips the printf for that iteration.

Exam pointers: Contrast break (exit loop) vs continue (skip iteration).

2.5.3 goto statement

goto performs an unconditional jump to a labelled statement:

int i = 0;
start:
    printf("%d ", i++);
    if (i < 5) goto start;
/* Output: 0 1 2 3 4 */

Avoid goto in structured code: it obscures flow and can jump past initializations. One accepted use is breaking out of deeply nested loops.

Self-check: Name one reason goto is discouraged in structured programming. Answer: It makes control flow difficult to follow and reason about.

Exam pointers: Show goto usage; state why it is generally avoided and one legitimate exception.

Key terms — Unit 2

Format specifier · width/precision modifier · address-of operator & · fall-through · dangling-else · pre-test vs post-test · break vs continue · goto label

Unit 2 summary

This unit covered formatted and unformatted I/O (printf, scanf, getchar, putchar, gets/puts, fgets), then all control structures: if, if-else, nested if-else, else-if ladder, switch (with fall-through and default), the ternary operator, while, do-while, for, nested loops, and jump statements break, continue, goto. Each loop was contrasted on test position and minimum iterations, and every topic includes worked code you can compile and trace.

Expanded chapter notes

A computer program that only executes a fixed sequence of instructions without interacting with the outside world is of limited use. To solve real problems, programs must ingest data, evaluate conditions, and repeat operations based on dynamic states. This unit introduces the two pillars of dynamic programming in C: Input/Output (I/O) operations and Control Structures. I/O functions allow a program to communicate with the user, reading keystrokes and displaying formatted results. Control structures break the default top-to-bottom execution flow of a program. By evaluating logical conditions, control structures allow the processor to branch into different execution paths, skip instructions, or repeat blocks of code thousands of times in a fraction of a second. Together, these tools transform a static script into an interactive, decision-making application.

2.1 Standard Input and Output Functions

In C, input and output are not built directly into the language keywords. Instead, they are handled by standard library functions, primarily defined in the <stdio.h> (Standard Input/Output) header file. These functions treat I/O as a stream of bytes moving between the program and external devices (like the keyboard and monitor).

2.1.1 Formatted I/O: printf() and scanf()

Formatted I/O functions allow the programmer to dictate exactly how data should be interpreted and displayed. They rely on format specifiers (like %d for integers, %f for floats, and %c for characters) to translate raw binary data in memory into human-readable text, and vice versa.

Unit 3: Functions, Arrays and Strings

Teaching hours: 11

3.1 Functions

A function is a named, reusable block of code that performs one task. Benefits: modularity, reuse, easier testing and debugging.

3.1.1 Introduction to functions: advantages, function definition, function declaration/prototype

A definition provides the body; a prototype (declaration) tells the compiler the return type, name, and parameter types before the definition appears.

/* Prototype */
int factorial(int n);

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

Parts: return type, function name, parameter list (formal parameters), body. Advantages: avoid repeating code, divide a program into testable units, enable team development.

Self-check: What must a prototype tell the compiler? Answer: Return type, name, and parameter types.

Exam pointers: State the parts of a function definition and the purpose of a prototype.

3.1.2 Function call

Calling a function transfers control to it: arguments are passed, the body executes, a value may be returned, and control resumes after the call.

int result = factorial(5);   /* 5 is the actual argument */
printf("%d\n", result);      /* 120 */

Self-check: What is the actual argument in factorial(5)? Answer: 5.

Exam pointers: Describe the five steps of a function call; distinguish actual vs formal arguments.

3.1.3 Types of functions: library functions vs. user-defined functions

Library functions User-defined functions
Pre-written in the standard library Written by the programmer
Declared in headers (<math.h>, <string.h>) Prototyped in the same or another file
Examples: printf, sqrt, strlen Examples: factorial, add

Self-check: Is strlen a library function or user-defined function? Answer: Library function (declared in <string.h>).

Exam pointers: Compare library vs user-defined functions with examples.

3.1.4 Function arguments: call by value, call by reference

Call by value: a copy of the argument is passed; changes inside the function do not affect the original.

void doubleIt(int x) {
    x = x * 2;
}
int main(void) {
    int a = 5;
    doubleIt(a);
    printf("%d\n", a);   /* 5 — unchanged */
    return 0;
}

Call by reference: pass the address via a pointer; changes through the pointer affect the original.

void doubleIt(int *x) {
    *x = *x * 2;
}
int main(void) {
    int a = 5;
    doubleIt(&a);
    printf("%d\n", a);   /* 10 — changed */
    return 0;
}

Worked example — swap by reference:

#include <stdio.h>
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}
int main(void) {
    int x = 10, y = 20;
    swap(&x, &y);
    printf("x = %d, y = %d\n", x, y);  /* x = 20, y = 10 */
    return 0;
}

Self-check: After call by value, is the original variable changed? Answer: No — only a copy is modified.

Exam pointers: Contrast call by value vs call by reference with code and output; show pointer-based swap.

3.1.5 Recursion: concepts and examples

Recursion is a function calling itself. It needs a base case (stops) and a recursive case (moves toward the base case).

Traced example — factorial(3):

factorial(3) → 3 × factorial(2)
              → 2 × factorial(1)
                   → 1 × factorial(0)
                         → 1      (base case)
                   ← 1 × 1 = 1
              ← 2 × 1 = 2
   ← 3 × 2 = 6
int fib(int n) {
    if (n <= 1) return n;
    return fib(n - 1) + fib(n - 2);
}

Naive recursive Fibonacci is O(2ⁿ); an iterative version is O(n). Deep recursion without a base case overflows the call stack.

Self-check: What two parts must every recursive function have? Answer: A base case and a recursive case.

Exam pointers: Trace factorial recursion; state base/recursive case; contrast recursive vs iterative Fibonacci complexity.

3.2 Arrays

An array is a contiguous block of memory holding a fixed number of same-type elements, indexed from 0.

3.2.1 Introduction to arrays: declaration, initialization, accessing elements

int marks[5];                    /* 5 ints, uninitialized */
int scores[5] = {90, 85, 78, 92, 88};
int grades[] = {70, 65, 80};     /* size inferred as 3 */
printf("%d\n", scores[0]);       /* 90 */

Elements occupy consecutive addresses; scores[1] sits at base + sizeof(int). The array name decays to a pointer to the first element.

Self-check: What is the index of the first element of a C array? Answer: 0.

Exam pointers: Declare and initialize arrays; state that indexing starts at 0.

3.2.2 One-dimensional arrays: processing and examples

Loops process every element:

/* Average of n integers */
#include <stdio.h>
#define MAX 100
int main(void) {
    int n, arr[MAX];
    double sum = 0;
    printf("How many numbers? ");
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
        sum += arr[i];
    }
    printf("Average = %.2f\n", sum / n);
    return 0;
}
/* Input: 3, 10 20 30 → Average = 20.00 */

Self-check: What index range is valid for arr[MAX]? Answer: 0 to MAX−1.

Exam pointers: Write a loop to read n numbers into an array and compute their average.

3.2.3 Two-dimensional arrays: declaration, initialization, accessing elements (matrix operations)

int mat[2][3] = {{1, 2, 3}, {4, 5, 6}};
printf("%d\n", mat[1][2]);  /* 6 */

/* Matrix addition */
for (int i = 0; i < R; i++)
    for (int j = 0; j < C; j++)
        result[i][j] = A[i][j] + B[i][j];

Matrix multiplication needs three nested loops: result[i][j] += A[i][k] * B[k][j].

Worked example — matrix addition:

#include <stdio.h>
int main(void) {
    int A[2][2] = {{1, 2}, {3, 4}};
    int B[2][2] = {{5, 6}, {7, 8}};
    int C[2][2];
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            C[i][j] = A[i][j] + B[i][j];
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) printf("%d ", C[i][j]);
        printf("\n");
    }
    return 0;
}
/* Output:
   6 8
   10 12 */

Self-check: What does mat[1][2] access in a 2×3 array? Answer: Row 1, column 2 (second row, third column).

Exam pointers: Show 2D array declaration, access, addition, and multiplication loop structure.

3.2.4 Multi-dimensional arrays

Declared as type name[d1][d2][d3]...; stored in row-major order (last index varies fastest). BCA exams mainly use 2D arrays.

Self-check: In row-major order, which index varies fastest? Answer: The last (rightmost) index.

Exam pointers: State declaration syntax and row-major storage.

3.2.5 Arrays and functions

An array name decays to a pointer to its first element when passed to a function; C does not pass the size, so pass it explicitly.

int sumArray(int arr[], int n) {  /* same as int *arr */
    int s = 0;
    for (int i = 0; i < n; i++) s += arr[i];
    return s;
}

Changes to elements inside the function affect the original array because only the address is passed — effectively pass by reference for the elements.

Self-check: Does changing an array element inside a function affect the original array? Answer: Yes — the function receives the array's address.

Exam pointers: Write a function that takes an array and its size; explain element mutation visibility.

3.3 Strings

A C string is a null-terminated character array; \0 marks the end.

3.3.1 Introduction to strings: declaration, initialization

char name[20];                      /* uninitialized */
char name[20] = "BCA Nepal";        /* "BCA Nepal\0" + unused bytes */
char name[] = "BCA Nepal";          /* size 10: 9 chars + '\0' */
char name[] = {'B','C','A','\0'};   /* explicit */

Common mistake: char name[9] = "BCA Nepal" is too small — needs at least 10 bytes (9 characters + \0).

Self-check: How many bytes does char s[] = "BCA" occupy? Answer: 4 (B, C, A, \0).

Exam pointers: Declare strings; state the role of \0; size a buffer correctly.

3.3.2 String input/output (gets, puts)

char str[50];
scanf("%s", str);      /* reads until whitespace; no & needed */
printf("%s\n", str);
gets(str);             /* reads a whole line — UNSAFE, deprecated */
fgets(str, sizeof(str), stdin);  /* safer: limits to size−1 chars */
puts(str);             /* prints str plus newline */

Self-check: Why does scanf("%s", str) not need & before str? Answer: An array name already decays to a pointer to its first element.

Exam pointers: Contrast scanf("%s"), gets, and fgets; state why gets() is unsafe.

3.3.3 String handling functions (strlen, strrev, strcpy, strupr, strlwr, strcmp, strcat)

All declared in <string.h>; strupr, strlwr, strrev are non-standard (Turbo C).

Function Prototype Purpose Example result
strlen size_t strlen(const char *s) length excluding \0 strlen("BCA") → 3
strcpy char *strcpy(char *d, const char *s) copy src to dest strcpy(a, "Hi")
strcat char *strcat(char *d, const char *s) append src to dest strcat("Hi","!") → "Hi!"
strcmp int strcmp(const char *a, const char *b) compare strings "abc" vs "abd" → negative
strupr char *strupr(char *s) uppercase (non-standard) "hi" → "HI"
strlwr char *strlwr(char *s) lowercase (non-standard) "HI" → "hi"
strrev char *strrev(char *s) reverse (non-standard) "abc" → "cba"

Swipe to see all columns

Worked example — palindrome check:

#include <stdio.h>
#include <string.h>
int main(void) {
    char str[100], rev[100];
    printf("Enter string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';
    strcpy(rev, str);
    int n = strlen(rev);
    for (int i = 0, j = n - 1; i < j; i++, j--) {
        char t = rev[i]; rev[i] = rev[j]; rev[j] = t;
    }
    if (strcmp(str, rev) == 0) printf("Palindrome\n");
    else printf("Not a palindrome\n");
    return 0;
}
/* "madam" → Palindrome; "hello" → Not a palindrome */

Self-check: When does strcmp return 0? Answer: When the two strings are identical.

Exam pointers: Give signature, purpose, and example result for each listed function; write a palindrome program.

3.3.4 Array of strings

char subjects[3][30] = {"Digital Logic", "Programming in C", "Mathematics I"};
for (int i = 0; i < 3; i++)
    printf("%s\n", subjects[i]);

Each row is a fixed-length buffer. For variable-length strings, use char * arrays or dynamic allocation.

Self-check: In subjects[3][30], what does 30 represent? Answer: Maximum characters per string (row length).

Exam pointers: Declare an array of strings and print each row; state the limitation of fixed row length.

Key terms — Unit 3

Function · prototype · actual vs formal argument · call by value · call by reference · base case · recursion · array decay · row-major order · null terminator · buffer overflow

Unit 3 summary

This unit covered functions (definition, prototype, call, library vs user-defined, call by value vs call by reference via pointers, recursion with base cases and traced factorial), arrays (1D processing, 2D matrix addition/multiplication, row-major order, passing arrays to functions), and strings (null termination, declaration, I/O with scanf/puts/fgets, <string.h> functions with a palindrome worked example, arrays of strings). Complete, compilable examples accompany each topic.

Expanded chapter notes

As programs grow in complexity, writing all instructions in a single, continuous block inside the main() function becomes unsustainable. The code becomes difficult to read, impossible to test in isolation, and highly repetitive. To build sophisticated software, programmers must organize code into isolated, reusable blocks, and they must organize data into structured collections. This unit introduces the mechanisms for achieving both. Functions allow programmers to encapsulate logic into independent modules that can be executed on demand. Arrays provide a way to group related variables under a single identifier, mapping them to contiguous blocks of memory. Strings, which are simply arrays of characters, allow C programs to process human-readable text. Together, these three constructs form the basis of structured programming, allowing developers to manipulate large datasets efficiently without duplicating code.

3.1 Functions

A function is a self-contained block of code designed to perform a specific, well-defined task. Instead of writing the same sequence of statements multiple times, a programmer writes the sequence once inside a function, and then instructs the program to execute that function whenever the task is needed.

3.1.1 Introduction to functions: Advantages, function definition, function declaration/prototype

The shift from monolithic programming to functional programming provides structural benefits that dictate how all modern software is written.

Unit 4: Structures, Unions, and Enumerations

Teaching hours: 5

4.1 Structures and unions

Structures group variables of different types under one name; each variable is a member.

struct Student {
    int   rollNo;
    char  name[50];
    float gpa;
};

struct Student s1;
struct Student s2 = {1, "Sita Sharma", 3.75};
s1.rollNo = 2;
strcpy(s1.name, "Ram Bahadur");
s1.gpa = 3.50;
printf("%s — GPA: %.2f\n", s1.name, s1.gpa);

Access members with the dot . operator.

Nested structures:

struct Date { int day, month, year; };
struct Person {
    char name[50];
    struct Date dob;
};
struct Person p = {"Hari", {15, 8, 2003}};
printf("%d/%d/%d\n", p.dob.day, p.dob.month, p.dob.year);

Array of structures:

struct Student batch[30];
scanf("%d %s %f", &batch[i].rollNo, batch[i].name, &batch[i].gpa);

Passing structures to functions: by value passes a copy; by pointer uses the arrow -> operator (ptr->m equals (*ptr).m):

void printStudent(struct Student s) {
    printf("%d %s %.2f\n", s.rollNo, s.name, s.gpa);
}
void updateGPA(struct Student *s, float g) {
    s->gpa = g;
}

sizeof and padding: a structure may be larger than the sum of its members because the compiler inserts padding bytes for alignment.

Unions allocate memory equal to their largest member; all members share the same storage, so only the last-written member holds meaningful data:

union Data {
    int   i;
    float f;
    char  c;
};
union Data d;
d.i = 65;         /* d.f and d.c now read as garbage */
d.c = 'A';
printf("%c\n", d.c);   /* 'A' */

Structure vs union:

Feature Structure Union
Memory Sum of members (+ padding) Size of largest member
Members active All simultaneously Last written one only
Typical use Records with many active fields Variant records, saving memory

Worked example — employee record: store id, name, salary in a structure; read 5 employees; print the highest-paid.

Self-check: In a union, how many members can hold valid data at the same time? Answer: Only the most recently written member.

Exam pointers: Define a structure; use . and ->; contrast structure vs union on memory and validity; show nested structure access.

4.2 Enumerations (enums) and typedef implementation

enum names integer constants:

enum Direction { NORTH, EAST, SOUTH, WEST };
enum Direction dir = NORTH;   /* 0 */

enum Weekday { MON = 1, TUE, WED, THU, FRI, SAT, SUN };
printf("%d\n", WED);  /* 3 */

Unnamed enum constants start at 0 and increment by 1 unless explicitly assigned.

typedef creates type aliases:

typedef unsigned int uint;
typedef struct Student { int roll; char name[50]; } Student;

uint x = 100;
Student s1;   /* no "struct" keyword needed */

Use case: typedef simplifies repeated struct Student declarations; enum improves readability of state codes.

Self-check: What value does WED have in enum Weekday { MON=1, TUE, WED, ... }? Answer: 3.

Exam pointers: Declare an enum and print a constant's value; use typedef for a struct alias; state the benefit of each.

Key terms — Unit 4

Member · dot operator · arrow operator · padding · alignment · variant record · type alias · enumeration constant

Unit 4 summary

Structures bundle heterogeneous data under one name with dot/arrow member access, support nesting and arrays, and can be passed to functions by value or pointer; unions share one storage area among members so only the last-written member is valid; enumerations name integer constants; typedef creates readable aliases. A comparison table distinguishes structure from union on memory layout and use case.

Expanded chapter notes

Standard data types like integers, floats, and characters represent single, isolated pieces of information. Arrays allow programmers to group multiple pieces of information together, but with a strict limitation: every element in an array must be of the exact same data type. In real-world software engineering, data is rarely homogeneous. A student record consists of a name (string), a roll number (integer), and a GPA (float). Storing these in separate, disconnected variables or arrays creates fragile, unreadable code. This unit introduces user-defined data types. By utilizing structures, unions, and enumerations, programmers can design custom data architectures that mirror real-world entities. These constructs allow the compiler to bundle different data types under a single identifier, manage shared memory spaces for extreme hardware efficiency, and assign readable vocabulary to raw numerical states.

4.1 Structures and Unions

Structures and unions are both composite data types that group variables of different types together. However, they handle computer memory in fundamentally different ways. A structure allocates separate memory for every single one of its members, while a union forces all of its members to share the exact same memory location.

Structures

A structure is a template that defines a new data type composed of multiple standard variables, known as members.

Unit 5: Pointers and Memory Management

Teaching hours: 5

5.1 Pointer declaration, initialization, and dereferencing

A pointer stores the memory address of another variable. & is address-of; * in a declaration means "pointer to"; * in an expression dereferences (reads the value at the address).

int x = 42;
int *ptr;
ptr = &x;
printf("%d\n", x);      /* 42 */
printf("%p\n", (void *)ptr);   /* address, e.g. 0x7ffee... */
printf("%d\n", *ptr);   /* 42 — value at the address */
*ptr = 100;             /* change x through the pointer */
printf("%d\n", x);      /* 100 */

Null pointer: int *p = NULL; points to address 0; dereferencing causes a segmentation fault. Always initialize pointers.

Self-check: What does *ptr do when ptr holds &x? Answer: It yields the value of x (dereference).

Exam pointers: Declare a pointer, assign an address, dereference; explain & and *; state the null-pointer risk.

5.1.2 Pointer arithmetic

Pointer arithmetic is scaled by the pointed-to type's size: p + 1 advances by sizeof(*p) bytes.

int arr[] = {10, 20, 30, 40};
int *p = arr;   /* points to arr[0] */
printf("%d\n", *p);     /* 10 */
printf("%d\n", *(p + 1)); /* 20 (advances 4 bytes for int) */
p++;
printf("%d\n", *p);     /* 20 */

On double *, p + 1 advances 8 bytes. arr[i] is equivalent to *(arr + i).

Self-check: If int *p points to address 1000, what is the value of p + 1 (assuming 4-byte int)? Answer: 1004.

Exam pointers: Show pointer arithmetic on an array; state scaling by element size; equate arr[i] with *(arr + i).

5.1.3 Pointers with arrays, string, function, structure

/* Array traversal via pointer */
int sum = 0;
for (int *p = arr; p < arr + 4; p++) sum += *p;

/* String via pointer */
char *str = "BCA Nepal";   /* string literal — do not write through it */
while (*str) putchar(*str++);

/* Pointer to structure */
struct Student s = {1, "Sita", 3.9};
struct Student *sp = &s;
printf("%s\n", sp->name);   /* arrow operator */

Pointers to functions enable call by reference (see 3.1.4).

Self-check: Is it safe to modify a string literal through char *str = "text";? Answer: No — string literals are read-only; modifying them is undefined behaviour.

Exam pointers: Traverse an array with a pointer; use -> on a struct pointer; state the read-only nature of string literals.

5.2 Dynamic memory allocation: malloc, calloc, realloc, free

Heap memory is allocated at runtime via <stdlib.h>:

Function Signature Initializes? Purpose
malloc void *malloc(size_t size) No (garbage) allocate size bytes
calloc void *calloc(size_t n, size_t size) Yes (zeros) allocate n × size bytes
realloc void *realloc(void *ptr, size_t size) — resize an allocation
free void free(void *ptr) — release memory to the heap

Swipe to see all columns

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    int n;
    printf("How many integers? ");
    scanf("%d", &n);
    int *arr = (int *)malloc(n * sizeof(int));  /* cast optional in C99+ */
    if (arr == NULL) {
        fprintf(stderr, "Allocation failed\n");
        return 1;
    }
    for (int i = 0; i < n; i++) arr[i] = (i + 1) * 10;
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);  /* n=4 → 10 20 30 40 */
    free(arr);
    arr = NULL;
    return 0;
}

Always check for NULL, and pair every allocation with exactly one free.

Self-check: What is the difference between malloc and calloc? Answer: malloc leaves garbage; calloc zero-initializes and takes two arguments (count, size).

Exam pointers: Write a complete malloc program with NULL check and free; contrast all four functions in a table.

5.3 DMA with structure

struct Student *sp = (struct Student *)malloc(sizeof(struct Student));
if (sp == NULL) { /* handle error */ }
sp->rollNo = 1;
strcpy(sp->name, "Nisha");
sp->gpa = 3.8;
free(sp);
sp = NULL;

For an array of structures: struct Student *batch = calloc(n, sizeof(struct Student));

Self-check: Which operator accesses a member through a structure pointer? Answer: -> (arrow operator).

Exam pointers: Allocate one structure and an array of structures dynamically; show -> member access.

5.4 Dangling pointers and memory leaks

Dangling pointer: points to freed or out-of-scope memory; dereferencing is undefined behaviour.

int *p = malloc(sizeof(int));
free(p);
*p = 5;   /* BUG: dangling pointer */

Fix: assign p = NULL immediately after free(p).

Memory leak: allocated memory never freed; the heap grows until exhausted (OS reclaims on process exit in most systems).

while (1) {
    char *buf = malloc(1024);  /* never freed: 1 KB leaks per iteration */
}

Fix: match every malloc/calloc/realloc with one free. Tools like Valgrind detect leaks.

Self-check: Name the bug: memory freed but pointer still used. Answer: Dangling pointer use.

Exam pointers: Explain dangling pointer and memory leak with code; show the p = NULL fix; mention Valgrind.

Key terms — Unit 5

Address-of & · dereference * · pointer arithmetic scaling · NULL pointer · heap · dangling pointer · memory leak · Valgrind · malloc/calloc/realloc/free

Unit 5 summary

Pointers hold addresses; & takes an address and * dereferences. Pointer arithmetic scales by the pointed-to type's size, enabling array and string traversal. Pointers work with arrays, strings, functions (call by reference), and structures (->). Dynamic memory from the heap uses malloc, calloc, realloc, and free; always check NULL and pair allocation with free to avoid dangling pointers and memory leaks. Worked examples include array traversal, structure allocation, and leak/dangling-pointer fixes.

Expanded chapter notes

In high-level programming languages, the computer's memory is hidden behind a layer of abstraction. The programmer declares a variable, and the language automatically finds a place in RAM to store it, tracks its location, and destroys it when it is no longer needed. C does not enforce this restriction. C provides direct, unfiltered access to the computer's physical memory through pointers. A pointer is not a magical construct; it is simply a variable that stores a memory address rather than a standard data value. By manipulating these addresses, a programmer can directly read and write to specific bytes of RAM, pass massive datasets to functions without copying them, and request memory from the operating system dynamically while the program is running. This level of control makes C incredibly fast and efficient, but it shifts the entire burden of memory management onto the programmer.

5.1 Pointer declaration, initialization, and dereferencing

To understand pointers, one must understand how variables are stored. When a variable int x = 10; is declared, the compiler reserves 4 bytes of memory at a specific hexadecimal address (e.g., 0x7ffeeb42). The variable name x is just an alias for that address. A pointer allows us to store and interact with 0x7ffeeb42 directly.

Pointer Declaration

A pointer is declared by placing an asterisk (*) between the data type and the variable name. The data type dictates what kind of data resides at the memory address the pointer will eventually hold. int *ptr; This declares a pointer named ptr that is designed to hold the memory address of an integer.

Unit 6: File Handling, Command-Line Arguments, and Graphics

Teaching hours: 11

6.1 File handling

Files provide persistent storage. FILE (defined in <stdio.h>) is an opaque structure holding the file descriptor, buffer, and position. Lifecycle: open → read/write → close.

6.1.2 Concepts of files (text vs. binary) and file operations (opening, closing, reading, writing)

Dimension Text file Binary file
Content Human-readable characters Raw machine representation
Line ending \n translated per platform No translation
Portability High Lower (type-size dependent)
Use cases Config, CSV, source code Images, executables, databases

A text file stores characters; a binary file stores data in the machine's internal format. Both follow open → operate → close.

Self-check: Name one advantage of text files and one of binary files. Answer: Text: human-readable and portable; binary: compact and exact for program data.

Exam pointers: Contrast text vs binary files; state the FILE role and file-operation lifecycle.

6.1.3 File modes and standard I/O functions (fgetc, fputc, fgets, fputs, fprintf, fscanf, fread, fwrite)

#include <stdio.h>
int main(void) {
    FILE *fp = fopen("data.txt", "w");
    if (fp == NULL) {
        perror("fopen");
        return 1;
    }
    fprintf(fp, "BCA Nepal\n");
    fputs("Hello\n", fp);
    fputc('X', fp);
    fclose(fp);

    fp = fopen("data.txt", "r");
    char line[100];
    while (fgets(line, sizeof(line), fp) != NULL)
        printf("%s", line);
    fclose(fp);
    return 0;
}

Modes: "r" read text (must exist), "w" write/create/truncate, "a" append/create, "r+" read+write (exists), "w+" read+write/truncate; add b for binary ("rb", "wb", "ab").

Function summary:

Function Action
fgetc(fp) read one char
fputc(c, fp) write one char
fgets(buf, n, fp) read up to n−1 chars (stops at \n/EOF)
fputs(str, fp) write a string
fscanf(fp, fmt, ...) formatted read
fprintf(fp, fmt, ...) formatted write
fread(buf, size, n, fp) read n items of size bytes
fwrite(buf, size, n, fp) write n items of size bytes
feof(fp) non-zero at end of file
ferror(fp) non-zero on error

Self-check: Which mode creates a file for writing and discards previous contents? Answer: "w".

Exam pointers: List all six file modes with behavior; name five file I/O functions and their actions; check fopen return for NULL.

6.1.4 Random access (fseek, ftell, rewind) and error handling

fseek(fp, 0, SEEK_SET);    /* start of file */
fseek(fp, 10, SEEK_CUR);   /* 10 bytes forward from current */
fseek(fp, -5, SEEK_END);   /* 5 bytes before end */
long pos = ftell(fp);      /* current byte position */
rewind(fp);                /* back to start */

whence values: SEEK_SET (start), SEEK_CUR (current position), SEEK_END (end). For record-based binary files, jump to record n with fseek(fp, n * sizeof(Record), SEEK_SET). Always test ferror after operations.

Self-check: What does ftell(fp) return? Answer: The current file position in bytes.

Exam pointers: Show fseek, ftell, rewind usage; name the three whence constants; explain random access to a binary record.

6.2 Command-line arguments

6.2.1 Introduction to main() function parameters (argc, argv)

int main(int argc, char *argv[])
  • argc: argument count, including the program name.
  • argv: array of argc C strings; argv[0] is the program name.

6.2.2 Passing and accessing arguments from the command line

$ ./myprogram 10 20 add
argc = 4
argv[0] = "./myprogram"
argv[1] = "10"
argv[2] = "20"
argv[3] = "add"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
    if (argc != 4) {
        fprintf(stderr, "Usage: %s num1 num2 op\n", argv[0]);
        return 1;
    }
    int a = atoi(argv[1]);   /* "10" → 10 */
    int b = atoi(argv[2]);   /* "20" → 20 */
    if (strcmp(argv[3], "add") == 0)
        printf("%d + %d = %d\n", a, b, a + b);  /* 10 + 20 = 30 */
    else
        printf("Unknown operation\n");
    return 0;
}

All arguments arrive as strings; convert with atoi (int) or atof (double) before arithmetic.

Self-check: What is argv[0]? Answer: The program name.

Exam pointers: State argc/argv meanings; show command-line values for a sample invocation; write a program that reads two numbers and an operator from the command line.

6.3 Graphics in C

Nepali BCA courses typically use Turbo C's BGI <graphics.h> library for graphics. Concepts below use that library; Linux modern alternatives (SDL/OpenGL) differ, but <graphics.h> remains the exam expectation.

6.3.1 Introduction to graphics programming (basic concepts, graphics modes)

#include <graphics.h>
#include <conio.h>
int main(void) {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "C:\\TC\\BGI");
    /* drawing here */
    getch();
    closegraph();
    return 0;
}

DETECT auto-selects the best graphics driver/mode; initgraph initializes graphics with pointers to driver and mode variables plus the BGI path; closegraph() returns to text mode.

Self-check: What does DETECT do in initgraph? Answer: Automatically detects and selects the best available graphics driver and mode.

Exam pointers: State the steps to initialize and close graphics mode; explain DETECT, gd, gm.

6.3.2 Drawing primitives: points, lines, and common geometric shapes (rectangles, circles, ellipses, arcs, polygons)

putpixel(x, y, color);             /* single pixel */
line(x1, y1, x2, y2);              /* straight line */
rectangle(left, top, right, bottom);   /* outline rectangle */
circle(x, y, radius);              /* circle */
ellipse(x, y, start, end, rx, ry);   /* ellipse arc */
arc(x, y, start, end, radius);     /* arc */
drawpoly(n, points);               /* polygon from point array */

Self-check: Which function draws a filled rectangle in BGI graphics? Answer: bar() (covered in 6.3.3); rectangle() draws only the outline.

Exam pointers: List drawing primitives with arguments; write code to draw a line, circle, and rectangle.

6.3.3 Managing colors and fill styles for graphical output

setcolor(RED);                        /* outline color */
setfillstyle(SOLID_FILL, BLUE);       /* fill pattern + color */
bar(100, 100, 300, 200);              /* filled rectangle */
fillellipse(200, 200, 50, 30);        /* filled ellipse */
floodfill(x, y, boundary_color);      /* fill enclosed region */

Colors: BLACK, BLUE, GREEN, CYAN, RED, MAGENTA, BROWN, LIGHTGRAY, DARKGRAY, LIGHTBLUE, LIGHTGREEN, LIGHTCYAN, LIGHTRED, LIGHTMAGENTA, YELLOW, WHITE.

Self-check: Which function fills an enclosed region bounded by a color? Answer: floodfill(x, y, boundary_color).

Exam pointers: Name three BGI colors and two fill functions; show code to draw a filled circle.

6.3.4 Displaying and formatting text in graphics mode

outtextxy(100, 50, "BCA Nepal");
settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 2);   /* font, direction, size */
outtext("Welcome");   /* at current position */

outtextxy prints at a coordinate; settextstyle chooses font, horizontal/vertical direction, and character-size multiplier.

Self-check: Which function prints text at a specific (x, y) coordinate? Answer: outtextxy(x, y, string).

Exam pointers: Contrast outtext and outtextxy; state settextstyle parameters.

6.3.5 Fundamentals of simple animation (clearing the screen, redrawing elements, using delays)

Animation loop: erase old position (redraw with background color) → update position → redraw at new position → pause with delay().

#include <graphics.h>
#include <conio.h>
#include <dos.h>
int main(void) {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "C:\\TC\\BGI");
    int x = 100, y = 100, r = 20, dx = 5, dy = 3;
    int maxX = getmaxx(), maxY = getmaxy();
    while (!kbhit()) {
        setcolor(BLACK);
        setfillstyle(SOLID_FILL, BLACK);
        fillellipse(x, y, r, r);   /* erase old ball */
        x += dx;  y += dy;
        if (x - r < 0 || x + r > maxX) dx = -dx;
        if (y - r < 0 || y + r > maxY) dy = -dy;
        setcolor(WHITE);
        setfillstyle(SOLID_FILL, WHITE);
        fillellipse(x, y, r, r);   /* draw new ball */
        delay(20);
    }
    getch();
    closegraph();
    return 0;
}

This erase-redraw-delay cycle is the simplest animation principle; it can flicker, which double-buffering addresses in richer libraries.

Self-check: Name the three steps of a simple animation loop. Answer: Erase old position → update position → redraw → pause (delay).

Exam pointers: Describe the erase-draw-delay animation cycle; explain wall-bounce logic (dx = -dx).

Key terms — Unit 6

FILE pointer · text vs binary mode · fopen modes · fseek/ftell/rewind · argc/argv · atoi/atof · initgraph · DETECT · animation erase-redraw-delay cycle

Unit 6 summary

Files offer persistent storage as text or binary; fopen modes control access; fgetc/fputc/fgets/fputs/fprintf/fscanf/fread/fwrite perform operations; fseek, ftell, rewind enable random access. main(int argc, char *argv[]) receives command-line arguments as strings, converted with atoi/atof. Graphics via BGI uses initgraph/closegraph, drawing primitives, colors/fills, text output, and the erase-draw-delay animation cycle. Complete compilable examples are given for file copy, command-line arithmetic, and a moving ball.

Expanded chapter notes

Up to this point, every variable, array, and structure created in a program has resided in Random Access Memory (RAM). RAM is volatile. The moment a program terminates or the computer loses power, the operating system reclaims that memory, and all data is permanently destroyed. To build software that remembers user preferences, stores financial records, or maintains databases, a program must be able to write its internal memory state to non-volatile storage (a hard drive or SSD). This unit introduces the mechanisms for interacting with the outside world beyond the standard keyboard and monitor. File handling allows programs to read and write persistent data. Command-line arguments allow users to pass configuration data to a program the exact millisecond it is launched by the operating system. Finally, graphics programming breaks away from the constraints of the text console, allowing the programmer to manipulate individual pixels to draw shapes, render colors, and simulate motion.

6.1 File Handling

In C, a file is treated as a one-dimensional stream of bytes. The C standard library (<stdio.h>) does not care whether the file is on a magnetic spinning disk, a solid-state drive, or a network location; it abstracts the hardware away, providing a standardized set of functions to push bytes into the stream or pull bytes out of it.

6.1.2 Concepts of files (text vs. binary) and file operations (opening, closing, reading, writing)

Files in C are broadly categorized into two distinct types based on how the bytes within them are interpreted by the operating system and the program.

Detailed practice questions and answer keys

Unit 1

  1. List the five generations of programming languages with one example each, and state which generation C belongs to.
    • Answer: 1GL machine (binary), 2GL assembly (e.g., x86 asm), 3GL high-level (C, Pascal, FORTRAN), 4GL very high-level (SQL, MATLAB), 5GL logic/constraint (Prolog). C is 3GL.
  2. Draw the five-stage C compilation pipeline with input/output files for each stage.
    • Answer: source .c → preprocessor → .i → compiler → .s → assembler → .o → linker → executable → loader runs main().
  3. State four characteristics of C and two application areas.
    • Answer: middle-level, procedural, portable, efficient (any four); OS/embedded systems (any two).

Unit 2 4. Write a C program to read two integers and print the larger using if-else.

  • Answer: read a, b; if (a > b) printf a; else printf b;
  1. Trace output: int i = 1; while (i <= 3) { printf("%d", i); i++; }
    • Answer: 123
  2. What is fall-through in switch, and when is it a bug?
    • Answer: Omitting break lets execution continue into the next case; useful intentionally (multiple cases, one action), usually a bug otherwise.

Unit 3 7. Write a recursive function for factorial and trace factorial(4).

  • Answer: int fact(int n){return n<=1?1:n*fact(n-1);}; trace: 4→3→2→1→1, result 24.
  1. Demonstrate call by value vs call by reference using a swap example.
    • Answer: value passes copies (original unchanged); reference passes addresses via pointers (original changed).
  2. Write a program to add two 2×2 matrices and print the result.
    • Answer: nested loops C[i][j] = A[i][j] + B[i][j].

Unit 4 10. Define struct Book { title, author, price, year }, store 5 books, print the most expensive. - Answer: array of 5 structs; loop comparing price; print fields of max. 11. Contrast structure and union with a memory-layout explanation. - Answer: struct = sum of sizes, all members valid; union = largest size, last-written member valid. 12. Use enum for weekdays; print whether a day is a weekend. - Answer: enum {MON..SUN}; check SAT/SUN.

Unit 5 13. Write a program using malloc to read n integers and print the largest. - Answer: allocate n * sizeof(int), NULL check, loop for max, free. 14. Contrast malloc and calloc; when use realloc? - Answer: malloc uninitialized, calloc zeroed; realloc resizes an existing allocation. 15. Explain dangling pointer and memory leak with code fixes. - Answer: dangling = use after free (fix: p = NULL); leak = never free (fix: match each alloc with free).

Unit 6 16. Write a program to copy one text file to another using fgetc/fputc. - Answer: open source "r", dest "w", loop fgetc/fputc until EOF, close both. 17. Write a program taking a filename from the command line and printing its contents. - Answer: argv[1] as filename; fopen, fgets loop, printf. 18. Explain random access with fseek; modify the third integer in a binary file. - Answer: fseek(fp, 2 * sizeof(int), SEEK_SET), fread/fwrite, fclose.


References

  • Balagurusamy, E. Programming in ANSI C (latest ed.). Tata McGraw-Hill Education.
  • Deitel, P. J., & Deitel, H. M. C How to Program (latest ed.). Pearson Education.
  • Kernighan, B. W., & Ritchie, D. M. The C Programming Language (latest ed.). Prentice Hall.
  • Prata, S. C Primer Plus (latest ed.). Pearson Education.

Source evidence