0% found this document useful (0 votes)
7 views60 pages

Introduction To Programming and Problem Solving

The document provides an overview of the history of computers, detailing significant inventions and their contributions from the abacus to modern computing technologies. It discusses the generations of computers, their classifications, computer architecture, and number systems, highlighting key components and functionalities. The content serves as an introduction to programming and problem-solving in the context of computer science.

Uploaded by

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

Introduction To Programming and Problem Solving

The document provides an overview of the history of computers, detailing significant inventions and their contributions from the abacus to modern computing technologies. It discusses the generations of computers, their classifications, computer architecture, and number systems, highlighting key components and functionalities. The content serves as an introduction to programming and problem-solving in the context of computer science.

Uploaded by

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

INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING

CS101

1) History of Computers

Year /
S.N Device /
Inventor / Developer Perio Main Features / Contributions
o. Invention
d

1 Abacus Egyptians, Hindus, Arou Early counting device with rods


Year /
S.N Device /
Inventor / Developer Perio Main Features / Contributions
o. Invention
d

nd
and beads; used for addition and
Chinese, Greeks 300
subtraction based on place value.
BC

Used rods made of bones for


(155
multiplication; converted
Napier’s 0–
2 John Napier multiplication into addition using
Bones 1617
logarithms; inspired the Slide
AD)
Rule (1662).

First mechanical calculator for


Pascal’s addition and subtraction using
Blaise Pascal 1642
3 Adding toothed wheels; worked on
(French) AD
Machine clockwork mechanism; had
automatic carry-transfer.

Improved Pascal’s machine; could


Leibnitz’s Gottfried Wilhelm 1673 perform multiplication, division,
4
Calculator Leibnitz (German) AD and square roots using a stepped
cylinder.

Used punched cards to control


Jacquard’s
weaving patterns; represented
Loom with Marie Jacquard 1801
5 data storage using holes (0/1);
Punched (French) AD
introduced the idea of automation
Card
in machines.

Could calculate mathematical


functions (logarithms,
Difference Charles Babbage 1822
6 polynomials); results up to 20
Engine (English) AD
decimal places; known as
Mechanical Calculator.

Designed as a programmable
mechanical computer; had
Charles Babbage
Analytical 1833 processor, memory, input/output
7 (assisted by Lady
Engine AD devices; used punched cards;
Ada Lovelace)
basis of modern computers; Ada
Lovelace is the First Programmer.

Used punched cards for U.S.


Hollerith’s Herman Hollerith 1877 Census data; reduced processing
8
Card Reader (American) AD time from 10 to 3 years; founded
company later known as IBM.
Year /
S.N Device /
Inventor / Developer Perio Main Features / Contributions
o. Invention
d

First electromechanical computer;


1937
performed automatic calculations;
Howard Aiken (with –
9 Mark I contained miles of wires and
IBM engineers) 1943
electromechanical relays; used
AD
preprogrammed instructions.

ENIAC
First electronic computer using
(Electronic
18,000 vacuum tubes; performed
Numerical Eckert and Mauchly 1946
10 fast calculations; used by U.S.
Integrator (USA) AD
Army; occupied 5000 sq. ft and
and
consumed 150,000 watts.
Calculator)

EDVAC
Introduced binary number system
(Electronic
and Von Neumann Architecture
Discrete Eckert and Mauchly 1949
11 (stored program concept);
Variable (USA) AD
operations became faster and
Automatic
more efficient.
Computer)

EDSAC
Used mercury delay lines for
(Electronic
Prof. M.V. Wilkes storage; implemented loop
Delay 1949
12 (Cambridge structures; based on binary
Storage AD
University) system and Von Neumann
Automatic
architecture.
Computer)

UNIVAC First commercial computer; used


(Universal Remington Rand 1951 by General Electric; applied in
13
Automatic Company (USA) AD science, engineering, and
Computer) business.

Made IBM the leader in computer


Thomas Watson Jr. 1955 technology; widely used for
14 IBM 650
and IBM Engineers AD business and scientific
applications.

Series of improved computers;


IBM 700
1955 each model had minor
15 Series (701, IBM Corporation
AD enhancements but no major
702, 703)
technological change.

(2)Generations of Computers
Generati Time
Technology Used Characteristics / Features Examples
on Period

- Very large in size-


First Consumed a lot of
1942–
Generati Vacuum Tubes electricity- Produced ENIAC, UNIVAC
1955
on excessive heat- Slow
processing speed

- Smaller and faster than


Second first generation- More
1955–
Generati Transistors reliable and energy IBM 1401
1964
on efficient- Consumed less
power

- More compact and


Third
1964– Integrated Circuits efficient- Faster
Generati IBM 360 Series
1975 (ICs) performance- Lower cost
on
and size

- Contained thousands of
circuits on a chip- Led to
Fourth
1975– personal computers and Apple II, IBM
Generati Microprocessors
1989 laptops- Supported PC
on
networking and
multitasking

Artificial - Capable of learning and


AI-powered
Fifth 1989– Intelligence (AI), decision-making- Natural
systems,
Generati Prese Machine Learning, language processing-
Supercompute
on nt Quantum High-speed and complex
rs
Computing problem-solving

(3)Classification of computers
Type Category Description / Features Examples

Deal with continuous data such as


temperature, pressure, or speed.
Based on Speedometer in
1. Analog Work with signals instead of
Data a car, Flight
Computers numbers. Commonly used in
Type simulators
scientific and engineering
applications.

Work with binary digits (0 and 1).


Based on
2. Digital Fast, reliable, and accurate. Most PCs, Laptops,
Data
Computers commonly used in homes, schools, Smartphones
Type
and offices.

Combine the features of analog and


Based on ECG and CT
3. Hybrid digital computers. Can process both
Data scan systems in
Computers signals and numbers. Used in
Type hospitals
medical and scientific research.

4. Based on Small, single-user computers.


Desktop PCs,
Microcomput Size and Affordable and portable; ideal for
Laptops
ers Power personal or office use.

Medium-sized computers supporting


5. Based on
multiple users simultaneously. Used
Minicompute Size and DEC PDP Series
in businesses and laboratories
rs Power
before PCs became advanced.

Very powerful systems capable of


Based on
6. Mainframe handling thousands of users and IBM Mainframe
Size and
Computers vast data processing. Used in banks, Systems
Power
railways, and large organizations.

Fastest and most powerful


PARAM (India),
7. Based on computers in the world. Used for
Cray
Supercomput Size and complex calculations, weather
Supercomputer
ers Power forecasting, scientific simulations,
s
and space research.

3. Computer Architecture

Computer architecture refers to the design, structure, and organization of computer system
components and their interconnections.
Von Neumann Architecture (Stored Program Concept)

The fundamental architecture of modern computers, proposed by John von Neumann in 1945.

Key Components:

A. Input/Output Units

Input Units

 Function: Accept data and instructions from external sources

 Process: Convert human-readable data into computer-readable format

 Common Input Devices:

 Keyboard: Character and command input

 Mouse: Pointing and clicking

 Scanner: Convert physical documents to digital

 Microphone: Audio input

 Webcam: Video/image input

 Touch screen: Direct interaction

 Barcode reader: Product identification

 Joystick: Gaming input

 Digital camera: Image capture

 Biometric devices: Fingerprint, retina scanners

