0% found this document useful (0 votes)
18 views97 pages

Programming for Problem Solving Guide

The document outlines a comprehensive curriculum on programming for problem solving, covering computer fundamentals, problem-solving techniques, and the C programming language. It includes topics such as computer architecture, data types, algorithms, flowcharts, and memory management. Additionally, it discusses the compilation process and various coding schemes, providing a foundational understanding for students in computer science.

Uploaded by

manishsen2151
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views97 pages

Programming for Problem Solving Guide

The document outlines a comprehensive curriculum on programming for problem solving, covering computer fundamentals, problem-solving techniques, and the C programming language. It includes topics such as computer architecture, data types, algorithms, flowcharts, and memory management. Additionally, it discusses the compilation process and various coding schemes, providing a foundational understanding for students in computer science.

Uploaded by

manishsen2151
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PROGRAMMING FOR PROBLEM SOLVING

Link of digital notes: [Link]

Unit I

The computer: Block diagram of functional units of the computer, Data and
information, Classification of computers, Computer characteristics, Advantages of
the computer, Limitations of computer, Applications of computers, The CPU and the
Memory, Primary memory, Secondary memory, Memory hierarchy, Measuring the
memory, Examples based on the inter-conversion of memory units, The Computer
Software, Classifications of software, Operating system, The Number Systems
(Binary Octal, Decimal, Hexadecimal and their conversion to one another,
Operations on binary numbers, Other popular codes (ASCII, BCD, EBCDIC,
Excess-3 and Gray code)

Unit II

Problem-solving Techniques: Steps for logical and numerical problem-solving,


Solving a logical problem, Solving a numerical problem, Algorithm, Flowcharts,
Pseudo codes, Programming language, Language translator, Interpreter, Assembler,
Compiler, Compiling and executing process, Syntax and logical errors in the
compilation, Files generated in the C program lifecycle, C Program compilation
process

Unit III

Fundamentals of C: History of C language, Why C?, characters set, Whitespace


characters or escape sequences, Format specifiers, Tokens in C, Keywords,
Variables, Constant, Identifiers, Special symbols, Header files, Data types, Type
casting, Operators and Expressions, Precedence and associativity of operators in C,
Decision-making Statements: Conditional and Unconditional decision-making
statements, Roots of a quadratic equation, Loops, Arrays, Single, Multidimensional
array, String, Standard inbuilt string functions, Linear searching, Binary search,
Bubble sort

Unit IV

Function, Need of the function, Types of function, Call by value, Call by reference,
The Console Input-output Functions, Preprocessor, Storage classes in C, Recursion,
use recursion for finding the factorial of a number, Fibonacci series, Ackermann
function, Structure and Union, Passing structure in a function, Pointers, Generic
pointer, Self-referential structure, Linked list, File Handling in C, Operations on file
through the inbuilt functions, Dynamic memory allocate: malloc(), calloc(), free().
Realloc(), Basic of Time and Space Complexity of an algorithm.

Link of digital notes: [Link]


UNIT I

1. Computer System & Functional Units


A computer is an electronic device that accepts data, processes it according to
instructions, and produces useful information. It consists of five basic functional
units:​
1.​ Input Unit
●​ Devices: Keyboard, mouse, scanner, microphone, barcode reader.
●​ Function: Accepts data and instructions from the user and converts
them into a form (binary) that the computer can process.​
2.​ Memory Unit
●​ Divided into Primary memory (RAM, ROM) and Secondary memory
(HDD/SSD, etc.).
●​ Stores data, instructions, intermediate results, and final results.​
3.​ Control Unit (CU)
●​ Controls and coordinates all operations.
●​ Fetches instructions from memory, decodes them, and issues control
signals to other units.​
4.​ Arithmetic Logic Unit (ALU)
●​ Performs arithmetic operations (addition, subtraction, multiplication,
division) and logical operations (AND, OR, NOT, comparisons).​
5.​ Output Unit
●​ Devices: Monitor, printer, speakers, plotter.
●​ Converts processed results into human‑readable form.​

Data flow: Input → Memory → CU/ALU → Memory → Output.​


2. Data, Information, Characteristics, Advantages,
Limitations

Data vs Information
●​ Data: Raw facts and figures, e.g., “40, 50, 70”.
●​ Information: Processed and organized data that has meaning, e.g., “Average
marks = 53.33”.​

Characteristics of Computers
●​ Speed: Millions of operations per second (microseconds, nanoseconds).
●​ Accuracy: Very high accuracy; errors usually due to wrong input/program.
●​ Diligence: No fatigue, can work continuously without loss in performance.
●​ Storage Capacity: Can store huge amounts of data.
●​ Versatility: Can perform different types of tasks (business, games, science).
●​ Automation: Works automatically once program is loaded.​

Advantages
●​ High speed, accuracy, reliability.
●​ Reduces manual effort and long‑term cost.
●​ Helps in complex computations and simulations.​

Limitations
●​ No intelligence or common sense.
●​ Cannot work without proper instructions.
●​ Dependent on electricity and maintenance.​

3. Applications of Computers
●​ Business: Billing, payroll, inventory, accounting.
●​ Education: E‑learning, online exams, simulations.
●​ Medicine: Diagnosis, patient records, surgery assistance.
●​ Entertainment: Games, movies, music, animation.
●​ Banking: Online transactions, ATMs.
●​ Government: E‑governance, citizen services, record management.
●​ Scientific Research: Simulations, data analysis, modeling.​

4. Memory Units & Hierarchy

Memory Units
●​ 1 Bit = 0 or 1
●​ 1 Byte = 8 bits
●​ 1 KB = 1024 Bytes
●​ 1 MB = 1024 KB
●​ 1 GB = 1024 MB
●​ 1 TB = 1024 GB​

Memory Hierarchy
Fastest & smallest at top, slowest & largest at bottom:​
●​ CPU Registers
●​ L1, L2, L3 Cache
●​ Main Memory (RAM)
●​ Secondary Storage (HDD, SSD, optical disk, USB)

5. Primary & Secondary Memory

Primary Memory
1.​ RAM (Random Access Memory)
●​ Volatile (data lost when power off).
●​ Stores currently executing programs and data.
●​ Types:
●​ SRAM: Faster, used for cache, more expensive.
●​ DRAM: Slower but cheaper, used as main memory.​
2.​ ROM (Read Only Memory)
●​ Non‑volatile (data retained without power).
●​ Stores firmware like BIOS.
●​ Variants: PROM, EPROM, EEPROM, Flash.​

Secondary Memory
●​ HDD: Magnetic, large capacity, cheaper.
●​ SSD: Flash‑based, faster, expensive per GB.
●​ Optical Disks: CD, DVD, Blu‑ray.
●​ Magnetic Tape: Sequential access, backups.
●​ Pen Drives/USB: Portable flash storage.​

6. Number Systems & Conversions

Number Systems
●​ Binary (Base 2): Digits 0,1.
●​ Octal (Base 8): Digits 0–7.
●​ Decimal (Base 10): Digits 0–9.
●​ Hexadecimal (Base 16): Digits 0–9, A–F.​

1. Types of Number Systems


System Base (Radix) Digits
Used
Decimal 10 0–9

Binary 2 0, 1

Octal 8 0–7

Hexadecimal 16 0–9, A–F

2. Decimal → Binary / Octal / Hexadecimal


Method: Repeated Division

Formula / Rule:

Divide the decimal number by the base repeatedly.​


Write remainders in reverse order.

Conversion Divide by

Decimal → Binary 2

Decimal → Octal 8

Decimal → Hexa 16

3. Binary / Octal / Hexadecimal → Decimal


Method: Positional Weight Method

Formula:

Example:

4. Binary → Octal
Method: Group of 3 bits (from right)
Binary Octal

000 0

001 1

010 2

011 3

100 4

101 5

110 6

111 7

5. Binary → Hexadecimal
Method: Group of 4 bits (from right)

Binary Hex

0000 0

1001 9

1010 A

1111 F

6. Octal → Binary
Method: Replace each octal digit with 3-bit binary

Example:

7. Hexadecimal → Binary
Method: Replace each hex digit with 4-bit binary
Example:

8. Octal → Hexadecimal
Method:​
Octal → Binary → Hexadecimal

9. Hexadecimal → Octal
Method:​
Hexadecimal → Binary → Octal

10. Fractional Number Conversion


Decimal Fraction → Binary

Multiply fraction by 2, take integer part.

Binary Fraction → Decimal

7. Binary Operations

Addition Rules
●​ 0+0=0
●​ 0+1=1
●​ 1+0=1
●​ 1+1=10 (0 with carry 1)​
Subtraction Rules
●​ 0−0=0
●​ 1−0=1
●​ 1−1=0
●​ 0−1=1 with borrow 1 from next bit.​

8. Coding Schemes
●​ ASCII: 7‑bit/8‑bit code, 128/256 characters; A=65, a=97, 0=48.​
●​ EBCDIC: 8‑bit code, used in IBM mainframes.​
●​ BCD: 4‑bit for each decimal digit (e.g., 25 = 0010 0101).​
●​ Excess‑3: BCD + 3, used in some arithmetic circuits.​
●​ Gray Code: Only one bit changes between successive numbers; used in
error‑sensitive hardware.​

1. ASCII (American Standard Code for Information


Interchange)
●​ Uses 7-bit (standard) or 8-bit (extended) code​

●​ Represents 128 characters (7-bit) or 256 characters (8-bit)​

●​ Includes alphabets, digits, symbols, control characters​

Examples:

●​ A = 65 → 1000001 (7-bit)​

●​ a = 97 → 1100001​

●​ 0 = 48 → 0110000​

2. EBCDIC (Extended Binary Coded Decimal


Interchange Code)
●​ Uses 8-bit code​
●​ Supports 256 characters​

●​ Mainly used in IBM mainframe computers​

Example:

●​ A = 193 → 11000001​

●​ 0 = 240 → 11110000​

3. BCD (Binary Coded Decimal)


●​ Each decimal digit is represented by 4 bits​

●​ Used in financial & display systems​

Example:

●​ 2 → 0010​

●​ 5 → 0101​

BCD = 0010 0101

4. Excess-3 Code
●​ Excess-3 = BCD + 3​

●​ Add 3 (0011) to each decimal digit​

●​ Used in arithmetic circuits​


Example:

Digit BCD +3 Excess-3

2 0010 +0011 0101

5 0101 +0011 1000

Excess-3 = 0101 1000

5. Gray Code
●​ Only one bit changes between consecutive numbers​

●​ Reduces errors in hardware encoders & digital systems​

Example:
Decimal Binary Gray

0 000 000

1 001 001

2 010 011

3 011 010

4 100 110

UNIT II – Problem Solving & Introduction to


C
2.1 Steps for Problem Solving

General Steps:
1.​ Understand the problem
2.​ Analyze the problem
3.​ Develop an algorithm
4.​ Draw flowchart
5.​ Write pseudocode
6.​ Code the program
7.​ Test and debug
8.​ Documentation

2.2 Solving a Logical Problem


Problem: Check if a person can vote (age ≥ 18)

Algorithm:
>>

Step 1: Start
Step 2: Input age
Step 3: If age >= 18 then
Print "Can vote"
Else
Print "Cannot vote"
Step 4: Stop

2.3 Solving a Numerical Problem


Problem: Find sum of two numbers

Algorithm:
>>

Step 1: Start
Step 2: Input a, b
Step 3: sum = a + b
Step 4: Print sum
Step 5: Stop

Flowchart:
>>

(Start)

[Input a, b]

[sum = a + b]

[Print sum]

(Stop)

2.4 Algorithm
Definition: Step-by-step procedure to solve a problem

Characteristics:
1.​ Finite: Must terminate
2.​ Definite: Clear instructions
3.​ Input: Zero or more inputs
4.​ Output: At least one output
5.​ Effective: Practical to execute
Example: Find largest of 3 numbers
>>

Algorithm: Find_Largest
Step 1: Start
Step 2: Input a, b, c
Step 3: If (a > b) AND (a > c) then
largest = a
Else if (b > c) then
largest = b
Else
largest = c
Step 4: Print largest
Step 5: Stop

2.5 Flowcharts
Definition: Pictorial representation of algorithm

Flowchart Symbols:

Symbol Name Purpose

Oval Terminal Start/Stop

Parallelogram Input/Output Read/Print

Rectangle Process Calculations

Diamond Decision Conditions

Arrow Flow line Direction


Circle Connector Join flow

2.6 Pseudocode
Definition: English-like representation of algorithm

Example: Find factorial


>>

BEGIN
INPUT n
SET fact = 1
FOR i = 1 TO n DO
fact = fact * i
END FOR
PRINT fact
END

2.7 Programming Language


Definition: Artificial language to write programs

Types:
1.​ Low-Level Languages
●​ Machine Language: Binary (0,1)
●​ Assembly Language: Mnemonics (MOV, ADD)
2.​ High-Level Languages
●​ C, C++, Java, Python
●​ Human-readable
●​ Need translator

2.8 Language Translators


1. Compiler
●​ Translates entire program at once
●​ Creates executable file
●​ Faster execution
●​ Examples: C, C++ use compiler
Process:
>>

Source Code → Compiler → Object Code → Linker → Executable

2. Interpreter
●​ Translates line by line
●​ No executable file
●​ Slower execution
●​ Examples: Python, JavaScript

3. Assembler
●​ Translates Assembly language to Machine code
●​ One-to-one mapping

Comparison:

Feature Compiler Interpreter

Translation Entire program Line by line

Speed Fast Slow

Executable Creates .exe No .exe


Debugging Difficult Easy

Memory More Less

Example C, C++ Python

2.9 Compiling and Executing Process

C Program Lifecycle:

┌──────────────┐
│ Source Code │ (.c file)
│ program.c │
└──────┬───────┘

[Preprocessor] (#include, #define expanded)

┌──────────────┐
│ Expanded │ (.i file)
│ Source │
└──────┬───────┘

[Compiler] (Converts to assembly)

┌──────────────┐
│ Assembly │ (.s file)
│ Code │
└──────┬───────┘

[Assembler] (Converts to machine code)

┌──────────────┐
│ Object Code │ (.o or .obj file)
└──────┬───────┘

[Linker] (Links library functions)

┌──────────────┐
│ Executable │ (.exe file)
│ [Link] │
└──────────────┘

Steps:
1.​ Write code: program.c
2.​ Preprocessing: Expands macros, includes headers
3.​ Compilation: Converts to assembly, then object code
4.​ Linking: Links with libraries
5.​ Execution: Run the .exe file

2.10 Types of Errors

1. Syntax Errors (Compile-time)


●​ Wrong grammar/syntax
●​ Detected by compiler
●​ Examples:
●​ Missing semicolon: printf("Hello")
●​ Wrong keyword: inte age;
●​ Unmatched braces: { printf("Hi");

2. Logical Errors (Runtime)


●​ Wrong logic
●​ Program runs but wrong output
●​ Examples:
●​ Wrong formula: area = 2 * r instead of area = 3.14 * r * r
●​ Infinite loop: for(i=1; i>=1; i++)
3. Runtime Errors
●​ Error during execution
●​ Examples:
●​ Division by zero
●​ Array index out of bounds
●​ Stack overflow

2.11 Files Generated in C Program Lifecycle

File Extension Description

Source File .c Original C code

Header File .h Contains function declarations

Preprocessed File .i After preprocessing

Assembly File .s Assembly code

Object File .o, .obj Machine code (not executable)

Executable File .exe (Windows), no ext (Linux) Final runnable program

UNIT III
3.1 History of C Language
●​ Developed by: Dennis Ritchie
●​ Year: 1972
●​ Place: Bell Laboratories, AT&T, USA
●​ Purpose: Develop UNIX Operating System
●​ Predecessor: B language (by Ken Thompson)

Evolution:

1960: ALGOL → 1963: CPL → 1967: BCPL → 1970: B → 1972: C

3.2 Why C?
Reasons to learn C:
1.​ Foundation: Base for C++, Java, C#
2.​ Fast: Compiled language
3.​ Portable: Write once, compile anywhere
4.​ System Programming: OS, Compilers, Drivers
5.​ Embedded Systems: Microcontrollers
6.​ Rich Library: Built-in functions
7.​ Structured: Modular programming
8.​ Middle-level: Low + High level features

3.3 Character Set

Basic Characters in C:
1.​ Alphabets: A-Z, a-z
2.​ Digits: 0-9
3.​ Special Symbols: ! @ # $ % ^ & * ( ) - _ = + [ ] { } ; : ' " < > , . ? / \ | ~
4.​ White Spaces: Space, Tab, Newline

3.4 Escape Sequences (Whitespace Characters)


Escape Sequence Meaning Example Output

Hello
\n New line
World

\t Horizontal tab Hello World

\b Backspace Helllo → Hello

\r Carriage return Returns to start of line

\ Backslash \

' Single quote '

" Double quote "

\0 Null character String terminator

\a Alert (beep) System beep

Example Code:

#include <stdio.h>
int main() {
printf("Hello\nWorld\n"); // New line
printf("Name:\tRahul\n"); // Tab
printf("Path: C:\\Users\n"); // Backslash
printf("He said, \"Hi\"\n"); // Quote

return 0;
}

Output:

Hello
World
Name: Rahul
Path: C:\Users
He said, "Hi"

3.5 Format Specifiers

Specifier Data Type Example

%d or %i int 25

%ld long int 123456789

%f float 3.14
%lf double 3.14159265

%c char 'A'

%s string "Hello"

%u unsigned int 50

%o octal 77

%x hexadecimal (lowercase) 2f

%X hexadecimal (uppercase) 2F

%p pointer 0x7fff5fbff

%% print % %

Example Code:
c

#include <stdio.h>

int main() {
int age = 20;
float marks = 85.5;
char grade = 'A';
char name[] = "Rahul";

printf("Age: %d\n", age);


printf("Marks: %.2f\n", marks); // 2 decimal places
printf("Grade: %c\n", grade);
printf("Name: %s\n", name);
printf("Percentage: 85%%\n"); // Print %

return 0;
}

Output:

Age: 20
Marks: 85.50
Grade: A
Name: Rahul
Percentage: 85%

3.6 Tokens in C
Definition: Smallest individual unit in C program

Types of Tokens:
1.​ Keywords
2.​ Identifiers
3.​ Constants
4.​ Strings
5.​ Special Symbols
6.​ Operators

3.7 Keywords
Definition: Reserved words with predefined meaning
Total: 32 keywords
>>

auto break case char const continue


default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
volatile while

Rules:
●​ Cannot be used as variable names
●​ Always lowercase
●​ Have special meaning

3.8 Variables
Definition: Named memory location to store data

Syntax:
c

data_type variable_name;

Declaration:
c

int age;
float salary;
char grade;

Initialization:
c

int age = 25;


float salary = 50000.50;
char grade = 'A';
Multiple Declaration:
c

int a, b, c;
int x = 10, y = 20, z = 30;

Example Code:
c

#include <stdio.h>

int main() {
int age;
float salary;
char grade;

age = 25;
salary = 45000.75;
grade = 'B';

printf("Age: %d\n", age);


printf("Salary: %.2f\n", salary);
printf("Grade: %c\n", grade);

return 0;
}

3.9 Constants
Definition: Fixed value that cannot be changed during program execution

Types:
1. Integer Constants
c

int a = 10; // Decimal


int b = 010; // Octal (starts with 0)
int c = 0x10; // Hexadecimal (starts with 0x)

2. Floating-point Constants
c

float pi = 3.14;
double e = 2.71828;

3. Character Constants
c

char ch = 'A';
char newline = '\n';

4. String Constants
c

char name[] = "Rahul Kumar";

5. Symbolic Constants
c

#define PI 3.14
#define MAX 100

const int MIN = 10;

Example Code:
c

#include <stdio.h>
#define PI 3.14

int main() {
const int MAX = 100;

printf("PI = %.2f\n", PI);


printf("MAX = %d\n", MAX);

// PI = 3.15; // Error: cannot modify


// MAX = 200; // Error: cannot modify

return 0;
}

3.10 Identifiers
Definition: Names given to variables, functions, arrays, etc.

Rules:
1.​ Can contain: letters, digits, underscore (_)
2.​ Must start with: letter or underscore
3.​ Cannot start with: digit
4.​ Cannot be: keyword
5.​ Case-sensitive: age ≠ Age
6.​ No spaces allowed
Valid Identifiers:
c

age
_name
roll123
student_name
totalMarks
Invalid Identifiers:
c

2age // starts with digit


roll-no // contains hyphen
int // keyword
student name // contains space

3.11 Special Symbols

Symbol Name Use

{} Braces Block of code

() Parentheses Function calls, expressions

[] Brackets Arrays

, Comma Separate variables

; Semicolon End of statement

# Hash Preprocessor directive

* Asterisk Pointer, multiplication


& Ampersand Address operator, AND

3.12 Header Files


Definition: Files containing function declarations and macros

Syntax:
c

#include <header_file.h> // System header


#include "header_file.h" // User-defined header

Common Header Files:

Header File Purpose Functions

stdio.h Standard Input/Output printf(), scanf(), gets(), puts()

conio.h Console I/O getch(), clrscr()

math.h Mathematics sqrt(), pow(), sin(), cos()

string.h String handling strlen(), strcpy(), strcmp()

stdlib.h Standard library malloc(), free(), exit()


time.h Date and time time(), clock()

ctype.h Character type isalpha(), isdigit(), toupper()

Example Code:
c

#include <stdio.h>
#include <math.h>
#include <string.h>

int main() {
// math.h functions
printf("Square root of 16: %.2f\n", sqrt(16));
printf("2 power 3: %.2f\n", pow(2, 3));

// string.h functions
char name[] = "Hello";
printf("Length: %d\n", strlen(name));

return 0;
}

Output:
>>

Square root of 16: 4.00


2 power 3: 8.00
Length: 5

3.13 Data Types


Basic Data Types:

Data Type Size Range Format

char 1 byte -128 to 127 %c

unsigned char 1 byte 0 to 255 %c

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 8 bytes Large range %ld

float 4 bytes 6 decimal precision %f

double 8 bytes 15 decimal precision %lf

long double 16 bytes 19 decimal precision %Lf

Example Code:
c

#include <stdio.h>
int main() {
char ch = 'A';
int age = 25;
float marks = 85.5;
double salary = 50000.75;

printf("Size of char: %d byte\n", sizeof(char));


printf("Size of int: %d bytes\n", sizeof(int));
printf("Size of float: %d bytes\n", sizeof(float));
printf("Size of double: %d bytes\n", sizeof(double));

return 0;
}

Output:
>>

Size of char: 1 byte


Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes

3.14 Type Casting


Definition: Converting one data type to another

Types:

1. Implicit Type Casting (Automatic)


c

#include <stdio.h>

int main() {
int a = 10;
float b = 5.5;
float result;

result = a + b; // int automatically converted to float


printf("Result: %.2f\n", result); // 15.50

return 0;
}

2. Explicit Type Casting (Manual)


c

#include <stdio.h>

int main() {
int a = 10, b = 3;
float result;

// Without casting
result = a / b;
printf("Without casting: %.2f\n", result); // 3.00

// With casting
result = (float)a / b;
printf("With casting: %.2f\n", result); // 3.33

return 0;
}

Output:
>>

Without casting: 3.00


With casting: 3.33
3.15 Operators and Expressions

1. Arithmetic Operators
c

#include <stdio.h>

int main() {
int a = 10, b = 3;

printf("Addition: %d\n", a + b); // 13


printf("Subtraction: %d\n", a - b); // 7
printf("Multiplication: %d\n", a * b); // 30
printf("Division: %d\n", a / b); // 3
printf("Modulus: %d\n", a % b); // 1

return 0;
}

2. Relational Operators
c

#include <stdio.h>

int main() {
int a = 5, b = 10;

printf("%d == %d: %d\n", a, b, a == b); // 0 (false)


printf("%d != %d: %d\n", a, b, a != b); // 1 (true)
printf("%d < %d: %d\n", a, b, a < b); // 1 (true)
printf("%d > %d: %d\n", a, b, a > b); // 0 (false)
printf("%d <= %d: %d\n", a, b, a <= b); // 1 (true)
printf("%d >= %d: %d\n", a, b, a >= b); // 0 (false)

return 0;
}

3. Logical Operators
c

#include <stdio.h>

int main() {
int a = 1, b = 0;

printf("a && b: %d\n", a && b); // 0 (AND)


printf("a || b: %d\n", a || b); // 1 (OR)
printf("!a: %d\n", !a); // 0 (NOT)

return 0;
}

4. Increment/Decrement Operators
c

#include <stdio.h>

int main() {
int a = 5;

printf("a = %d\n", a); // 5


printf("a++ = %d\n", a++); // 5 (post-increment)
printf("a = %d\n", a); // 6

printf("++a = %d\n", ++a); // 7 (pre-increment)


printf("a = %d\n", a); // 7

printf("a-- = %d\n", a--); // 7 (post-decrement)


printf("a = %d\n", a); // 6

printf("--a = %d\n", --a); // 5 (pre-decrement)


printf("a = %d\n", a); // 5

return 0;
}

5. Assignment Operators
c

#include <stdio.h>

int main() {
int a = 10;

a += 5; // a = a + 5
printf("a += 5: %d\n", a); // 15

a -= 3; // a = a - 3
printf("a -= 3: %d\n", a); // 12

a *= 2; // a = a * 2
printf("a *= 2: %d\n", a); // 24

a /= 4; // a = a / 4
printf("a /= 4: %d\n", a); // 6

a %= 5; // a = a % 5
printf("a %%= 5: %d\n", a); // 1

return 0;
}

6. Bitwise Operators
c

#include <stdio.h>
int main() {
int a = 5, b = 3; // 5 = 0101, 3 = 0011

printf("a & b = %d\n", a & b); // 1 (AND: 0001)


printf("a | b = %d\n", a | b); // 7 (OR: 0111)
printf("a ^ b = %d\n", a ^ b); // 6 (XOR: 0110)
printf("~a = %d\n", ~a); // -6 (NOT)
printf("a << 1 = %d\n", a << 1); // 10 (Left shift)
printf("a >> 1 = %d\n", a >> 1); // 2 (Right shift)

return 0;
}

7. Conditional (Ternary) Operator


c

#include <stdio.h>

int main() {
int a = 10, b = 20;
int max;

max = (a > b) ? a : b;
printf("Maximum: %d\n", max); // 20

return 0;
}

8. Special Operators
sizeof() Operator:
c

#include <stdio.h>

int main() {
printf("Size of int: %d bytes\n", sizeof(int));
printf("Size of float: %d bytes\n", sizeof(float));
printf("Size of char: %d byte\n", sizeof(char));

return 0;
}

Comma Operator:
c

#include <stdio.h>

int main() {
int a, b, c;

a = (b = 5, c = 10, b + c);
printf("a = %d\n", a); // 15

return 0;
}

3.16 Precedence and Associativity

Operator Precedence Table:

Priority Operators Associativity

1 (Highest) ( ) [ ] -> . Left to Right

2 ! ~ ++ -- + - * & sizeof (unary) Right to Left


3 */% Left to Right

4 +- Left to Right

5 << >> Left to Right

6 < <= > >= Left to Right

7 == != Left to Right

8 & Left to Right

9 ^ Left to Right

10 | Left to Right

11 && Left to Right

12 || Left to Right

13 ?: Right to Left
14 (Lowest) = += -= *= /= %= etc. Right to Left

Example:
c

#include <stdio.h>

int main() {
int result;

result = 2 + 3 * 4;
printf("2 + 3 * 4 = %d\n", result); // 14 (not 20)

result = (2 + 3) * 4;
printf("(2 + 3) * 4 = %d\n", result); // 20

return 0;
}

3.17 Decision Making Statements

Conditional Statements:

1. if Statement
c

#include <stdio.h>

int main() {
int age;
printf("Enter age: ");
scanf("%d", &age);

if (age >= 18) {


printf("You can vote!\n");
}

return 0;
}

2. if-else Statement
c

#include <stdio.h>

int main() {
int num;
printf("Enter number: ");
scanf("%d", &num);

if (num % 2 == 0) {
printf("%d is EVEN\n", num);
} else {
printf("%d is ODD\n", num);
}

return 0;
}

3. if-else-if Ladder
c

#include <stdio.h>

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

if (marks >= 90) {


printf("Grade A\n");
} else if (marks >= 80) {
printf("Grade B\n");
} else if (marks >= 70) {
printf("Grade C\n");
} else if (marks >= 60) {
printf("Grade D\n");
} else {
printf("Grade F\n");
}

return 0;
}

4. Nested if
c

#include <stdio.h>

int main() {
int age;
char gender;

printf("Enter age: ");


scanf("%d", &age);
printf("Enter gender (M/F): ");
scanf(" %c", &gender);

if (age >= 18) {


if (gender == 'M') {
printf("Eligible for Army\n");
} else {
printf("Eligible for voting only\n");
}
} else {
printf("Not eligible\n");
}
return 0;
}

5. switch Statement
c

#include <stdio.h>

int main() {
int choice;

printf("Menu:\n");
printf("1. Tea\n");
printf("2. Coffee\n");
printf("3. Juice\n");
printf("Enter choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("You ordered Tea\n");
break;
case 2:
printf("You ordered Coffee\n");
break;
case 3:
printf("You ordered Juice\n");
break;
default:
printf("Invalid choice!\n");
}

return 0;
}
Unconditional Statements:

1. goto Statement
c

#include <stdio.h>

int main() {
int num;

input:
printf("Enter positive number: ");
scanf("%d", &num);

if (num < 0) {
printf("Invalid! Try again.\n");
goto input;
}

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

return 0;
}

2. break Statement
c

#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // Exit loop when i = 6
}
printf("%d ", i);
}
return 0;
}

