Unit I · JNTUK R23

Introduction to
Programming

Build your programming foundation: understand how computers think, write your first C program, and learn to solve problems like a software engineer.

History of Computers ALU Memory Data Types Variables Operators Algorithms Flowcharts Pseudocode Complexity
Why Programming Matters ⭐ EXAM

Every app on your phone, every website you visit, every ATM you use — all powered by programming. When you learn C, you're learning the language that built UNIX, Linux, and most operating systems. You're learning how computers actually work at the metal level.

C is the grandfather of Python, Java, JavaScript, and C++. Master C, and everything else becomes easier.

Why C?
Fast · Portable · Foundational
Used In
OS · Embedded · Games · Compilers
Year Created
1972 — Bell Labs
Creator
Dennis Ritchie
Computer Architecture — ALU, Memory & I/O ⭐ PYQ

Think of a computer like a human body: The brain = CPU, Memory = short-term memory (RAM), Disk = long-term memory, Keyboard = eyes/ears (input), Monitor = mouth (output).

ALU
Arithmetic Logic Unit — does ALL math (+, -, ×, ÷) and comparisons (>, <, ==)
Control Unit (CU)
Directs all operations — the "manager" of the CPU
Program Counter (PC)
Holds address of NEXT instruction to execute — like a bookmark
Memory (RAM)
Temporary storage — variables live here when program runs

Memory Hierarchy (Fastest → Slowest):

Registers
Nanoseconds
Cache (L1/L2)
Nanoseconds
RAM
Microseconds
Disk (SSD/HDD)
Milliseconds
💡
Key InsightWhen you declare int a = 5;, variable 'a' lives in RAM. The CPU fetches it, does math in registers, stores result back in RAM.
Programming Languages — Types & Levels PYQ
Machine Language
Binary 0s & 1s — what CPU actually reads. Not human-friendly.
Assembly Language
MOV, ADD, JMP — symbolic codes. Closer to human but still hardware-specific.
High-Level (C, Python, Java)
Human-readable! Compiler/interpreter converts to machine code.
1

Write Source Code (.c file)

Your C program written in editor
2

Preprocessor

Handles #include, #define — expands macros
3

Compiler (gcc)

Translates C code to assembly/machine code
4

Linker

Connects standard library functions, creates .exe
5

Execute

CPU runs the machine code, program output appears
Data Types, Variables & Constants ⭐ EXAM

A variable is a named box in memory that stores a value. A data type tells the compiler: how many bytes to reserve and what kind of data goes in.

🖥️ Memory Visualization
0x1000
5
a (int)
0x1004
3.14
pi (float)
0x1008
'A'
ch (char)
0x1009
12345.6
x (double)
Data TypeSizeRangeFormat
int4 bytes-2,147,483,648 to 2,147,483,647%d
float4 bytes±3.4 × 10⁻³⁸ to 10³⁸%f
double8 bytes±1.7 × 10⁻³⁰⁸ to 10³⁰⁸%lf
char1 byte-128 to 127 (ASCII)%c
long8 bytes±9.2 × 10¹⁸%ld
variables.c
#include<stdio.h>

int main() {
    /* Variable Declarations */
    int age = 20;
    float gpa = 8.75;
    char grade = 'A';
    double salary = 75000.50;

    /* Constant — value CANNOT change */
    const float PI = 3.14159;

    printf("Age: %d\n", age);
    printf("GPA: %.2f\n", gpa);
    printf("Grade: %c\n", grade);

    return 0;
}
  • Line 1#include <stdio.h> — includes Standard I/O library (printf, scanf live here)
  • Line 4-7Variable declarations — tells compiler to reserve memory. int age = 20 reserves 4 bytes at some address and puts 20 in it.
  • Line 10const — PI can never be changed after declaration. Trying to do PI = 3 gives a compile error.
  • %.2fFormat specifier — prints float with exactly 2 decimal places
⚠️
Common ErrorUsing a variable before declaring it: a = 5; int a; → Compile error! Always declare first.
Operators & Type Conversion ⭐ PYQ
CategoryOperatorsExampleResult
Arithmetic+ - * / %10 % 31 (remainder)
Relational== != > < >= <=5 > 31 (true)
Logical&& || !1 && 00 (false)
Bitwise& | ^ ~ << >>5 << 110 (shift left)
Assignment= += -= *= /=a += 5a = a + 5
Increment++ --a++ or ++aadds 1
Ternary? :a > b ? a : bmax of a, b