Output Units

 Function: Present processed data to users

 Process: Convert computer-readable data into human-readable format

 Common Output Devices:

 Monitor/Display: Visual output (LED, LCD, OLED)

 Printer: Hard copy output (Inkjet, Laser, 3D)

 Speakers: Audio output

 Projector: Large-screen display

 Plotter: High-precision drawings

 Headphones: Personal audio output

B. Memory Units

Primary Memory (Main Memory)

1. RAM (Random Access Memory)


 Type: Volatile memory (data lost when power off)

 Characteristics:

 Fast access time (nanoseconds)

 Directly accessible by CPU

 Temporary storage

 Read and write operations

 Types:

 SRAM (Static RAM):

 Faster, more expensive

 Used for cache memory

 No refresh required

 DRAM (Dynamic RAM):

 Slower, cheaper

 Used for main memory

 Requires periodic refresh

 Variants: DDR, DDR2, DDR3, DDR4, DDR5

2. ROM (Read-Only Memory)

 Type: Non-volatile memory (retains data without power)

 Characteristics:

 Permanent storage

 Contains boot instructions (BIOS/UEFI)

 Cannot be easily modified

 Types:

 PROM (Programmable ROM): One-time programmable

 EPROM (Erasable PROM): UV light erasable

 EEPROM (Electrically Erasable PROM): Electrically erasable

 Flash Memory: Modern EEPROM variant

3. Cache Memory:

 Purpose: Bridge speed gap between CPU and RAM

 Characteristics:
 Extremely fast (SRAM-based)

 Small capacity

 Stores frequently accessed data

 Levels:

 L1 Cache: Closest to CPU, smallest (KB range), fastest

 L2 Cache: Larger than L1 (MB range), slightly slower

 L3 Cache: Shared among cores, largest (MB range)

Secondary Memory (Auxiliary Storage)

 Type: Non-volatile, permanent storage

 Characteristics:

 Large capacity

 Slower than primary memory

 Not directly accessible by CPU

 Stores programs and data permanently

Types:

1. Magnetic Storage

 Hard Disk Drive (HDD):

 Rotating magnetic platters

 Capacity: TB range

 Moderate speed

 Mechanical parts (can fail)

 Magnetic Tape:

 Sequential access

 Backup and archival storage

2. Solid State Storage:

 SSD (Solid State Drive):

 No moving parts (flash memory)

 Very fast access

 More expensive than HDD

 Capacity: GB to TB

 USB Flash Drive:


 Portable storage

 Plug-and-play

 GB range capacity

3. Optical Storage

 CD (Compact Disc): ~700 MB

 DVD (Digital Versatile Disc): 4.7-17 GB

 Blu-ray: 25-128 GB

 Read-only, recordable, or rewritable variants

Memory Hierarchy (Speed vs Capacity)

CPU Registers (Fastest, Smallest)

L1 Cache

L2 Cache

L3 Cache

Main Memory (RAM)

Secondary Storage (Slowest, Largest)

C. Central Processing Unit (CPU)

The "brain" of the computer that executes instructions.

Components:

1. Arithmetic Logic Unit (ALU):

 Function: Performs arithmetic and logical operations

 Arithmetic Operations:

 Addition (+)

 Subtraction (-)

 Multiplication (×)

 Division (÷)

 Logical Operations:
 AND, OR, NOT, XOR

 Comparisons (>, <, =, ≥, ≤, ≠)

 Output: Result and status flags (Zero, Carry, Overflow, Sign)

2. Control Unit (CU):

 Function: Directs and coordinates all computer operations

 Responsibilities:

 Fetch instructions from memory

 Decode instructions

 Execute instructions

 Control data flow between components

 Generate timing and control signals

 Does not: Perform actual computations (ALU's job)

3. Registers:

 Function: Small, fast storage locations within CPU

 Types:

 Program Counter (PC): Holds address of next instruction

 Instruction Register (IR): Holds current instruction

 Memory Address Register (MAR): Holds memory address

 Memory Data Register (MDR): Holds data from/to memory

 Accumulator (ACC): Stores intermediate results

 General Purpose Registers: Temporary data storage

 Status Register/Flags: Stores condition codes

CPU Operation Cycle (Fetch-Decode-Execute)

1. FETCH:

- PC provides address of next instruction

- Instruction fetched from memory to IR

- PC incremented

2. DECODE:

- CU decodes the instruction

- Determines operation and operands


3. EXECUTE:

- ALU performs operation

- Results stored in registers/memory

4. STORE:

- Results written back to memory if needed

(Cycle repeats)

Performance Factors

 Clock Speed: Measured in GHz (billions of cycles per second)

 Cores: Multiple processing units (dual, quad, octa-core)

 Cache Size: Larger cache = better performance

 Architecture: Instruction set (x86, ARM, RISC-V)

 Word Size: 32-bit vs 64-bit processing

System Bus:

The communication pathway connecting CPU, memory, and I/O devices.

Types:

i) Data Bus:

 Carries actual data

 Bi-directional

 Width determines word size (32-bit, 64-bit)

ii) Address Bus:

 Carries memory addresses

 Uni-directional (CPU to Memory)

 Width determines addressable memory (32-bit = 4GB max)

iii) Control Bus:

 Carries control signals

 Read/Write signals, clock signals, interrupt signals

 Bi-directional

4. Number Systems:
Number systems are mathematical notation systems for representing numbers using symbols and
rules.

A. Decimal Number System (Base 10)

 Base: 10

 Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

 Most common: Used in everyday life

 Place values: Powers of 10

Example: 5234₁₀

5234 = (5 × 10³) + (2 × 10²) + (3 × 10¹) + (4 × 10⁰)

= 5000 + 200 + 30 + 4

= 5234

B. Binary Number System (Base 2)

 Base: 2

 Digits: 0, 1 (called bits)

 Used by: All digital computers

 Place values: Powers of 2

 Why binary?:

 Easy to implement electronically (ON/OFF, HIGH/LOW voltage)

 Reliable and simple

 Compatible with Boolean algebra

Example: 1011₂

1011₂ = (1 × 2³) + (0 × 2²) + (1 × 2¹) + (1 × 2⁰)

=8+0+2+1

= 11₁₀

Terminology:

 Bit: Single binary digit (0 or 1)

 Nibble: 4 bits

 Byte: 8 bits

 Word: 16, 32, or 64 bits (depends on system)

C. Octal Number System (Base 8)

 Base: 8
 Digits: 0, 1, 2, 3, 4, 5, 6, 7

 Place values: Powers of 8

 Purpose: Shorthand for binary (easier to read/write)

 Conversion: 3 binary bits = 1 octal digit

Example: 157₈

157₈ = (1 × 8²) + (5 × 8¹) + (7 × 8⁰)

= 64 + 40 + 7

= 111₁₀

Binary to Octal Grouping:

Binary: 001 101 111

Octal: 1 5 7 = 157₈

D. Hexadecimal Number System (Base 16)

 Base: 16

 Digits: 0-9, A-F (A=10, B=11, C=12, D=13, E=14, F=15)

 Place values: Powers of 16

 Purpose: Compact representation of binary

 Usage: Memory addresses, color codes, assembly programming

 Conversion: 4 binary bits = 1 hex digit

Example: 2AF₁₆

2AF₁₆ = (2 × 16²) + (10 × 16¹) + (15 × 16⁰)

= 512 + 160 + 15

= 687₁₀

Binary to Hex Grouping:

Binary: 0010 1010 1111

Hex: 2 A F = 2AF₁₆