Output: 1 2 3 4 5

3. continue Statement
c

#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}

return 0;
}

Output: 1 3 5 7 9

3.18 Roots of Quadratic Equation


Equation: ax² + bx + c = 0

Formula:
●​ Discriminant (D) = b² - 4ac
●​ If D > 0: Two real and distinct roots
●​ If D = 0: Two real and equal roots
●​ If D < 0: Complex roots
Roots:
●​ root1 = (-b + √D) / 2a
●​ root2 = (-b - √D) / 2a
Code:
c

#include <stdio.h>
#include <math.h>

int main() {
float a, b, c, D, root1, root2, real, imag;

printf("Enter a, b, c: ");
scanf("%f %f %f", &a, &b, &c);

D = b*b - 4*a*c;

if (D > 0) {
root1 = (-b + sqrt(D)) / (2*a);
root2 = (-b - sqrt(D)) / (2*a);
printf("Roots are real and distinct\n");
printf("Root 1 = %.2f\n", root1);
printf("Root 2 = %.2f\n", root2);
}
else if (D == 0) {
root1 = root2 = -b / (2*a);
printf("Roots are real and equal\n");
printf("Root 1 = Root 2 = %.2f\n", root1);
}
else {
real = -b / (2*a);
imag = sqrt(-D) / (2*a);
printf("Roots are complex\n");
printf("Root 1 = %.2f + %.2fi\n", real, imag);
printf("Root 2 = %.2f - %.2fi\n", real, imag);
}

return 0;
}
3.19 Loops