Type Conversion: C automatically converts smaller types to larger (implicit). You can force it with casting (explicit).

typecast.c
int a = 7, b = 2;

/* Implicit: int ÷ int = int → TRUNCATES decimal */
printf("%d\n", a / b);     // Output: 3 (NOT 3.5)

/* Explicit Cast: force float division */
printf("%f\n", (float)a / b); // Output: 3.500000
🐛
Classic Bugint/int = int always! Beginner expects 3.5, gets 3. Always cast to float when you need decimal results.
Algorithms, Flowcharts & Pseudocode ⭐ EXAM

Algorithm = step-by-step instructions to solve a problem. Like a recipe. Write the algorithm BEFORE you code. Think first, code second!

Problem: Find largest of two numbers

1

START

2

Read inputs A and B

3

Check condition: if A > B

Go to step 4 if true, else step 5
4

Print "A is largest"

Go to step 6
5

Print "B is largest"

6

STOP

START
Read A, B
A > B ?
YES
Print A is largest
NO
Print B is largest
STOP
Oval
START / STOP
Rectangle
Process / Statement
Diamond
Decision (Yes/No)
Parallelogram
Input / Output
pseudocode
BEGIN
  READ A, B
  IF A > B THEN
    PRINT "A is largest"
  ELSE
    PRINT "B is largest"
  END IF
END
Time & Space Complexity ⭐ EXAM

Time Complexity = how long an algorithm takes as input grows. Space Complexity = how much memory it uses. We use Big O Notation to express these.

Time Complexity
O(n)
Loop runs n times → linear time
Space Complexity
O(1)
Fixed variables → constant space
NotationNameExampleSpeed
O(1)ConstantAccess array[0]⚡ Fastest
O(log n)LogarithmicBinary Search🚀 Very Fast
O(n)LinearLinear Search Good
O(n²)QuadraticBubble Sort (nested loop)⚠️ Slow
O(2ⁿ)ExponentialBrute Force subsets Very Slow
Your First C Program — Hello World + Input/Output ⭐ EXAM
hello.c
#include <stdio.h>   /* Step 1: Import I/O library */

int main()             /* Step 2: Program starts here */
{
    int num;           /* Step 3: Declare variable */

    printf("Enter a number: ");  /* Output */
    scanf("%d", &num);            /* Input (& = address of num) */

    printf("You entered: %d\n", num);

    return 0;           /* Step 4: Exit program */
}
  • #includePreprocessor directive — pastes stdio.h content before compilation. Gives access to printf and scanf.
  • int main()Every C program starts executing from main(). Returns int (0 = success, non-zero = error).
  • printf()Prints text to screen. \n = newline character (go to next line).
  • scanf()Reads user input. &num = address of num (where to store the value in memory).
  • return 0Signals to OS that program ran successfully. 0 = no errors.
🐛
Forgetting & in scanfscanf("%d", num) instead of scanf("%d", &num) → CRASH! The & gives scanf the memory address to write into.
Unit I — Practice MCQs
Q1. What is the size of int in C on a 32-bit system?
A2 bytes
B4 bytes
C8 bytes
D1 byte
B — int is 4 bytes (32 bits). It stores whole numbers from -2,147,483,648 to +2,147,483,647.
Q2. What does & operator do in scanf("%d", &a)?
AAND operation
BMultiply a by 2
CGet memory address of a
DDeclares a new variable
C — & is the "address-of" operator. scanf needs the address to know WHERE in memory to store the input.
Q3. What is the output of: printf("%d", 10/3);?
A3.33
B3
C3.0
DError
B — int/int = int! The decimal is TRUNCATED (not rounded). 10/3 = 3 in integer division.
Unit I — Exam Focus & PYQ Analysis
Write a C program to find sum of two numbers (PYQ — 2022, 2023)
Explain ALU, Control Unit, Memory hierarchy (PYQ — 2021, 2022)
What is an algorithm? Write algorithm to find largest of 3 numbers
Difference between compiler and interpreter
Explain time complexity with Big O notation — O(1), O(n), O(n²)
What are data types in C? Explain with size and range
Explain top-down vs bottom-up approach
Draw flowchart for swapping two numbers
Unit I — Quick Revision Cheat Sheet
int
4 bytes · %d · whole numbers
float
4 bytes · %f · decimals
char
1 byte · %c · single character
double
8 bytes · %lf · high precision
printf
Output to screen
scanf
Input from user (use &)
Algorithm
Step-by-step problem solution
O(1)
Constant — fastest
O(n)
Linear — one loop
O(n²)
Quadratic — nested loops
ALU
Does math + comparisons
PC
Holds next instruction address
Unit II · JNTUK R23