Comparison Table

System Base Digits Example Decimal Equivalent

Binary 2 0-1 1010₂ 10₁₀


System Base Digits Example Decimal Equivalent

Octal 8 0-7 12₈ 10₁₀

Decimal 10 0-9 10₁₀ 10₁₀

Hexadecimal 16 0-9, A-F A₁₆ 10₁₀

5. Number System Conversions:

A. Decimal to Binary

Method 1: Successive Division by 2

Divide by 2 and note remainders (read bottom to top).

Example: Convert 25₁₀ to binary

25 ÷ 2 = 12 remainder 1 ↑

12 ÷ 2 = 6 remainder 0 ↑

6 ÷ 2 = 3 remainder 0 ↑

3 ÷ 2 = 1 remainder 1 ↑

1 ÷ 2 = 0 remainder 1 ↑ (Read upward)

Answer: 11001₂

Method 2: Sum of Powers of 2

Find largest power of 2 ≤ number, subtract, repeat.

25 = 16 + 8 + 1

= 2⁴ + 2³ + 2⁰

= 11001₂

For Decimal Fractions:

Multiply by 2 and note integer part (read top to bottom).

Example: Convert 0.625₁₀ to binary

0.625 × 2 = 1.25 → 1 ↓

0.25 × 2 = 0.5 → 0 ↓ (Read downward)

0.5 × 2 = 1.0 → 1 ↓

Answer: 0.101₂
B. Binary to Decimal

Method: Multiply each bit by its positional value and sum.

Example: Convert 1011.101₂ to decimal

1 0 1 1 . 1 0 1

↓ ↓ ↓ ↓ ↓ ↓ ↓

2³ 2² 2¹ 2⁰ 2⁻¹ 2⁻² 2⁻³

8 4 2 1 0.5 0.25 0.125

= 8 + 0 + 2 + 1 + 0.5 + 0 + 0.125

= 11.625₁₀

C. Decimal to Octal:

Method: Successive division by 8

Example: Convert 127₁₀ to octal

127 ÷ 8 = 15 remainder 7 ↑

15 ÷ 8 = 1 remainder 7 ↑

1 ÷ 8 = 0 remainder 1 ↑

Answer: 177₈

D. Octal to Decimal:

Method: Multiply each digit by power of 8 and sum.

Example: Convert 177₈ to decimal

177₈ = (1 × 8²) + (7 × 8¹) + (7 × 8⁰)

= 64 + 56 + 7

= 127₁₀

E. Decimal to Hexadecimal:

Method: Successive division by 16

Example: Convert 254₁₀ to hexadecimal

254 ÷ 16 = 15 remainder 14 (E) ↑

15 ÷ 16 = 0 remainder 15 (F)

Answer: FE₁₆

F. Hexadecimal to Decimal:
Method: Multiply each digit by power of 16 and sum.

Example: Convert FE₁₆ to decimal

FE₁₆ = (15 × 16¹) + (14 × 16⁰)

= 240 + 14

= 254₁₀

G. Binary to Octal:

Method: Group binary digits in sets of 3 (from right), convert each group.

Example: Convert 111010110₂ to octal

Binary: 111 010 110

↓ ↓ ↓

Octal: 7 2 6

Answer: 726₈

Note: Add leading zeros if needed for complete groups.

H. Octal to Binary:

Method: Convert each octal digit to 3-bit binary.

Example: Convert 726₈ to binary

Octal: 7 2 6

↓ ↓ ↓

Binary: 111 010 110

Answer: 111010110₂

I. Binary to Hexadecimal:

Method: Group binary digits in sets of 4 (from right), convert each group.

Example: Convert 111010110₂ to hexadecimal

Binary: 0001 1101 0110

↓ ↓ ↓

Hex: 1 D 6

Answer: 1D6₁₆
J. Hexadecimal to Binary:

Method: Convert each hex digit to 4-bit binary.

Example: Convert 1D6₁₆ to binary

Hex: 1 D 6

↓ ↓ ↓

Binary:0001 1101 0110

Answer: 111010110₂

K. Octal to Hexadecimal (via Binary):

Method: Octal → Binary → Hexadecimal

Example: Convert 726₈ to hexadecimal

Step 1: Octal to Binary

726₈ = 111 010 110₂

Step 2: Binary to Hex

111010110₂ = 0001 1101 0110

= 1 D 6

= 1D6₁₆

L. Hexadecimal to Octal (via Binary):

Method: Hex → Binary → Octal

Example: Convert 1D6₁₆ to octal

Step 1: Hex to Binary

1D6₁₆ = 0001 1101 0110₂

Step 2: Binary to Octal

111010110₂ = 111 010 110

= 7 2 6

= 726₈

Quick Reference Table


Decimal Binary Octal Hexadecimal

0 0000 0 0

1 0001 1 1

2 0010 2 2

3 0011 3 3

4 0100 4 4

5 0101 5 5

6 0110 6 6

7 0111 7 7

8 1000 10 8

9 1001 11 9

10 1010 12 A

11 1011 13 B

12 1100 14 C

13 1101 15 D

14 1110 16 E

15 1111 17 F

6. Signed Number Representations:

In computer systems, we need to represent both positive and negative numbers. Several methods
exist:

A. Sign-Magnitude Representation

Concept: Use the leftmost bit (MSB) as sign bit

 0 = Positive

 1 = Negative

 Remaining bits represent magnitude

Example (8-bit):

+25₁₀ = 0 0011001

Sign bit (0 = positive)

-25₁₀ = 1 0011001
Sign bit (1 = negative)

Characteristics:

 Range (n bits): -(2ⁿ⁻¹ - 1) to +(2ⁿ⁻¹ - 1)

 8-bit range: -127 to +127

 Problems:

 Two representations of zero (+0 and -0)

 Addition/subtraction complex

 Not commonly used in modern computers

Examples:

+0 = 00000000

-0 = 10000000 (Two zeros!)

B. 1's Complement Representation

For Positive Numbers: Same as binary representation

For Negative Numbers: Invert all bits (0→1, 1→0)

Example (8-bit):

+25₁₀ = 00011001

-25₁₀ = 11100110 (Inverted bits)

Range (n bits): -(2ⁿ⁻¹ - 1) to +(2ⁿ⁻¹ - 1)

8-bit examples:

+127 = 01111111

+1 = 00000001

+0 = 00000000

-0 = 11111111 (Two zeros!)

-1 = 11111110

-127 = 10000000

Characteristics:

 Range (8-bit): -127 to +127

 Problem: Still has two zeros

 Advantage: Easy to negate (just flip bits)

 Disadvantage: Addition requires end-around carry

Addition Example:
+25: 00011001

+10: 00001010

───────────────

00100011 = +35 ✓

+25: 00011001

-10: 11110101

───────────────

1 00001110

+1 (end-around carry)

───────────────

00001111 = +15 ✓

C. 2's Complement Representation:

Most widely used method in modern computers.

For Positive Numbers: Same as binary

For Negative Numbers:

1. Find 1's complement (invert bits)

2. Add 1

Alternative Method:

 Start from right, copy bits until first 1 (inclusive)

 Invert remaining bits

Example (8-bit):

+25₁₀ = 00011001

-25₁₀:

Step 1: 1's complement = 11100110

Step 2: Add 1 = 11100111

Range (n bits): -2ⁿ⁻¹ to +(2ⁿ⁻¹ - 1)