1. for Loop
Syntax:
c

for (initialization; condition; increment/decrement) {


// statements
}

Example 1: Print 1 to 10
c

#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {
printf("%d ", i);
}
return 0;
}

Example 2: Sum of N numbers


c

#include <stdio.h>

int main() {
int n, sum = 0;
printf("Enter n: ");
scanf("%d", &n);

for (int i = 1; i <= n; i++) {


sum += i;
}
printf("Sum = %d\n", sum);
return 0;
}

Example 3: Multiplication Table


c

#include <stdio.h>

int main() {
int num;
printf("Enter number: ");
scanf("%d", &num);

for (int i = 1; i <= 10; i++) {


printf("%d x %d = %d\n", num, i, num*i);
}

return 0;
}

Example 4: Factorial
c

#include <stdio.h>

int main() {
int n;
long long fact = 1;

printf("Enter number: ");


scanf("%d", &n);

for (int i = 1; i <= n; i++) {


fact *= i;
}
printf("Factorial = %lld\n", fact);
return 0;
}

2. while Loop
Syntax:
c

initialization;
while (condition) {
// statements
increment/decrement;
}

Example 1: Print 1 to 5
c

#include <stdio.h>

int main() {
int i = 1;

while (i <= 5) {
printf("%d ", i);
i++;
}

return 0;
}