Control
Structures

Master the logic that controls program flow — conditions, decisions, and loops. This unit is the core of ALL programming logic.

if / if-else switch for loop while loop do-while break continue Nested loops
if, if-else, else-if Ladder ⭐ PYQ

Decision making in code! Like traffic signals — if red, stop; else, go. The CPU evaluates a condition: if TRUE (non-zero), execute block. If FALSE (zero), skip it.

grade.c — else-if ladder
#include <stdio.h>

int main() {
    int marks;
    printf("Enter marks (0-100): ");
    scanf("%d", &marks);

    if (marks >= 90)
        printf("Grade: O (Outstanding)\n");
    else if (marks >= 75)
        printf("Grade: A+ (Excellent)\n");
    else if (marks >= 60)
        printf("Grade: A (Very Good)\n");
    else if (marks >= 50)
        printf("Grade: B (Good)\n");
    else
        printf("Grade: F (Fail)\n");

    return 0;
}

🧠 Dry Run:

marksCondition CheckedResultOutput
95marks >= 90TRUEGrade: O
78marks >= 90 → FALSE
marks >= 75 → TRUE
2nd condition trueGrade: A+
45All conditions FALSEelse executesGrade: F
⚠️
= vs ==if(a = 5) is assignment (always true!). if(a == 5) is comparison. This is the most common beginner bug!
switch Statement PYQ

switch is a cleaner alternative to long if-else ladders. It matches a value to cases and executes. Perfect for menus, day names, grade display, etc. Works with int and char only — NOT float!

calculator.c — switch
#include <stdio.h>

int main() {
    int a, b, choice;
    char op;

    printf("Enter: a op b (e.g. 5 + 3): ");
    scanf("%d %c %d", &a, &op, &b);

    switch(op) {
        case '+': printf("Result = %d\n", a+b); break;
        case '-': printf("Result = %d\n", a-b); break;
        case '*': printf("Result = %d\n", a*b); break;
        case '/':
            if(b != 0)
                printf("Result = %d\n", a/b);
            else
                printf("Error: Divide by zero!\n");
            break;
        default: printf("Invalid operator!\n");
    }
    return 0;
}
🐛
Missing break!Without break, execution falls through to next case. This is called "fall-through" — often a bug unless intentional.
Loops — for, while, do-while ⭐ EXAM

for loop — use when you know exactly how many times to repeat. Has 3 parts: init, condition, update — all in one line.

for_loop.c
/* Print 1 to 10 */
for (int i = 1; i <= 10; i++) {
    printf("%d ", i);
}
/* Output: 1 2 3 4 5 6 7 8 9 10 */

/* Sum of first n numbers */
int n=5, sum=0;
for (int i=1; i<=n; i++) {
    sum += i;   // sum = sum + i
}
printf("Sum = %d", sum); // Sum = 15
iCondition i≤5sum = sum+isum
1TRUE0+11
2TRUE1+23
3TRUE3+36
4TRUE6+410
5TRUE10+515
6FALSELoop ends15

while loop — use when you DON'T know how many times. Checks condition BEFORE each iteration. If condition is false initially, loop body never executes.

while_loop.c
/* Reverse digits of a number */
int n = 1234, rev = 0;

while (n != 0) {
    int digit = n % 10;  // get last digit
    rev = rev * 10 + digit;
    n = n / 10;           // remove last digit
}
printf("Reversed: %d\n", rev); // 4321
ndigit (n%10)rev = rev*10+digitn = n/10
123440*10+4 = 4123
12334*10+3 = 4312
12243*10+2 = 4321
11432*10+1 = 43210
0Loop ends → rev = 4321

do-while — loop body executes AT LEAST ONCE, THEN checks condition. Use for menus where user must see at least one option.