8-bit examples:

+127 = 01111111

+1 = 00000001
+0 = 00000000 (Only one zero!)

-1 = 11111111

-25 = 11100111

-128 = 10000000

Characteristics:

 Range (8-bit): -128 to +127

 Advantage:

 Single representation of zero

 Simple addition/subtraction (no special cases)

 Most significant bit is sign bit

 Hardware implementation is simple

 Used in: All modern processors

How to Identify Sign:

MSB = 0 → Positive number

MSB = 1 → Negative number

To Convert Back to Decimal (if MSB = 1):

Method 1: Take 2's complement, convert, add negative sign

Method 2: Use weighted positions with MSB as -2⁷

Example: 11100111

= -(2⁷) + 2⁶ + 2⁵ + 0 + 0 + 1×2² + 2¹ + 2⁰

= -128 + 64 + 32 + 4 + 2 + 1

= -128 + 103 = -25₁₀

Arithmetic Operations:

Addition:

+25: 00011001

+10: 00001010

───────────────

00100011 = +35 ✓

+25: 00011001
-10: 11110110

───────────────

1 00001111 = +15 ✓ (ignore carry)

Subtraction (A - B = A + (-B)):

25 - 10 = 25 + (-10)

+25: 00011001

-10: 11110110

───────────────

1 00001111 = +15 ✓

Overflow Detection:

 Occurs when: Result exceeds representable range

 Detection: Carry into sign bit ≠ Carry out of sign bit

 Signs:

 Positive + Positive = Negative → Overflow

 Negative + Negative = Positive → Overflow

 Positive + Negative → Never overflow

Comparison of Methods

Method Range (8-bit) Zeros Addition Usage

Sign-Magnitude -127 to +127 Two Complex Rare

1's Complement -127 to +127 Two End-around carry Rare

2's Complement -128 to +127 One Simple Standard

7. Floating Point Representation:

Used to represent very large or very small numbers with decimal points.

Why Floating Point?

Fixed Point Limitations:

 Limited range

 Poor precision for very large/small numbers

 Example: Cannot efficiently represent 0.000000123 or 1,234,567,890,000


Floating Point Solution:

 Similar to scientific notation: 6.022 × 10²³

 Separates number into: Sign, Mantissa/Significand, Exponent

General Format:

± Number =¿

Example: -1.5 × 2⁵

IEEE 754 Standard


The IEEE 754 standard defines how floating-point numbers are stored in
binary.
There are mainly two formats used in computers:
 Single Precision (32 bits)
 Double Precision (64 bits)

(i) IEEE 754 Single Precision (32-bit) Format

Bit
Field Description
s

Determines the sign of the number.


Sign Bit 1 • 0 → Positive
• 1 → Negative

Used to store the exponent (after adding a


Exponent 8
bias of 127).

Mantissa Represents the fractional part (the digits


23
(Fraction) after the binary point).

Total = 1 + 8 + 23 = 32 bits
Bias = 127
Value Representation:

N=¿
Example:
Suppose we have a number stored as:
0 10000010 10100000000000000000000
 Sign bit (S) = 0 → Positive
 Exponent = 130 → Actual exponent = 130 − 127 = 3
 Mantissa = 1.101 (binary) = 1.625 (decimal)
So,
3
N=+ 1.625× 2 =13.0

(ii) IEEE 754 Double Precision (64-bit) Format

Bit
Field Description
s

0 = Positive, 1 =
Sign Bit 1
Negative

Exponent value (bias


Exponent 11
= 1023)

Mantissa Fractional part of the


52
(Fraction) number

Total = 1 + 11 + 52 = 64 bits
Bias = 1023
Value Representation:

N=¿
Example:
0 10000000010
0100000000000000000000000000000000000000000000000000
 S = 0 → Positive
 Exponent = 1026 → Actual exponent = 1026 − 1023 = 3
 Mantissa = 1.01 (binary) = 1.25 (decimal)
So,
3
N=+ 1.25× 2 =10.0

(8)ASCII Codes (American Standard Code for Information Interchange)


Introduction
ASCII stands for American Standard Code for Information Interchange.
It is a character encoding system used by computers and electronic
devices to represent text characters (letters, digits, symbols, and
control characters) using binary numbers.
Every character in ASCII has a unique numerical code ranging from 0 to
127 (7 bits).
Some extended versions use 8 bits (0–255), known as Extended ASCII.
Need for ASCII
Computers understand only binary (0s and 1s).
To handle letters, numbers, and symbols, a standard mapping was
needed between characters and binary values.
ASCII provides this mapping — allowing computers, printers, and
communication devices to exchange information accurately.

Structure of ASCII Codes

Range
Type of Characters Examples
(Decimal)

Control Characters (Non- NULL (0), Backspace (8), Enter


0 – 31
printable) (13), ESC (27)

32 – 47 Special Symbols Space (32), !, “, #, $, %, &, '

48 – 57 Digits 0–9

58 – 64 Special Symbols :, ;, <, =, >, ?, @

65 – 90 Uppercase Alphabets A–Z