Example 2: Sum of Digits


c

#include <stdio.h>
int main() {
int num, sum = 0, digit;

printf("Enter number: ");


scanf("%d", &num);

while (num > 0) {


digit = num % 10;
sum += digit;
num = num / 10;
}

printf("Sum of digits = %d\n", sum);


return 0;
}

Example 3: Reverse Number


c

#include <stdio.h>

int main() {
int num, rev = 0, digit;

printf("Enter number: ");


scanf("%d", &num);

while (num > 0) {


digit = num % 10;
rev = rev * 10 + digit;
num = num / 10;
}

printf("Reversed number = %d\n", rev);


return 0;
}
Example 4: Palindrome Check
c

#include <stdio.h>

int main() {
int num, original, rev = 0, digit;

printf("Enter number: ");


scanf("%d", &num);

original = num;

while (num > 0) {


digit = num % 10;
rev = rev * 10 + digit;
num = num / 10;
}

if (original == rev) {
printf("%d is a Palindrome\n", original);
} else {
printf("%d is NOT a Palindrome\n", original);
}

return 0;
}

3. do-while Loop
Syntax:
c

initialization;
do {
// statements
increment/decrement;
} while (condition);

Example 1: Menu Driven Program


c

#include <stdio.h>

int main() {
int choice;

do {
printf("\nMenu:\n");
printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Addition selected\n");
break;
case 2:
printf("Subtraction selected\n");
break;
case 3:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 3);

return 0;
}
Nested Loops
Example 1: Square Pattern
c