do_while.c
int choice;
do {
    printf("1. Add  2. Sub  3. Exit\n");
    printf("Enter choice: ");
    scanf("%d", &choice);
    // process choice...
} while (choice != 3); // repeat until Exit
for
Known iterations · condition checked BEFORE
while
Unknown iterations · condition BEFORE
do-while
Executes minimum ONCE · condition AFTER
break & continue — Loop Control PYQ
break_continue.c
/* break — exits loop immediately */
for (int i=1; i<=10; i++) {
    if (i == 5) break;   // stops at 5
    printf("%d ", i);
}
// Output: 1 2 3 4

/* continue — skips current iteration */
for (int i=1; i<=10; i++) {
    if (i % 2 == 0) continue; // skip even
    printf("%d ", i);
}
// Output: 1 3 5 7 9
Important Programs — Unit II ⭐ EXAM
factorial.c
#include <stdio.h>
int main() {
    int n, fact = 1;
    scanf("%d", &n);
    for (int i=1; i<=n; i++)
        fact *= i;   // fact = fact * i
    printf("%d! = %d\n", n, fact);
    return 0;
}
ifact = fact×ifact
11×11
21×22
32×36
46×424
524×5120
prime.c
#include <stdio.h>
int main() {
    int n, isPrime=1;
    scanf("%d", &n);

    if (n < 2) isPrime = 0;

    for (int i=2; i*i<=n; i++) {
        if (n % i == 0) {
            isPrime = 0;
            break;
        }
    }
    if (isPrime)
        printf("%d is Prime\n", n);
    else
        printf("%d is Not Prime\n", n);
    return 0;
}
💡
Optimization TrickCheck only up to √n (i*i <= n). If n has a factor greater than √n, it must also have one smaller than √n. This makes it O(√n) instead of O(n).
star_pattern.c
/* Right Triangle Star Pattern */
#include <stdio.h>
int main() {
    int n = 5;
    for (int i=1; i<=n; i++) {
        for (int j=1; j<=i; j++)
            printf("* ");
        printf("\n");
    }
}
/*
*
* *
* * *
* * * *
* * * * *
*/
💡
Pattern LogicOuter loop = rows (i). Inner loop = columns (j). Number of stars in row i = i. Nested loops are the KEY to all patterns!
fibonacci.c
#include <stdio.h>
int main() {
    int n, a=0, b=1, c;
    scanf("%d", &n);
    printf("%d %d ", a, b);
    for (int i=2; i<n; i++) {
        c = a + b;
        printf("%d ", c);
        a = b;
        b = c;
    }
    return 0;
}
/* n=8: 0 1 1 2 3 5 8 13 */
Unit II — Exam Focus & Quick Revision
🔥Factorial, Fibonacci — most repeated programs (PYQ every year)
🔥Prime number check using for loop (PYQ 2022, 2023)
🔥Star patterns with nested loops (PYQ 2021, 2022, 2023)
Difference: for vs while vs do-while with example
break and continue — explain with programs
Simple Calculator using switch statement
if(a=5)
Assignment — always true! BUG!
if(a==5)
Comparison — correct!
break
Exit loop immediately
continue
Skip to next iteration
do-while
Min 1 execution
switch
int/char only, needs break
Unit III · JNTUK R23

Arrays &
Strings

Store multiple values, search, sort, and manipulate text. Arrays and strings are the building blocks of data handling in C.

1D Arrays2D ArraysArray Indexing SearchingSortingStrings String Functionsgets/puts
Arrays — Memory Model & Indexing ⭐ EXAM

Array = collection of same-type elements stored in contiguous (adjacent) memory. Instead of declaring 100 int variables, declare one array of 100 ints.

Key Rule: Array indexing starts from 0, NOT 1! An array of size n has indices 0 to n-1.