91 – 96 Special Symbols [, , ], ^, _, `

97 – 122 Lowercase Alphabets a–z

123 – 126 Special Symbols {,

127 Delete (DEL) Used for deleting characters

Examples of ASCII Codes

Character Decimal Value Binary (7-bit) Hexadecimal

A 65 1000001 41

B 66 1000010 42

Z 90 1011010 5A

a 97 1100001 61

b 98 1100010 62

z 122 1111010 7A

0 48 0110000 30
Character Decimal Value Binary (7-bit) Hexadecimal

9 57 0111001 39

Space 32 0100000 20

Enter (CR) 13 0001101 0D

Important Points
 Standard ASCII uses 7 bits per character (0–127).
 Extended ASCII uses 8 bits (0–255), allowing 128 extra characters
(for symbols, accents, etc.).
 ASCII is widely used in text files, programming languages, and
communication protocols.
 Every keyboard key corresponds to an ASCII code.

9. Compiler, Interpreter, and Assembler:

These are language translators that convert programs from one form to another.

Language Levels

High Level (Python, Java, C++)

↓ Translation

Assembly Language (x86 ASM, ARM ASM)

↓ Translation

Machine Language (Binary: 010101...)

↓ Execution

Hardware (CPU)

A. Compiler:

Definition: Translates entire high-level program to machine code before execution.

Characteristics:

 Input: Source code (entire program)

 Output: Object code/executable file

 Translation: All at once

 Execution: Separate phase after compilation

 Speed: Slower compilation, faster execution

 Error Detection: Reports all errors after scanning entire program


 Memory: Requires more memory (stores entire code)

 Debugging: Harder (no line-by-line feedback)

Working Process:

1. Lexical Analysis

↓ (Tokenization)

2. Syntax Analysis

↓ (Parse tree generation)

3. Semantic Analysis

↓ (Type checking)

4. Intermediate Code Generation

5. Code Optimization

6. Code Generation

7. Machine Code (executable file)

Phases in Detail:

1. Lexical Analysis:

 Breaks source code into tokens

 Removes whitespace, comments

 Example: int x = 5; → [int, x, =, 5, ;]

2. Syntax Analysis:

 Checks grammar rules

 Creates parse tree

 Example: Ensures proper statement structure

3. Semantic Analysis:

 Type checking

 Scope resolution

 Example: Can't assign string to int variable

4. Intermediate Code Generation:

 Platform-independent representation
 Three-address code, bytecode

5. Optimization:

 Improves performance

 Removes redundant code

 Loop optimizations

6. Code Generation:

 Converts to machine/assembly code

 Platform-specific

Examples of Compiled Languages:

 C: gcc program.c -o [Link]

 C++: g++ [Link] -o [Link]

 Fortran: gfortran program.f90

 Go: go build [Link]

Advantages:

✅ Fast execution (pre-translated) ✅ Optimized code ✅ No need for translator during execution ✅
Protects source code (only distributes binary)

Disadvantages:

❌ Slower development cycle (compile each time) ❌ Platform-specific executables ❌ Harder to


debug ❌ Entire program recompiled for small changes

B. Interpreter:

Definition: Translates and executes program line by line.

Characteristics:

 Input: Source code (line by line)

 Output: Direct execution results

 Translation: Statement by statement

 Execution: Immediate (during translation)

 Speed: Slower execution, faster development

 Error Detection: Stops at first error

 Memory: Less memory required

 Debugging: Easier (line-by-line feedback)

Working Process:

Read line 1 → Translate → Execute → Read line 2 → Translate → Execute...


1. Fetch next statement

2. Analyze and translate

3. Execute immediately

4. Repeat for next statement

5. Stop on error or end of program

Examples of Interpreted Languages:

 Python: python [Link]

 JavaScript: Browser/[Link] execution

 Ruby: ruby [Link]

 PHP: php [Link]

 R: Interactive REPL

Advantages:

✅ Easy debugging (immediate error location) ✅ Platform-independent (same code runs anywhere)
✅ Interactive development (REPL) ✅ No compilation step ✅ Good for learning/prototyping

Disadvantages:

❌ Slower execution (translates each time) ❌ Source code must be distributed ❌ Requires
interpreter on target system ❌ No optimization

C. Assembler:

Definition: Translates assembly language to machine code.

Characteristics:

 Input: Assembly language (.asm file)

 Output: Machine code (object file)

 Translation: One-to-one mapping (mostly)

 Level: Low-level translation

 Platform: Specific to CPU architecture

Assembly Language Features:

 Mnemonics: Human-readable opcodes

 Fast Execution: Minimal abstraction

 Architecture Specific: x86, ARM, MIPS, etc.

Working Process:

Assembly Code (.asm)


Assembler

Object Code (.obj)

Linker

Executable (.exe)

Two Passes:

Pass 1:

 Create symbol table

 Assign addresses to labels

 Identify errors

Pass 2:

 Generate machine code

 Resolve addresses

 Produce object file

Common Assemblers:

 NASM (Netwide Assembler): Cross-platform

 MASM (Microsoft Macro Assembler): Windows, x86

 GAS (GNU Assembler): Linux, part of binutils

 TASM (Turbo Assembler): Legacy DOS

Advantages:

✅ Fine-grained hardware control ✅ Maximum performance ✅ Small executable size ✅ Direct


memory access

Disadvantages:

❌ Platform-specific ❌ Difficult to learn/write ❌ Not portable ❌ Time-consuming development ❌


Error-prone

Comparison Table:

Feature Compiler Interpreter Assembler

Input High-level code High-level code Assembly code

Output Machine code Direct execution Machine code


Feature Compiler Interpreter Assembler

Translation Entire program Line by line Instruction by instruction

Execution Separate phase During translation Separate (after linking)

Speed Fast (runtime) Slow (runtime) Very fast (runtime)

Development Slower Faster Slowest

Debugging Harder Easier Very hard

Memory More Less Minimal

Error Detection All at once Stops at first All at once

Portability Platform-specific Platform-independent Platform-specific

Examples C, C++, Rust Python, JavaScript NASM, MASM

Therefore
Overview of Compiler, Interpreter, and Assembler

Example
Translator Converts Execution Method
Language
High-level → Translates whole
Compiler C, C++
Machine code program at once
Interprete High-level → Python,
Translates line by line
r Machine code BASIC
Assembly → Converts mnemonics to
Assembler Assembly
Machine code binary
1. Algorithm, Flowchart, and Pseudocode:
Algorithm:
 A finite sequence of well-defined, unambiguous steps to solve a
problem or perform a computation.
 Characteristics: Input, output, definiteness, finiteness,
effectiveness.
 Example: Algorithm to find the largest number in a list:
1. Start.
2. Read the list of numbers.
3. Set the first number as the largest.
4. Compare each subsequent number with the current largest;
update if larger.
5. Output the largest number.
6. End.
Flowchart:
 A graphical representation of an algorithm using standardized
symbols to show the flow of control.
 Common symbols:
 Oval: Start/End.
 Rectangle: Process/Instruction.
 Diamond: Decision (yes/no).
 Arrow: Flow direction.
 Advantages: Visual, easy to understand, helps in debugging.
 Example: Flowchart for the above algorithm would include a loop
for comparison.
Pseudocode:
 A high-level description of an algorithm in plain English,
resembling code but without strict syntax.
 Uses keywords like IF, WHILE, FOR, but not tied to a specific
programming language.
 Example for the largest number algorithm:
 Purpose: Bridge between algorithm and actual code, aids in
planning.

2. Procedural vs Structured Programming


Feature Procedural Programming Structured Programming

Programs divided into procedures or Programs divided into modules using


Definition
functions control structures

Control Flow Uses GOTO and jumps Uses sequence, selection, and iteration

Readability Harder to maintain Easier to understand and debug

Example
BASIC, COBOL C, Pascal
Languages

 🔸 C language follows structured programming principles.

C Basics: Keywords, Identifiers, Variable Naming (Hungarian Notation):

C Language:

 Developed by Dennis Ritchie (1972) at Bell Labs.

 It is a structured, general-purpose, middle-level programming language.

 Combines low-level features of assembly and high-level features of modern languages.

Keywords:
 Reserved words in C that have special meanings and cannot be
used as identifiers.
 Examples: int, float, if, else, while, for, return, void, char, double,
switch, case, break, continue, default, goto, sizeof, typedef,
struct, union, enum, auto, register, static, extern, const, volatile,
signed, unsigned.
 Total: 32 keywords in standard C (ANSI C).
Identifiers:
 Names given to variables, functions, arrays, etc.
 Rules: Must start with a letter (a-z, A-Z) or underscore (_),
followed by letters, digits (0-9), or underscores. Case-sensitive.
No keywords allowed.
 Length: At least 31 characters significant (implementation-
dependent).
 Examples: valid - myVar, _temp, func1; invalid - 1var, int
(keyword).
Variable Naming (Hungarian Notation):
 A naming convention where variable names are prefixed with a
code indicating their type.
 Purpose: Improves readability and reduces errors by making type
obvious.
 Common prefixes:
 i: int (e.g., iCount)
 f: float (e.g., fValue)
 c: char (e.g., cLetter)
 p: pointer (e.g., pData)
 sz: string (null-terminated, e.g., szName)
 Example: int iAge; float fSalary;
 Not enforced by C, but a good practice for clarity.
Data Types, Constants, Declaration, Storage Size, Endianness:
Data Types:
 Fundamental types in C: char, int, float, double.
 Modifiers: signed, unsigned, short, long.
 Derived types: arrays, pointers, structures, unions, enums.

 Data Types in C

Type Keyword Size (bytes) Range (approx.)

Integer int 2 or 4 -32,768 to 32,767 / -2³¹ to 2³¹−1

Character char 1 -128 to 127

Floating Point float 4 ±3.4E–38 to ±3.4E+38

Double Precision double 8 ±1.7E–308 to ±1.7E+308

Void void — No value

Constants:
 Fixed values that do not change during execution.

Type Example

Integer Constant 100, -25

Floating Constant 3.14, -0.7

Character Constant 'A', '5'

String Constant "Hello"

Variable Declaration:
Variable Declaration in C

A variable is a named memory location used to store data temporarily during program execution.
It must be declared before it can be used, so that the compiler knows what type of data it will hold
and how much memory to allocate.

Syntax

data_type variable_name;

You can also declare and initialize a variable at the same time:

data_type variable_name = value;

Examples

int age; // declaration only

float salary = 55000; // declaration with initialization

char grade = 'A'; // single character

double area; // variable for double-precision value

You can also declare multiple variables of the same type in one statement:

int a, b, c;

float x = 2.5, y = 3.6;

Rules for Naming Variables

1. The first character must be a letter (A–Z, a–z) or underscore (_).

2. Subsequent characters may be letters, digits, or underscores.

3. No special characters (@, $, %, etc.) or spaces are allowed.

4. Variable names are case-sensitive (age and Age are different).

5. Avoid using keywords (like int, float, return, etc.) as variable names.

✅ Valid: total_marks, x1, _sum


❌ Invalid: 1num, float, first-name

Variable Initialization

When you assign an initial value to a variable at the time of declaration:

int num = 10;

char letter = 'B';


float average = 75.5;

If a variable is declared but not initialized, it contains a garbage value (random data already in
memory).

Variable Declaration vs. Definition

Term Description Example

Declaration Tells the compiler that a variable exists, but may not allocate memory. extern int a;

Definition Actually allocates memory for the variable. int a = 5;

Storage Size:
 Size of data types in bytes (varies by system, but standard):
 char: 1 byte
 short int: 2 bytes
 int: 4 bytes
 long int: 4 or 8 bytes
 float: 4 bytes
 double: 8 bytes
 long double: 10-16 bytes
 Use sizeof() operator to check: printf("%d", sizeof(int));
Endianness:
 Refers to the order in which bytes are stored in memory for multi-
byte data.
 Little-endian: Least significant byte first (e.g., Intel x86).
 Big-endian: Most significant byte first (e.g., Motorola).
 Example: int value = 0x12345678;
 Little-endian: Stored as 78 56 34 12
 Big-endian: Stored as 12 34 56 78
 C does not specify endianness; it's platform-dependent.
Operators:
Arithmetic Operators
 Perform mathematical operations.
 +, -, *, /, % (modulo).
 Examples: a + b, x % y.
Logical Operators
 Used for logical expressions (true/false).
 && (AND), || (OR), ! (NOT).
 Examples: (a > b) && (c < d).
Relational Operators
 Compare values.
 ==, !=, >, <, >=, <=.
 Examples: a == b, x > y.
Bitwise Operators
 Operate on bits of integers.
 & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift).
 Examples: a & b, x << 2.
Conditional Operator
 Ternary operator: condition ? expr1 : expr2.
 Example: max = (a > b) ? a : b;
Operator Precedence and Type Conversions:
Operator Precedence
 Order in which operators are evaluated in an expression.
 Higher precedence operators evaluated first.
 Associativity: Left-to-right or right-to-left.

 Operator Precedence Table (Highest → Lowest)

Precedence Operator Associativity

1 ++, --, () Left to Right

2 *, /, % Left to Right

3 +, - Left to Right

4 <, <=, >, >= Left to Right

5 ==, != Left to Right

6 &&, || Left to Right

7 = , +=, -= Right to Left

8 , Left to Right
Precedence Operator Associativity

Type Conversion

1. Implicit (Automatic Conversion)

o Done automatically by compiler.

o Example:

int a = 5;

float b = 2.5;

float c = a + b; // a converted to float

2. Explicit (Type Casting)

o Done manually by programmer.

o Example:

int a = 10, b = 3;

float c = (float)a / b;

Input/Output: scanf(), printf():


printf():
 Function to output formatted data to stdout.
 Syntax: printf("format string", arg1, arg2, ...);
 Format specifiers:
 %d: int
 %f: float
 %c: char
 %s: string
 %lf: double
 %%: literal %
 Examples: printf("Age: %d", age); printf("Pi: %.2f", 3.14159);
scanf():
 Function to read formatted input from stdin.
 Syntax: scanf("format string", &var1, &var2, ...);
 Note: Use & for variables (address-of operator).
 Format specifiers same as printf.
 Examples: scanf("%d", &x); scanf("%f %c", &y, &ch);
 Returns number of successful inputs; check for errors.

Common Format Specifiers

Specifier Data Type Example

%d int 10

%f float 3.14

%c char 'A'

%s string "Hello"

%lf double 23.56


Control Structures:
Control structures direct the flow of execution in a program based on
conditions or decisions. They allow selective execution of code blocks.
if Statement:
 Purpose: Executes a block of code if a condition is true.
Syntax:
if (condition) {
// statements
}
Example:
if (x > 0) {
printf("x is positive\n");
}
 Key Points: Condition must evaluate to a non-zero value (true) or
zero (false). No semicolon after the condition.
if-else Statement:
 Purpose: Executes one block if the condition is true, another if
false.
Syntax:
if (condition) {
// if block
} else {
// else block
}
Example:
if (x > 0) {
printf("positive\n");
} else {
printf("non-positive\n");
}
 Key Points: Only one block executes. Can be chained for multiple
conditions.
switch Statement:
 Purpose: Selects one of many code blocks based on the value of
an expression.
 Syntax:
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
}
 Example:
switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
default: printf("Other day\n");
}
 Key Points: Expression must be integer or
character. break prevents fall-through. default handles
unmatched cases.
Nested Conditions:
 Purpose: Placing one control structure inside another for complex
logic.
Example:
if (x > 0) {
if (x % 2 == 0) {
printf("positive even\n");
} else {
printf("positive odd\n");
}
} else {
printf("non-positive\n");
}
 Key Points: Increases complexity; use indentation for readability.
Avoid deep nesting to maintain clarity.
Loops:
Loops repeat a block of code until a condition is met. C supports three
main types, with control statements like break and continue.
while Loop:
 Purpose: Repeats while a condition is true (entry-controlled).
Syntax:
while (condition) {
// statements
}
Example:
int i = 0;
while (i < 5) {
printf("%d ", i);
i++;
}
 Key Points: Condition checked before each iteration. Infinite loop
if condition never false.
for Loop:
 Purpose: Repeats for a specified number of times (entry-
controlled).
Syntax:
for (initialization; condition; increment) {
// statements
}
Example:
for (int i = 0; i < 5; i++) {
printf("%d ", i);
}
 Key Points: Initialization, condition, and increment in one line.
Useful for counters.
do-while Loop:
 Purpose: Repeats at least once, then while condition is true (exit-
controlled).

Syntax:
do {
// statements
} while (condition);
Example:
int i = 0;
do {
printf("%d ", i);
i++;
} while (i < 5);
 Key Points: Body executes before condition check. Semicolon
after while.
break and continue:
 break: Exits the loop immediately.
 Example: In a loop, if (i == 3) break; stops at i=3.
 continue: Skips the rest of the current iteration and proceeds to
the next.
 Example: In a loop, if (i % 2 == 0) continue; skips even i.
 Key Points: break works in loops and switch; continue only in
loops.
goto and Labels:
 Purpose: Unconditional jump to a labeled statement.
Syntax:
label:
// statements
goto label;
Example:
int i = 0;
loop:
printf("%d ", i);
i++;
if (i < 5) goto loop;
 Key Points: Can create loops or jumps, but often leads to
spaghetti code. Structured programming (using if-else, loops) is
preferred over unstructured (goto) for readability and
maintainability. Goto is rarely used in modern C; avoid for
complex programs.
Functions:

A function is a block of code designed to perform a specific task.


Functions promote modularity, reusability, and easier debugging.

🔹 Function Declaration

Tells the compiler about the function’s name, return type, and parameters.

return_type function_name(parameter_list);

Example:

int add(int, int);

🔹 Function Definition

Contains the actual code for the function.

int add(int a, int b)

return a + b;

🔹 Function Call

Transfers control to the function.

sum = add(5, 10);

🔹 Function Prototype

A declaration that specifies the type signature before main().

float area(float radius);

Parameter Passing and Return Types:


 Parameter Passing: Arguments passed by value (copies made).
 Example: add(5, 3); passes copies of 5 and 3.
 Return Types: Specifies what the function returns (e.g., int, void).
 Example: int add(...) returns an int; void print(...) returns
nothing.
 Key Points: Changes to parameters inside function don't affect
originals. Use pointers for pass-by-reference.
Recursion:
 Purpose: Function calls itself to solve problems (e.g., factorial).
 Example:
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
 Key Points: Requires base case to avoid infinite recursion. Uses
stack space; can cause overflow for deep recursion.
Storage Classes:
Storage classes define scope, lifetime, and linkage of variables.
Auto:
 Scope: Block (local).
 Lifetime: Automatic (created/destroyed with block).
 Example: auto int x; (default for local variables).
 Key Points: Rarely used explicitly.
Static:
 Scope: Local to function/file.
 Lifetime: Program duration.
 Example: static int count = 0; retains value between calls.
 Key Points: For global static, limits linkage to file.
Extern:
 Scope: Global.
 Lifetime: Program duration.
 Example: extern int global_var; declares without defining.
 Key Points: Used for variables defined in other files.
Register:
 Scope: Block.
 Lifetime: Automatic.
 Example: register int x; suggests storing in CPU register.
 Key Points: Hint to compiler; not guaranteed. For frequently used
variables.
Preprocessor Directives and Macros:
Preprocessor Directives

Preprocessor directives begin with # and are processed before compilation.

 Examples:
 #include: Includes files (e.g., #include <stdio.h>).
 #define: Defines constants or macros.
 #ifdef, #ifndef, #endif: Conditional compilation.
 Key Points: Processed before code; no semicolons.
Macros
 Purpose: Text substitution.
 Syntax: #define MACRO_NAME value or #define
MACRO_NAME(parameters) expression.
 Examples:
 Constant: #define PI 3.14
 Function-like: #define SQUARE(x) ((x)*(x))
 Key Points: No type checking; use parentheses to avoid issues.
Can lead to side effects (e.g., SQUARE(a++)). Prefer inline
functions for complex macros.
Arrays:

An array is a collection of elements of the same data type, stored in contiguous memory locations,
and accessed using an index.

1D Arrays
 Purpose: Store a linear sequence of elements.
 Declaration: data_type array_name[size];
 Example: int arr[5]; // Array of 5 integers
 Initialization:
 int arr[5] = {1, 2, 3, 4, 5};
 Partial: int arr[5] = {1, 2}; // Rest initialized to 0
 Access: arr[index] (e.g., arr[0] = 10;)
 Key Points: Size must be constant. Out-of-bounds access causes
undefined behavior. Arrays decay to pointers in expressions.
2D Arrays
 Purpose: Store tabular data (rows and columns).
 Declaration: data_type array_name[rows][columns];
 Example: int matrix[3][4]; // 3 rows, 4 columns
 Initialization:
 int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
 Row-major order in memory.
 Access: matrix[row][col] (e.g., matrix[0][1] = 5;)
 Key Points: Can be visualized as an array of arrays. Memory layout
is contiguous.
Array to Function Passing
 Purpose: Pass arrays to functions for processing.
 Syntax: Functions receive arrays as pointers.
 Declaration: void func(int arr[], int size); or void func(int *arr, int
size);
Example:
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printArray(arr, 5); // Passes pointer to first element
}
 Key Points: Arrays are passed by reference (address). Size must
be passed separately. Modifications affect original array.
Pointers:

A pointer is a variable that stores the memory address of another variable.

Basics:
 Purpose: Reference variables indirectly via addresses.
 Declaration: data_type *pointer_name;
 Example: int *ptr; // Pointer to int
 Initialization: ptr = &variable; (e.g., int x = 10; ptr = &x;)
 Dereferencing: *ptr accesses the value at the address.
 Example: printf("%d", *ptr); // Prints 10
 Key Points: Uninitialized pointers are dangerous (garbage
values). NULL (0) indicates no address. Use sizeof for pointer size
(usually 4 or 8 bytes).
Pointer Arithmetic
 Purpose: Navigate arrays or memory blocks.
 Operations: Increment/decrement by data type size.
 Example: int arr[5]; int *ptr = arr; ptr++; // Moves to next
int (4 bytes ahead)
 Arithmetic: ptr + n, ptr - n, ptr1 - ptr2 (gives element difference).
Example:
int arr[3] = {1, 2, 3};
int *ptr = arr;
printf("%d", *(ptr + 1)); // Prints 2
 Key Points: Valid only within allocated memory. Pointer
subtraction gives elements, not bytes. Avoid invalid arithmetic.
Pointer to Arrays:
 Purpose: Treat arrays as pointers for flexibility.
 Syntax: data_type (*ptr)[size]; for 2D, or data_type *ptr; for 1D.

Example:
//For 1D:
int arr[3] = {1, 2, 3};
int *ptr = arr; // Points to first element
printf("%d", *ptr); // 1
// For 2D:
int matrix[2][3] = {{1,2,3},{4,5,6}};
int (*ptr2d)[3] = matrix; // Pointer to array of 3 ints
printf("%d", (*ptr2d)[1]); // 2
 Key Points: Useful for dynamic arrays or function
parameters. arr decays to &arr[0].
Strings:
Strings are null-terminated character arrays ('\0' ends the string). C
treats them as arrays of chars.
Character Arrays
 Purpose: Store sequences of characters.
 Declaration: char str[size];
 Example: char name[20];
 Initialization:
 char str[] = "Hello"; // Auto-sizes to 6 (including '\0')
 char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
 Access: str[index] (e.g., str[0] = 'A';)
 Key Points: Always null-terminate. Size includes space for '\0'. No
built-in bounds checking.
String Library Functions
 Purpose: Manipulate strings safely (include <string.h>).
 Common Functions:
 strlen(str): Returns length (excluding '\0').
 Example: strlen("Hello") → 5
 strcpy(dest, src): Copies src to dest.
 Example: strcpy(dest, "World");
 strcat(dest, src): Appends src to dest.
 Example: strcat(dest, " World");
 strcmp(str1, str2): Compares strings (0 if equal, <0 or >0
otherwise).
 Example: strcmp("abc", "abd") → -1
 strncpy, strncat, strncmp: Safer versions with length limits.
 Key Points: Ensure destination has enough space. Functions
modify strings in place.
Array of Strings
 Purpose: Store multiple strings.
 Declaration: char array_name[num_strings][max_length];
 Example: char names[3][20] = {"Alice", "Bob", "Charlie"};
 Access: names[index][char_index] (e.g., names[0][0] = 'A';)
 Alternative: Array of pointers: char *names[] = {"Alice", "Bob"};
 Key Points: Useful for lists. Pointer arrays save space if strings
vary in length.
Dynamic Memory Allocation:
Dynamic allocation manages memory at runtime using heap space,
allowing flexible sizing.

malloc()

Allocates memory block of given size (in bytes).

int *p;

p = (int *)malloc(5 * sizeof(int));

 Does not initialize memory.

 Returns pointer of type void * (needs casting in C++).

 Returns NULL if allocation fails.


calloc()

Allocates multiple blocks and initializes them to zero.

int *p;

p = (int *)calloc(5, sizeof(int)); // 5 blocks initialized to 0

realloc()

Changes the size of a previously allocated block.

p = (int *)realloc(p, 10 * sizeof(int)); // resize to 10 ints

free()

Frees previously allocated memory.

free(p);

Always free() dynamically allocated memory to prevent memory leaks.

Memory Management Summary

Function Initialization Purpose

malloc() Garbage Allocates single block

calloc() Zero Allocates multiple blocks

realloc() Retains old data Resize block

free() — Deallocates block

Example: Dynamic Array

#include <stdio.h>

#include <stdlib.h>

int main() {

int n, *ptr, i;

printf("Enter size: ");

scanf("%d", &n);

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


if (ptr == NULL) {

printf("Memory not allocated!\n");

return 0;

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

printf("Enter element %d: ", i+1);

scanf("%d", &ptr[i]);

printf("Array elements: ");

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

printf("%d ", ptr[i]);

free(ptr);

return 0;

}
Structures:

🔸 Definition

A structure in C is a user-defined data type that allows combining data of different types under a
single name.
Useful for representing complex data like student records, employees, books, etc.

Syntax:

struct structure_name {

data_type member1;

data_type member2;

...

};

Example:

struct student {

int roll;

char name[20];

float marks;

};

🔸 Declaring and Initializing Structure Variables

After defining the structure, create a variable:

struct student s1; // declaration

Initialization:
struct student s1 = {101, "Ravi", 89.5};

Accessing Members (Dot Operator):

printf("%d %s %.2f", [Link], [Link], [Link]);

🔸 Array of Structures

Used to store multiple records of the same type.

Example:

struct student s[3];

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

scanf("%d %s %f", &s[i].roll, s[i].name, &s[i].marks);

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

printf("%d %s %.2f\n", s[i].roll, s[i].name, s[i].marks);

📘 Example Output:

101 Ravi 89.5

102 Anita 91.0

103 Rahul 78.0

🔸 Pointers to Structures

A pointer can store the address of a structure variable.

Example:

struct student s1 = {101, "Ravi", 89.5};

struct student *ptr = &s1;

printf("%d %s %.2f", ptr->roll, ptr->name, ptr->marks);

Note:
Use → (arrow operator) to access members using pointer.

Unions and enum, typedef, bit fields:

These features enhance data type flexibility: unions save space, enums define constants, typedef
creates aliases, and bit fields pack data.

Unions:
 Purpose: Store different data types in the same memory location (overlapping).

Syntax:

union union_name {

data_type member1;

data_type member2;

// ...

};

Example:

union Data {

int i;

float f;

char str[20];

};

union Data d;

d.i = 10; // Now d.f and [Link] are invalid

 Key Points: Size is the largest member. Only one member active at a time. Useful for
memory efficiency in variant data.

Enum:

 Purpose: Define named integer constants for readability.

Syntax:

enum enum_name {

constant1,

constant2 = value,

// ...

};

Example:

enum Days {MON, TUE, WED = 5, THU, FRI};

// MON=0, TUE=1, WED=5, THU=6, FRI=7

enum Days today = MON;


 Key Points: Default starts at 0, increments by 1. Can assign custom values. Improves code
clarity over magic numbers.

Typedef:

 Purpose: Create aliases for existing types to simplify code.

 Syntax: typedef existing_type new_name;

Example:

typedef int Integer;

typedef struct Student Student; // Alias for struct

Integer num = 5;

Student s; // Instead of struct Student s;

 Key Points: Doesn't create new types, just synonyms. Commonly used with structs, unions,
and pointers for brevity.

Bit Fields:

 Purpose: Pack multiple small data into a single integer for space efficiency.

Syntax: In a struct, declare members with bit widths.

struct BitField {

unsigned int flag1 : 1; // 1 bit

unsigned int value : 3; // 3 bits

// ...

};

Example:

struct BitField bf;

bf.flag1 = 1;

[Link] = 5; // Fits in 3 bits (0-7)

 Key Points: Total bits <= word size (e.g., 32 bits). Useful for flags or compact storage. No
address access; compiler manages packing.

File I/O in C:

File I/O handles reading from and writing to files for data persistence. C uses streams (text or
binary) via standard library functions in <stdio.h>.

fopen() and fclose():

 Purpose: Open and close files for I/O operations.

 Syntax: FILE *fopen(const char *filename, const char *mode); and int fclose(FILE *stream);
 Modes: "r" (read), "w" (write, truncates), "a" (append), "r+" (read/write), etc. Add "b" for
binary (e.g., "rb").

Example:

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

if (fp == NULL) {

perror("Error opening file");

return 1;

// Operations...

fclose(fp);

 Key Points: Returns NULL on failure. Always close files to flush buffers and free resources.
Check for errors.

fprintf() and fscanf():

 Purpose: Formatted writing and reading to/from files (like printf/scanf for files).

 Syntax: int fprintf(FILE *stream, const char *format, ...); and int fscanf(FILE *stream, const
char *format, ...);

Example:

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

fprintf(fp, "Name: %s, Age: %d\n", "Alice", 25);

fclose(fp);

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

char name[50];

int age;

fscanf(fp, "Name: %s, Age: %d", name, &age);

fclose(fp);

 Key Points: Return number of items read/written. Handles text files. For binary, use
fread/fwrite. Buffering may delay writes.

fgetc() and fputc():

 Purpose: Character-based reading and writing for unformatted I/O.

 Syntax: int fgetc(FILE *stream); and int fputc(int char, FILE *stream);

Example:
FILE *fp = fopen("[Link]", "w");

fputc('A', fp);

fputc('B', fp);

fclose(fp);

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

int ch;

while ((ch = fgetc(fp)) != EOF) {

putchar(ch);

fclose(fp);

 Key Points: fgetc returns int (EOF on end/error). Useful for processing files character-by-
character. EOF is -1.

Command Line Arguments:

Command-line arguments allow passing inputs to programs via the terminal, enabling flexible
execution.

 Purpose: Accept arguments from the command line (e.g., program arg1 arg2).

 Syntax: int main(int argc, char *argv[]) or int main(int argc, char **argv)

 argc: Argument count (includes program name).

 argv: Array of strings (arguments).

 Example:

#include <stdio.h>

int main(int argc, char *argv[]) {

printf("Program name: %s\n", argv[0]);

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

printf("Argument %d: %s\n", i, argv[i]);

return 0;

// Run: ./program hello world

// Output: Program name: ./program

// Argument 1: hello
// Argument 2: world

You might also like