#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}

Output:
>>

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

Example 2: Right Triangle


c

#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}

Output:
>>

*
* *
* * *
* * * *
* * * * *

Example 3: Inverted Triangle


c

#include <stdio.h>

int main() {
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}

Output:
>>

* * * * *
* * * *
* * *
* *
*
Example 4: Number Pyramid
c

#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}

Output:
>>

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

3.20 Arrays
Definition: Collection of similar data type elements stored in contiguous memory.

1. Single Dimensional Array


Declaration:
c

data_type array_name[size];
Example 1: Basic Array
c

#include <stdio.h>

int main() {
int marks[5] = {85, 90, 78, 92, 88};

printf("Marks:\n");
for (int i = 0; i < 5; i++) {
printf("Student %d: %d\n", i+1, marks[i]);
}

return 0;
}

Example 2: Array Input/Output


c

#include <stdio.h>

int main() {
int n, arr[100];

printf("Enter size: ");


scanf("%d", &n);

printf("Enter %d elements:\n", n);


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Array elements:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}

Example 3: Sum of Array Elements


c

#include <stdio.h>

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

for (int i = 0; i < n; i++) {


sum += arr[i];
}

printf("Sum = %d\n", sum);


printf("Average = %.2f\n", (float)sum/n);

return 0;
}