🖥️ Memory — int arr[5] = {10, 20, 30, 40, 50}
0x100
10
arr[0]
0x104
20
arr[1]
0x108
30
arr[2]
0x10C
40
arr[3]
0x110
50
arr[4]
Each int = 4 bytes → addresses jump by 4. arr[0] is at base address, arr[i] is at base + i×4.
arrays.c
#include <stdio.h>

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int n = 5, sum = 0;

    /* Traverse array */
    for (int i=0; i<n; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
        sum += arr[i];
    }
    printf("Sum = %d\n", sum);
    printf("Average = %.2f\n", (float)sum/n);
    return 0;
}
🐛
Out of Bounds!Accessing arr[5] when size is 5 → arr[5] doesn't exist! C won't warn you — it reads garbage memory or crashes. Always use indices 0 to n-1.
Searching & Sorting Arrays ⭐ EXAM
bubble_sort.c
#include <stdio.h>
int main() {
    int arr[] = {64,34,25,12,22};
    int n=5, temp;

    for (int i=0; i<n-1; i++) {
        for (int j=0; j<n-i-1; j++) {
            if (arr[j] > arr[j+1]) {
                temp = arr[j];       // swap
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
    /* Sorted: 12 22 25 34 64 */
    return 0;
}
💡
Bubble Sort LogicIn each pass, the largest unsorted element "bubbles up" to its correct position. After pass 1, largest is at end. After pass 2, 2nd largest is placed. Time: O(n²)
🔲
2D Arrays — Matrix Operations ⭐ PYQ

2D array = matrix = array of arrays. Think of it as rows and columns. int mat[3][3] = 3 rows, 3 columns.

matrix_add.c
#include <stdio.h>
int main() {
    int a[2][2]={{1,2},{3,4}};
    int b[2][2]={{5,6},{7,8}};
    int c[2][2];

    /* Matrix Addition */
    for (int i=0; i<2; i++) {
        for (int j=0; j<2; j++) {
            c[i][j] = a[i][j] + b[i][j];
            printf("%d ", c[i][j]);
        }
        printf("\n");
    }
    return 0;
}
/* Output:
6 8
10 12 */
📝
Strings — Character Arrays & Functions ⭐ EXAM

String in C = char array ending with null character '\0'. C has no built-in String type — it's just an array of characters.

🖥️ "HELLO" in Memory
0x200
'H'
[0]
0x201
'E'
[1]
0x202
'L'
[2]
0x203
'L'
[3]
0x204
'O'
[4]
0x205
'\0'
null
strings.c
#include <stdio.h>
#include <string.h>  /* For string functions */

int main() {
    char name[50];

    printf("Enter name: ");
    gets(name);   /* Read string with spaces */

    printf("Hello, %s!\n", name);
    printf("Length: %d\n", strlen(name));

    /* String functions */
    char s1[20]="Hello", s2[20]="World", s3[50];

    strcat(s1, s2);   /* Concatenate: "HelloWorld" */
    strcpy(s3, s1);   /* Copy s1 to s3 */
    strcmp(s1, s2);   /* 0 if equal */
    strupr(s1);       /* Convert to uppercase */
    strlwr(s1);       /* Convert to lowercase */
    return 0;
}
FunctionHeaderWhat it doesReturns
strlen(s)<string.h>Length of stringint (count)
strcpy(d,s)<string.h>Copy s into ddest string
strcat(d,s)<string.h>Append s to ddest string
strcmp(s1,s2)<string.h>Compare strings0 if equal
strupr(s)<string.h>UPPERCASE conversionmodified string
strlwr(s)<string.h>lowercase conversionmodified string
Unit III — Exam Focus & Quick Revision
🔥Bubble Sort program with dry run (PYQ every year)
🔥Matrix multiplication (PYQ 2022, 2023)
🔥String operations: reverse, palindrome check (PYQ repeated)
Linear search vs binary search comparison
Explain string functions with examples
Array index
Starts at 0, ends at n-1
String end
'\0' null terminator
Bubble sort
O(n²) — nested loops, swap adjacent
2D array
arr[row][col] — row major order
strlen
Counts chars BEFORE '\0'
strcmp
0 = equal, <0 = first smaller
🔗 Unit IV · JNTUK R23

Pointers &
User-Defined Types

Master the most powerful — and feared — concept in C. Pointers let you talk directly to memory. Structures let you create your own data types.

PointersDereferencingPointer Arithmetic Array & PointersStructuresUnions
🔗
Pointers — Address, Dereferencing & Arithmetic ⭐ EXAM

Pointer = a variable that stores a memory ADDRESS instead of a regular value. Instead of storing 42, it stores where 42 lives in memory.

Real-world analogy: A pointer is like a Google Maps pin — it doesn't contain the restaurant, it contains its LOCATION.

🖥️ Pointer Memory Visualization
Variable 'a'
0x1004
42
int a
Pointer 'p'
0x2008
0x1004
int *p
p holds address of a
pointers.c
#include <stdio.h>

int main() {
    int a = 42;         // Normal variable
    int *p;              // Pointer variable (stores address)

    p = &a;              // p = address of a

    printf("Value of a    = %d\n", a);    // 42
    printf("Address of a  = %p\n", &a);   // 0x1004 (some hex)
    printf("p holds       = %p\n", p);    // 0x1004 (same!)
    printf("Value via p   = %d\n", *p);   // 42 (dereference)

    *p = 100;             // Change a's value THROUGH pointer
    printf("a is now      = %d\n", a);    // 100!

    return 0;
}
  • int *pDeclares pointer — p can hold address of any int. The * means "this is a pointer"
  • p = &a& = address-of operator — gets the memory address where a lives
  • *pDereferencing — "go to the address in p, and give me the value there". * in this context = "value at"
  • *p = 100Modifying via pointer — changes a's value without using a directly!

Pointer Arithmetic — when you do p++, pointer moves by the SIZE of the data type (4 bytes for int).

ptr_arithmetic.c
int arr[] = {10, 20, 30};
int *p = arr;   // p points to arr[0]

printf("%d\n", *p);   // 10 (arr[0])
p++;               // move to next int (4 bytes ahead)
printf("%d\n", *p);   // 20 (arr[1])
p++;
printf("%d\n", *p);   // 30 (arr[2])
⚠️
Null PointerAlways initialize pointers! int *p = NULL; means "points to nothing". Using an uninitialized pointer causes undefined behavior or crash.
🏗️
Structures — User-Defined Data Types ⭐ PYQ

struct = custom data type that groups different data types together. Instead of separate name, age, gpa variables for each student, bundle them in one structure.

structures.c
#include <stdio.h>

/* Define structure */
struct Student {
    int   rollno;
    char  name[50];
    float gpa;
};

int main() {
    /* Create structure variable */
    struct Student s1 = {101, "Ravi Kumar", 8.75};

    /* Access using dot operator */
    printf("Roll: %d\n",  s1.rollno);
    printf("Name: %s\n",  s1.name);
    printf("GPA:  %.2f\n", s1.gpa);

    /* Array of structures */
    struct Student class[60];  // 60 students!

    return 0;
}
. (dot) operator
s1.name → access member via struct variable
→ (arrow) operator
ptr→name → access via struct POINTER
🔀
Unions — Shared Memory PYQ

Union = like struct, but ALL members share the SAME memory location. Size = size of largest member. Only ONE member can hold a valid value at a time.

union.c
union Data {
    int i;       // 4 bytes
    float f;     // 4 bytes
    char str[20]; // 20 bytes — union size = 20
};
/* All share the same memory! */
struct
Each member has OWN memory. Size = sum of all members.
union
All members SHARE memory. Size = largest member.
Unit IV — Exam Focus & Quick Revision
🔥What is a pointer? Write C program demonstrating pointer (PYQ every year)
🔥Swap two numbers using pointers (PYQ 2022, 2023)
🔥Define structure, write program for student database (PYQ repeated)
Pointer arithmetic with arrays — explain with diagram
Difference: structure vs union with memory layout
&a
Address of variable a
*p
Value at address p (deref)
int *p
Pointer to int declaration
p++
Move 4 bytes for int pointer
s1.name
Access struct member via .
ptr→name
Access via struct pointer
⚙️ Unit V · JNTUK R23

Functions &
File Handling

Break programs into reusable blocks. Store and retrieve data from files. These are the hallmarks of professional C programming.

Function DeclarationArgumentsReturn Types RecursionScopeStorage Classes File I/Ofopen/fclose
⚙️
Functions — Declaration, Definition & Calls ⭐ EXAM

Function = reusable block of code that does a specific task. Write once, call many times. Like a machine in a factory — give it input, it produces output.

Functions prevent code repetition (DRY = Don't Repeat Yourself).

functions.c
#include <stdio.h>

/* ── Step 1: Function Declaration (Prototype) ── */
int add(int a, int b);
int factorial(int n);

/* ── Step 2: main() ── */
int main() {
    int result = add(5, 3);   // Function Call
    printf("5+3 = %d\n", result);

    printf("5! = %d\n", factorial(5));
    return 0;
}

/* ── Step 3: Function Definitions ── */
int add(int a, int b) {   // a,b are parameters
    return a + b;
}

int factorial(int n) {
    if (n == 0 || n == 1) return 1;  // base case
    return n * factorial(n-1);         // recursive call
}
  • PrototypeFunction declaration — tells compiler: function name, return type, parameter types. Must come BEFORE main().
  • add(5,3)Function call — 5,3 are ARGUMENTS. Values are passed to parameters a and b.
  • return a+bReturn value — sends computed result back to caller. return type must match declaration.
  • RecursionFunction calling itself — needs a base case to stop. factorial(5) calls factorial(4) calls... factorial(1) which returns 1.
🖥️ Stack Frame — factorial(3)
factorial(1)
n=1 → returns 1
factorial(2)
n=2 → 2 × factorial(1) = 2
factorial(3)
n=3 → 3 × factorial(2) = 6
main()
calls factorial(3) → gets 6
📦
Scope, Lifetime & Storage Classes PYQ
Local Variable
Declared inside function. Exists only while function runs. Default: auto.
Global Variable
Declared outside all functions. Accessible everywhere. Exists for entire program.
auto
Default for local vars. Created on stack, destroyed when function ends.
static
Retains value between function calls. Initialized once only.
extern
Access global variable from another file.
register
Hint to store in CPU register for speed (e.g. loop counter).
static_demo.c
void counter() {
    static int count = 0;  // initialized ONCE
    count++;
    printf("Count = %d\n", count);
}
int main() {
    counter(); // Count = 1
    counter(); // Count = 2
    counter(); // Count = 3
}
📁
File Handling — Read & Write to Files ⭐ EXAM

File handling = permanent data storage. Unlike variables (lost when program ends), files persist on disk. Used in real software: logs, databases, config files.

1

Open File — fopen()

Creates/opens a file. Returns FILE pointer. Check for NULL (file open failure).
2

Read/Write — fprintf(), fscanf(), fgets()

Write to or read from the file.
3

Close File — fclose()

ALWAYS close after use! Saves buffer, frees resources.
file_handling.c
#include <stdio.h>

int main() {
    FILE *fp;

    /* ── WRITE to file ── */
    fp = fopen("student.txt", "w"); // "w" = write mode
    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
    fprintf(fp, "Name: Ravi Kumar\n");
    fprintf(fp, "Roll: 101\n");
    fclose(fp);   // close after writing

    /* ── READ from file ── */
    fp = fopen("student.txt", "r"); // "r" = read mode
    char line[100];
    while (fgets(line, 100, fp) != NULL) {
        printf("%s", line);
    }
    fclose(fp);

    return 0;
}
ModeMeaningIf file doesn't exist
"r"Read onlyReturns NULL (error)
"w"Write (overwrite)Creates new file
"a"Append (add to end)Creates new file
"r+"Read + WriteReturns NULL
"w+"Write + Read (overwrite)Creates new file
🔗
Pointers in Functions & Arrays as Parameters PYQ

Call by Value — copy of argument passed. Changes in function DON'T affect original.
Call by Reference (using pointers) — address passed. Changes DO affect original.

call_by_ref.c — Swap using pointers
/* Swap using pointers (call by reference) */
void swap(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

int main() {
    int a=10, b=20;
    swap(&a, &b);   // pass ADDRESSES
    printf("a=%d b=%d\n", a, b);
    // Output: a=20 b=10
}

/* Arrays are ALWAYS passed by reference (pointer) */
void printArray(int arr[], int n) {
    for (int i=0; i<n; i++)
        printf("%d ", arr[i]);
}
Unit V — Exam Focus & Quick Revision
🔥Recursive factorial, Fibonacci (PYQ every year)
🔥Swap two numbers using call by reference / pointers (PYQ 2022, 2023)
🔥Write and Read from a file using fopen, fprintf, fclose (PYQ 2022)
Call by value vs call by reference with programs
Explain storage classes: auto, static, extern, register
Function prototype — what, why, when?
fopen("f","w")
Open file for writing
fclose(fp)
Always close after use!
static var
Retains value between calls
Call by val
Copy — original unchanged
Call by ref
Pointer — original changes
Recursion
Function calls itself, needs base case
🤖
EngiPrepHub Logo

About the Author

EngiPrepHub is an academic initiative aimed at providing high-quality, verified, and structured JNTUK R23 study notes, PYQs, and interactive tools for engineering students. Our materials are reviewed by expert students and engineers to ensure syllabus alignment.