Example 4: Find Largest and Smallest


c

#include <stdio.h>

int main() {
int arr[] = {45, 23, 78, 12, 90, 56};
int n = 6;
int max = arr[0], min = arr[0];

for (int i = 1; i < n; i++) {


if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}

printf("Largest = %d\n", max);


printf("Smallest = %d\n", min);

return 0;
}

2. Multidimensional Array (2D Array)


Declaration:
c

data_type array_name[rows][columns];

Example 1: 2D Array
c

#include <stdio.h>

int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

printf("Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}

Example 2: Matrix Addition


c

#include <stdio.h>

int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int sum[2][2];

// Addition
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}

// Display
printf("Sum Matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}

return 0;
}

3.21 Strings
Definition: Array of characters terminated by '\0' (null character)
Declaration:
c

char string_name[size];

Example 1: String Input/Output


c

#include <stdio.h>

int main() {
char name[50];

printf("Enter name: ");


scanf("%s", name); // Reads until space

printf("Name: %s\n", name);

return 0;
}

Example 2: String with spaces


c

#include <stdio.h>

int main() {
char name[50];

printf("Enter full name: ");


scanf(" %[^\n]", name); // Reads entire line

printf("Name: %s\n", name);

return 0;
}
3.22 Standard String Functions
Header: #include <string.h>

1. strlen() - String Length


c

#include <stdio.h>
#include <string.h>

int main() {
char str[] = "Hello";

printf("Length = %d\n", strlen(str)); // 5

return 0;
}

2. strcpy() - String Copy


c

#include <stdio.h>
#include <string.h>

int main() {
char src[] = "Hello";
char dest[20];

strcpy(dest, src);

printf("Source: %s\n", src);


printf("Destination: %s\n", dest);

return 0;
}
3. strcat() - String Concatenation
c

#include <stdio.h>
#include <string.h>

int main() {
char str1[50] = "Hello ";
char str2[] = "World";

strcat(str1, str2);

printf("Result: %s\n", str1); // Hello World

return 0;
}

4. strcmp() - String Comparison


c

#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "World";

if (strcmp(str1, str2) == 0) {
printf("str1 and str2 are equal\n");
}

if (strcmp(str1, str3) != 0) {
printf("str1 and str3 are different\n");
}

return 0;
}

5. strlwr() - Convert to Lowercase


c

#include <stdio.h>
#include <string.h>

int main() {
char str[] = "HELLO";

strlwr(str);

printf("Lowercase: %s\n", str); // hello

return 0;
}

6. strupr() - Convert to Uppercase


c

#include <stdio.h>
#include <string.h>

int main() {
char str[] = "hello";

strupr(str);

printf("Uppercase: %s\n", str); // HELLO

return 0;
}

7. strrev() - Reverse String


c

#include <stdio.h>
#include <string.h>

int main() {
char str[] = "Hello";

strrev(str);

printf("Reversed: %s\n", str); // olleH

return 0;
}

3.23 Searching Algorithms

1. Linear Search
Logic: Check each element one by one
c

#include <stdio.h>

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

printf("Enter element to search: ");


scanf("%d", &key);

for (int i = 0; i < n; i++) {


if (arr[i] == key) {
printf("Element found at position %d\n", i+1);
found = 1;
break;
}
}

if (!found) {
printf("Element not found\n");
}

return 0;
}

Time Complexity: O(n)

2. Binary Search
Logic: Divide and conquer (Array must be sorted)
c

#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50, 60, 70};
int n = 7, key, low = 0, high = n-1, mid;
int found = 0;

printf("Enter element to search: ");


scanf("%d", &key);

while (low <= high) {


mid = (low + high) / 2;

if (arr[mid] == key) {
printf("Element found at position %d\n", mid+1);
found = 1;
break;
}
else if (arr[mid] < key) {
low = mid + 1;
}
else {
high = mid - 1;
}
}

if (!found) {
printf("Element not found\n");
}

return 0;
}

Time Complexity: O(log n)

3.24 Sorting Algorithms

Bubble Sort
Logic: Compare adjacent elements and swap if wrong order
c

#include <stdio.h>

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = 7;

printf("Original Array: ");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

// Bubble Sort
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

printf("\nSorted Array: ");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}

Output:
>>

Original Array: 64 34 25 12 22 11 90
Sorted Array: 11 12 22 25 34 64 90

Time Complexity: O(n²)

UNIT IV – Advanced C Programming


4.1 Functions
Definition: Block of code that performs specific task

Need of Functions:
1.​ Code Reusability
2.​ Modularity
3.​ Easy Debugging
4.​ Easy Maintenance

Types of Functions:

1. Function with no arguments and no return value


c

#include <stdio.h>

void greet() {
printf("Hello, Welcome to C Programming!\n");
}

int main() {
greet(); // Function call
return 0;
}

2. Function with arguments but no return value


c

#include <stdio.h>

void add(int a, int b) {


int sum = a + b;
printf("Sum = %d\n", sum);
}

int main() {
add(10, 20);
add(50, 75);
return 0;
}
3. Function with no arguments but return value
c

#include <stdio.h>

int getNumber() {
return 100;
}

int main() {
int num = getNumber();
printf("Number = %d\n", num);
return 0;
}

4. Function with arguments and return value


c

#include <stdio.h>

int add(int a, int b) {


return a + b;
}

int main() {
int result = add(10, 20);
printf("Sum = %d\n", result);
return 0;
}

4.2 Call by Value


Definition: Copy of actual parameter is passed
c

#include <stdio.h>

void swap(int a, int b) {


int temp = a;
a = b;
b = temp;
printf("Inside function: a = %d, b = %d\n", a, b);
}

int main() {
int x = 10, y = 20;

printf("Before swap: x = %d, y = %d\n", x, y);


swap(x, y);
printf("After swap: x = %d, y = %d\n", x, y);

return 0;
}

Output:
>>

Before swap: x = 10, y = 20


Inside function: a = 20, b = 10
After swap: x = 10, y = 20

Note: Original values NOT changed

4.3 Call by Reference


Definition: Address of actual parameter is passed
c

#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
printf("Inside function: a = %d, b = %d\n", *a, *b);
}

int main() {
int x = 10, y = 20;

printf("Before swap: x = %d, y = %d\n", x, y);


swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);

return 0;
}

Output:
>>

Before swap: x = 10, y = 20


Inside function: a = 20, b = 10
After swap: x = 20, y = 10

Note: Original values ARE changed

4.4 Console Input-Output Functions

1. Formatted I/O
printf():
c

printf("format specifier", variables);


scanf():
c

scanf("format specifier", &variables);

2. Character I/O
getch() - Get character (no echo)
c

#include <stdio.h>
#include <conio.h>

int main() {
char ch;
printf("Press any key: ");
ch = getch(); // No display on screen
printf("\nYou pressed: %c\n", ch);
return 0;
}

getche() - Get character (with echo)


c

#include <stdio.h>
#include <conio.h>

int main() {
char ch;
printf("Press any key: ");
ch = getche(); // Displays on screen
printf("\nYou pressed: %c\n", ch);
return 0;
}

getchar() - Get character


c

#include <stdio.h>

int main() {
char ch;
printf("Enter character: ");
ch = getchar();
printf("You entered: %c\n", ch);
return 0;
}

putchar() - Put character


c

#include <stdio.h>

int main() {
char ch = 'A';
putchar(ch);
return 0;
}

3. String I/O
gets() - Get string
c

#include <stdio.h>

int main() {
char name[50];
printf("Enter name: ");
gets(name);
printf("Name: %s\n", name);
return 0;
}
puts() - Put string
c

#include <stdio.h>

int main() {
char name[] = "Hello World";
puts(name);
return 0;
}

4.5 Preprocessor Directives


Definition: Instructions to compiler before compilation

Types:

1. #include - Include header files


c

#include <stdio.h> // System header


#include "myheader.h" // User header

2. #define - Define macros


c

#include <stdio.h>
#define PI 3.14
#define SQUARE(x) ((x) * (x))

int main() {
printf("PI = %.2f\n", PI);
printf("Square of 5 = %d\n", SQUARE(5));
return 0;
}
3. #undef - Undefine macro
c

#include <stdio.h>
#define MAX 100

int main() {
printf("MAX = %d\n", MAX);
#undef MAX
// #define MAX 200 // Can redefine now
return 0;
}

4. #ifdef, #ifndef - Conditional compilation


c

#include <stdio.h>
#define DEBUG

int main() {
#ifdef DEBUG
printf("Debug mode ON\n");
#endif

#ifndef RELEASE
printf("Not in release mode\n");
#endif

return 0;
}

4.6 Storage Classes


1. auto (Automatic)
c

#include <stdio.h>

void function() {
auto int x = 10; // 'auto' is default
printf("x = %d\n", x);
}

int main() {
function();
function(); // x created again
return 0;
}

Properties:
●​ Scope: Local
●​ Lifetime: Until block ends
●​ Default value: Garbage
●​ Keyword: auto (optional)

2. static
c

#include <stdio.h>

void counter() {
static int count = 0; // Initialized only once
count++;
printf("Count = %d\n", count);
}

int main() {
counter(); // Count = 1
counter(); // Count = 2
counter(); // Count = 3
return 0;
}

Properties:
●​ Scope: Local
●​ Lifetime: Entire program
●​ Default value: 0
●​ Retains value between function calls

3. extern (External)
file1.c:
c

#include <stdio.h>

int globalVar = 100; // Global variable

void display() {
printf("Global Var = %d\n", globalVar);
}

file2.c:
c

#include <stdio.h>

extern int globalVar; // Declaration

int main() {
printf("Global Var = %d\n", globalVar);
return 0;
}

Properties:
●​ Scope: Global
●​ Lifetime: Entire program
●​ Default value: 0
●​ Accessible in multiple files

4. register
c

#include <stdio.h>

int main() {
register int i;

for (i = 1; i <= 10; i++) {


printf("%d ", i);
}

return 0;
}

Properties:
●​ Scope: Local
●​ Lifetime: Until block ends
●​ Storage: CPU register (if available)
●​ Faster access
●​ Cannot use & (address operator)

4.7 Recursion
Definition: Function calling itself

Factorial using Recursion


c

#include <stdio.h>

int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive call
}

int main() {
int num = 5;
printf("Factorial of %d = %d\n", num, factorial(num));
return 0;
}

Output: Factorial of 5 = 120

Explanation:
>>

factorial(5) = 5 × factorial(4)
= 5 × 4 × factorial(3)
= 5 × 4 × 3 × factorial(2)
= 5 × 4 × 3 × 2 × factorial(1)
= 5 × 4 × 3 × 2 × 1
= 120

Fibonacci Series using Recursion


c

#include <stdio.h>

int fibonacci(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
return fibonacci(n-1) + fibonacci(n-2);
}

int main() {
int terms = 10;

printf("Fibonacci Series: ");


for (int i = 0; i < terms; i++) {
printf("%d ", fibonacci(i));
}

return 0;
}

Output: Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

Ackermann Function
c

#include <stdio.h>

int ackermann(int m, int n) {


if (m == 0) {
return n + 1;
}
else if (m > 0 && n == 0) {
return ackermann(m - 1, 1);
}
else {
return ackermann(m - 1, ackermann(m, n - 1));
}
}

int main() {
int m = 2, n = 3;
printf("Ackermann(%d, %d) = %d\n", m, n, ackermann(m, n));
return 0;
}

4.8 Structure
Definition: User-defined data type to group different data types

Basic Structure
c

#include <stdio.h>

struct Student {
int roll;
char name[50];
float marks;
};

int main() {
struct Student s1;

[Link] = 101;
strcpy([Link], "Rahul");
[Link] = 85.5;

printf("Roll: %d\n", [Link]);


printf("Name: %s\n", [Link]);
printf("Marks: %.2f\n", [Link]);

return 0;
}

Passing Structure to Function


1. Pass by Value:
c

#include <stdio.h>

struct Student {
int roll;
char name[50];
float marks;
};

void display(struct Student s) {


printf("Roll: %d\n", [Link]);
printf("Name: %s\n", [Link]);
printf("Marks: %.2f\n", [Link]);
}

int main() {
struct Student s1 = {101, "Rahul", 85.5};
display(s1);
return 0;
}

2. Pass by Reference:
c

#include <stdio.h>

struct Student {
int roll;
char name[50];
float marks;
};

void update(struct Student *s) {


s->marks = 95.0; // Arrow operator
}
int main() {
struct Student s1 = {101, "Rahul", 85.5};

printf("Before: %.2f\n", [Link]);


update(&s1);
printf("After: %.2f\n", [Link]);

return 0;
}

4.9 Union
Definition: Similar to structure but shares same memory
c

#include <stdio.h>

union Data {
int i;
float f;
char c;
};

int main() {
union Data d;

printf("Size of union: %d bytes\n", sizeof(d));

d.i = 10;
printf("d.i = %d\n", d.i);

d.f = 220.5;
printf("d.f = %.2f\n", d.f);
printf("d.i = %d (garbage)\n", d.i); // Overwritten

return 0;
}

Difference: Structure vs Union

Feature Structure Union

Memory Separate for each member Shared by all

Size Sum of all members Size of largest member

Access All simultaneously One at a time

4.10 Pointers
Definition: Variable that stores address of another variable

Basic Pointer
c

#include <stdio.h>

int main() {
int num = 10;
int *ptr;

ptr = &num; // Store address

printf("Value of num: %d\n", num);


printf("Address of num: %p\n", &num);
printf("Value of ptr: %p\n", ptr);
printf("Value at ptr: %d\n", *ptr); // Dereference
return 0;
}

Generic Pointer (void pointer)


c

#include <stdio.h>

int main() {
void *ptr;
int num = 10;
float f = 5.5;

ptr = &num;
printf("Integer: %d\n", *(int*)ptr);

ptr = &f;
printf("Float: %.2f\n", *(float*)ptr);

return 0;
}

4.11 Self-Referential Structure


Definition: Structure containing pointer to same structure type
c

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node *next; // Pointer to same type
};
int main() {
struct Node *node1 = (struct Node*)malloc(sizeof(struct
Node));
struct Node *node2 = (struct Node*)malloc(sizeof(struct
Node));

node1->data = 10;
node1->next = node2;

node2->data = 20;
node2->next = NULL;

printf("Node 1: %d\n", node1->data);


printf("Node 2: %d\n", node1->next->data);

return 0;
}

4.12 Linked List


Definition: Linear data structure where elements are not stored in contiguous
memory

Singly Linked List Operations


c

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node *next;
};

// Insert at beginning
void insertBegin(struct Node **head, int value) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct
Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}

// Display list
void display(struct Node *head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}

int main() {
struct Node *head = NULL;

insertBegin(&head, 30);
insertBegin(&head, 20);
insertBegin(&head, 10);

display(head);

return 0;
}

Output: 10 -> 20 -> 30 -> NULL

4.13 File Handling


Definition: Operations to read/write data from/to files

File Modes:
Mode Description

r Read (file must exist)

w Write (creates new or overwrites)

a Append (adds at end)

r+ Read and Write

w+ Write and Read (overwrites)

a+ Append and Read

Write to File
c

#include <stdio.h>

int main() {
FILE *fp;

fp = fopen("[Link]", "w");

if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(fp, "Hello World\n");
fprintf(fp, "File Handling in C\n");

fclose(fp);
printf("Data written to file successfully!\n");

return 0;
}

Read from File


c

#include <stdio.h>

int main() {
FILE *fp;
char line[100];

fp = fopen("[Link]", "r");

if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}

while (fgets(line, 100, fp) != NULL) {


printf("%s", line);
}

fclose(fp);

return 0;
}
File Functions:

Function Purpose

fopen() Open file

fclose() Close file

fgetc() Read single character

fputc() Write single character

fgets() Read string

fputs() Write string

fprintf() Write formatted data

fscanf() Read formatted data

feof() Check end of file


fseek() Move file pointer

ftell() Current position of pointer

rewind() Move pointer to beginning

4.14 Dynamic Memory Allocation

1. malloc() - Memory Allocation


c

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;
int n = 5;

ptr = (int*)malloc(n * sizeof(int));

if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

for (int i = 0; i < n; i++) {


ptr[i] = i + 1;
}

printf("Array elements: ");


for (int i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}

free(ptr);

return 0;
}

2. calloc() - Contiguous Allocation


c

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;
int n = 5;

ptr = (int*)calloc(n, sizeof(int)); // Initializes to 0

if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

printf("Array elements: ");


for (int i = 0; i < n; i++) {
printf("%d ", ptr[i]); // All zeros
}

free(ptr);

return 0;
}
3. realloc() - Reallocate Memory
c

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;
int n = 5;

ptr = (int*)malloc(n * sizeof(int));

for (int i = 0; i < n; i++) {


ptr[i] = i + 1;
}

// Resize to 10 elements
n = 10;
ptr = (int*)realloc(ptr, n * sizeof(int));

for (int i = 5; i < n; i++) {


ptr[i] = i + 1;
}

printf("Array elements: ");


for (int i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}

free(ptr);

return 0;
}

4. free() - Deallocate Memory


c

free(ptr); // Always free after use

4.15 Time and Space Complexity

Time Complexity
Definition: Amount of time algorithm takes to complete

Big-O Notation:

Complexity Name Example

O(1) Constant Accessing array element

O(log n) Logarithmic Binary search

O(n) Linear Linear search

O(n log n) Linearithmic Merge sort

O(n²) Quadratic Bubble sort

O(2ⁿ) Exponential Fibonacci recursion


Space Complexity
Definition: Amount of memory algorithm uses

Example 1: Constant Space O(1)


c

int sum(int a, int b) {


return a + b; // Only 2 variables
}

Example 2: Linear Space O(n)


c

int arr[n]; // Space depends on n

Analyzing Algorithms:
Linear Search:
●​ Time Complexity: O(n)
●​ Space Complexity: O(1)
Binary Search:
●​ Time Complexity: O(log n)
●​ Space Complexity: O(1)
Bubble Sort:
●​ Time Complexity: O(n²)
●​ Space Complexity: O(1)

Link of digital notes: [Link]

You might also like