0% found this document useful (0 votes)
14 views58 pages

Notes 1-4

The document provides an overview of computer fundamentals, including definitions of a computer, its key components, and how it works. It covers topics such as the Central Processing Unit (CPU), memory hierarchy, programming concepts, and an introduction to the C programming language. Additionally, it outlines number representation systems in computers, including binary, octal, decimal, and hexadecimal, along with conversion methods between these systems.

Uploaded by

22f2001737
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)
14 views58 pages

Notes 1-4

The document provides an overview of computer fundamentals, including definitions of a computer, its key components, and how it works. It covers topics such as the Central Processing Unit (CPU), memory hierarchy, programming concepts, and an introduction to the C programming language. Additionally, it outlines number representation systems in computers, including binary, octal, decimal, and hexadecimal, along with conversion methods between these systems.

Uploaded by

22f2001737
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
You are on page 1/ 58

Home Week-2

C Programming - Week 1
C Programming - Week 1
What is a Computer?
How Computers Work?
Central Processing Unit (CPU)
Memory Hierarchy in CPU
What is Programming?
Introduction to C Language

What is a Computer?
A computer is an electronic device that processes data, performs calculations, and executes
instructions to carry out various tasks.

It is a versatile and programmable machine that can perform a wide range of functions, from
simple arithmetic operations to complex data analysis and simulations.

Key Components of a Computer:

1. Central Processing Unit (CPU):

Often referred to as the "brain" of the computer.

Responsible for executing instructions and performing calculations.

Composed of control units and arithmetic logic units (ALU).

2. Memory (RAM - Random Access Memory):

Temporary storage used for actively running programs and data.

Data can be read from and written to RAM quickly.

Volatile memory, meaning data is lost when the computer is powered off.

3. Storage Devices:

Store data and programs for long-term use.

Examples include hard drives, solid-state drives (SSDs), and external storage devices.

Non-volatile memory, retaining data even when the computer is turned off.

4. Input Devices:

Allow users to input data and commands into the computer.

Examples include keyboards, mice, touchscreens, and microphones.

5. Output Devices:

Display or present the results of computer processing to users.

Examples include monitors, printers, speakers, and headphones.


6. Motherboard:

The main circuit board that connects and facilitates communication between all
computer components.

7. Software:

Programs and instructions that tell the computer what tasks to perform.

Includes operating systems, applications, and utility software.

How Computers Work?


1. Input Stage:

The process begins with the input of data and instructions.

Input devices such as keyboards, mice, and touchscreens are used to enter data.

Instructions can also come from pre-programmed software.

2. Processing Stage:

Data and instructions are sent to the Central Processing Unit (CPU).

The CPU decodes instructions and performs calculations and logical operations.

It uses memory (RAM) to temporarily store data and intermediate results.

3. Memory Storage:

Data and programs are stored in various types of memory:

RAM (Random Access Memory): Temporary storage used for active processes.

ROM (Read-Only Memory): Permanent storage containing essential system instructions.

Secondary Storage (Hard Drives, SSDs): Long-term storage for files and programs.

4. Control Unit:

The control unit coordinates and manages the execution of instructions.

It fetches instructions from memory, decodes them, and directs the CPU accordingly.

It controls data flow between the CPU and memory.

5. Arithmetic Logic Unit (ALU):

The ALU performs arithmetic operations (addition, subtraction, multiplication, division) and
logical operations (AND, OR, NOT).

These operations manipulate data according to the instructions.

6. Output Stage:

Processed data is sent to output devices for user consumption.

Output devices can include monitors, printers, speakers, and displays.

Users can interact with the computer through output devices.

7. Storage and Retrieval:

Data can be stored on secondary storage devices for long-term preservation.


When needed, data is retrieved from storage and loaded into RAM for processing.

8. Communication:

Computers can communicate with other devices and networks.

This allows data exchange over the internet, LANs, and WANs.

Network interface cards and protocols facilitate communication.

9. Software:

Software consists of programs and instructions that tell the computer what to do.

Operating systems manage hardware resources and enable software to run.

Application software performs specific tasks, such as word processing or gaming.

10. Execution of Programs:

Programs are executed in a step-by-step manner.

The computer fetches, decodes, and executes each instruction.

This process continues until the program is completed.

11. Binary Language:

Computers use binary code (0s and 1s) to represent data and instructions.

The CPU interprets binary code and performs operations accordingly.

Central Processing Unit (CPU)


Definition:

The CPU (Central Processing Unit) is the primary component of a computer responsible for
executing instructions and performing calculations.
Source: WikiPedia

Key Components:

1. Control Unit (CU):

Manages and coordinates the operation of the CPU.

Controls the flow of data and instructions within the CPU and between other hardware
components.

2. Arithmetic Logic Unit (ALU):

Performs mathematical calculations (addition, subtraction, multiplication, division).

Executes logical operations (AND, OR, NOT) for decision-making.

3. Registers:

Small, high-speed memory locations within the CPU.

Store data and instructions temporarily during processing.

Includes the program counter (PC), instruction register (IR), and general-purpose
registers.

Functions:

1. Instruction Execution:

Fetches instructions from memory.

Decodes instructions to determine the operation to be performed.

Executes instructions by performing calculations and data manipulations.

2. Data Processing:

Performs arithmetic and logical operations on data.

Processes data in accordance with the instructions provided by software.

3. Control of Peripherals:
Communicates with input and output devices to manage data transfer.

Controls the timing and synchronization of data exchange.


4. Memory Management:

Accesses and manages data stored in RAM and other memory locations.

Controls memory allocation and deallocation.

Memory Hierarchy in CPU


Introduction:

Memory hierarchy in a CPU refers to the organization of memory units with varying speeds
and capacities, allowing for efficient data access and processing.

This hierarchy is essential for balancing the trade-offs between speed and capacity in modern
computer systems.

Levels of Memory Hierarchy:

1. Registers:

Purpose:

Registers are the smallest and fastest memory units within the CPU.

Usage:

Stores the data that the CPU is actively processing.

Used for holding intermediate results and operands during calculations.

Examples include the program counter (PC) and general-purpose registers (e.g., AX,
BX, etc.).

2. Cache Memory:

Purpose:

Cache memory serves as a bridge between registers and main memory (RAM).
It provides faster access to frequently used data.
3. Main Memory (RAM - Random Access Memory):

Purpose:

Main memory is the primary memory for program and data storage during active
tasks.

It holds the code and data that the CPU is currently processing.

Characteristics:

Faster access times than secondary storage (e.g., hard drives).

Volatile memory, data is lost when the computer is powered off.

4. Secondary Memory (Storage Devices):

Purpose:

Secondary memory provides long-term storage for programs and data, even when
the computer is turned off.

It serves as a large storage pool for files, applications, and the operating system.

Types:

Hard Disk Drives (HDDs): Spinning disks for magnetic data storage.

Solid-State Drives (SSDs): Use flash memory for faster, more durable storage.

Optical Discs (e.g., DVDs, Blu-rays): Used for archiving and software distribution.

USB Drives (Flash Drives): Portable storage for data transfer and backup.

What is Programming?
Programming, also known as coding or software development, is the process of instructing a
computer to perform specific tasks by providing it with a set of structured instructions or
commands in a programming language.

Key Concepts:

1. Programming Languages:

These are formal languages with syntax and semantics used to communicate with
computers.

Examples include C, Python, Java, C++, and JavaScript.

2. Algorithms:

Algorithms are step-by-step sets of instructions used to solve specific problems or


perform tasks.

They form the core of computer programs.

3. Data Structures:
Data structures are ways to organize and store data efficiently, making it easier to
manipulate and access.
4. Software Development Cycle:

Programming involves multiple stages, including problem-solving, coding, testing,


debugging, and maintenance.

Purpose of Programming:

1. Automation:

Programming automates repetitive tasks, improving efficiency and reducing human


error.

2. Problem Solving:

It provides tools to tackle complex problems in various fields, from science and
engineering to finance and entertainment.

3. Creating Software:

Programmers create software applications, from simple scripts to complex software


systems, serving various purposes.

4. Innovation:

Programming drives technological innovation, enabling the development of new


products and services.

Programming Process:

1. Understanding the Problem:

Analyze the problem or task to be solved by the program.

2. Designing the Solution:

Plan the program's structure, algorithms, and data structures.

3. Writing Code:

Implement the solution in a programming language by writing code.

4. Testing and Debugging:

Verify that the program works correctly and fix any errors (bugs).

5. Optimization:

Improve the program's efficiency and performance, if needed.

6. Documentation:

Document the program's functionality, usage, and code for future reference.

Types of Programming:

1. Application Programming:

Developing software applications like word processors, games, and mobile apps.

2. Web Development:

Creating websites and web applications using languages like HTML, CSS, and JavaScript.

3. Embedded Programming:

Programming embedded systems, found in devices like smartphones, IoT devices, and
car systems.
4. Scientific and Data Analysis Programming:

Using programming to analyze and visualize data in scientific research and data science.

Programming Tools:

1. Integrated Development Environments (IDEs):

Software applications that provide a comprehensive development environment with


code editors, debuggers, and build tools.

2. Text Editors:

Simple tools for writing and editing code, often used by experienced programmers.

3. Version Control Systems:

Software like Git helps track changes and manage collaborative coding projects.

Introduction to C Language
C is considered as a middle-level language because it supports the feature of both low-level
and high-level languages. C language program is converted into assembly code, it supports
pointer arithmetic (low-level), but it is machine independent (a feature of high-level).

The C programming language is general-purpose programming language known for its


simplicity, efficiency, and portability.

It was developed in the early 1970s by Dennis Ritchie at Bell Labs for system programming
and has since become one of the most widely used programming languages.

Key Characteristics:

1. Procedural Language:

C follows a procedural programming paradigm, focusing on functions and procedures.

It's known for its structured and modular approach to code.

2. Portability:

C code can be compiled and run on various platforms with minor modifications, making
it highly portable.

3. Efficiency:

C provides low-level memory access and efficient control over hardware, making it
suitable for system programming and performance-critical applications.

4. Strongly Typed:

C enforces strong data typing, meaning data types must be explicitly declared and
adhered to.

5. Rich Standard Library:

C comes with a rich standard library that provides functions for I/O, string manipulation,
memory management, and more.
Basic Syntax:

C code is written in a C source file (usually with a .c extension) and follows a structured syntax
with key elements:

Variables: Used for data storage.

Functions: Blocks of code with a specific purpose.

Control Structures: Statements for making decisions (if-else), loops (for, while), and
branching.

Data Types: int, float, char, etc., to define variable types.

Operators: +, -, *, /, =, etc., for operations on data.

Hello World Example:

1 #include <stdio.h>
2
3 int main() {
4 printf("Hello, World!\n");
5 return 0;
6 }

Advantages of C Language:

1. Efficiency: C allows for precise control over hardware, making it efficient for system
programming and resource-constrained applications.

2. Portability: C programs can be compiled on different platforms with minor adjustments.

3. Vast Community and Resources: C has a large user community, offering extensive
documentation and libraries.

4. Compatibility: Many other languages, like C++, are based on or compatible with C, extending
its capabilities.

Applications:

1. System Programming: C is commonly used for operating system development, embedded


systems, and device drivers.

2. Application Development: It is used to build software applications, including desktop


software and games.

3. Compilers and Interpreters: C is used to create compilers and interpreters for other
programming languages.

4. Scientific and Numerical Computing: In fields like engineering and data analysis.
Week-1 Week-3

C Programming - Week 2
C Programming - Week 2
Number representation in computers
1. Binary Number System
2. Octal Number System
3. Decimal Number System
4. Hexadecimal Number System
Conversion Between Number Systems
Negative Number Representation in Computers
1. Sign and Magnitude
2. Two's Complement
Floating Point Representation in Computers
Character Representation and Encoding in Computers
1. ASCII (American Standard Code for Information Interchange)
2. Extended ASCII
3. Unicode
4. UTF-8 (Unicode Transformation Format - 8-bit)
Example: Encoding and Decoding
Instruction Encoding in a Computer
Program Compilation in a Computer
Stages of Compilation
Role of the Operating System in a Computer
Functions of the Operating System
Booting
Bootstrap
BIOS (Basic Input/Output System)

Number representation in computers


1. Binary Number System
Definition:

The binary number system uses two digits, 0 and 1. Each digit is known as a bit.

It is the foundation of all binary code, which is used in computer and digital systems.

Example:

The binary number 1011 represents the decimal number 11.

Explanation:

Binary numbers are base-2 numbers.


To convert a binary number to decimal, sum the products of each bit and its corresponding
power of 2.

Conversion Example:

2. Octal Number System


Definition:

The octal number system uses eight digits, from 0 to 7.

It is a base-8 number system.

Example:

The octal number 17 represents the decimal number 15.

Explanation:

To convert an octal number to decimal, sum the products of each digit and its corresponding
power of 8.

Conversion Example:

3. Decimal Number System


Definition:

The decimal number system uses ten digits, from 0 to 9.

It is a base-10 number system and the most commonly used in everyday life.

Example:

The decimal number 345 represents the same number in the decimal system.

Explanation:

Each digit in a decimal number is multiplied by the corresponding power of 10.

Conversion Example:

4. Hexadecimal Number System


Definition:

The hexadecimal number system uses sixteen digits, from 0 to 9 and A to F (where A = 10, B =
11, C = 12, D = 13, E = 14, and F = 15).

It is a base-16 number system.

Example:

The hexadecimal number 1A3 represents the decimal number 419.


Explanation:

To convert a hexadecimal number to decimal, sum the products of each digit and its
corresponding power of 16.

Conversion Example:

Conversion Between Number Systems


1. Decimal to Binary:

Example: Convert 13 to binary.

Divide by 2 and record the remainders:

Read the remainders from bottom to top: .

2. Decimal to Octal:

Example: Convert 65 to octal.

Divide by 8 and record the remainders:

Read the remainders from bottom to top: .

3. Octal to Binary:

Example: Convert 157 to binary.

Convert each octal digit to its binary equivalent:

Result:

4. Decimal to Hexadecimal:

Example: Convert 255 to hexadecimal.

Divide the number by 16 and record the remainders:

255 ÷ 16 = 15 remainder 15
15 ÷ 16 = 0 remainder 15
Write remainders in reverse: FF

255 = FF in hexadecimal.

5. Hexadecimal to Decimal:

Example: Convert 1A3 to decimal.

Each digit is multiplied by its corresponding power of 16:

1 * 16^2 + A * 16^1 + 3 * 16^0

1 * 256 + 10 * 16 + 3 * 1

256 + 160 + 3

419

1A3 = 419 in decimal.

6. Binary to Hexadecimal:

Example: Convert 11010110 to hexadecimal.

Group binary digits in sets of four from right to left:

Convert each group to decimal, then to hexadecimal:

Result:

7. Hexadecimal to Binary

Direct Mapping: 1 hexadecimal digit maps to 4 binary digits.

Example: Convert 3F to binary.

Convert each digit:

3 = 0011

F = 1111

Result: 00111111

Negative Number Representation in Computers


Negative numbers can be represented in computers using several methods. The most common
ones are:
1. Sign and Magnitude
Description: The most significant bit (MSB) represents the sign (0 for positive, 1 for negative),
and the remaining bits represent the magnitude (absolute value) of the number.

Example:

For an 8-bit system:

+18: 00010010

-18: 10010010

Explanation:

The MSB indicates the sign.

This method is simple but has issues with two representations for zero (+0 and -0).

2. Two's Complement
Description: Negative numbers are represented by inverting all the bits of the positive
number and then adding 1 to the least significant bit (LSB).

Example:

For an 8-bit system:

+18: 00010010

-18: 11101110 (invert 00010010 to get 11101101, then add 1)

Explanation:

This is the most commonly used method because it simplifies arithmetic operations.

There's only one representation for zero.

Easy to implement in hardware and supports straightforward addition and subtraction.

Floating Point Representation in Computers


Floating-point representation is a way to store real numbers (numbers with fractional parts) in a
format that can accommodate a wide range of values. This is essential for scientific calculations,
graphics, and many other applications.

1. Why Use Floating Point?

Wide Range of Values: Floating-point can represent very small and very large numbers.

Fractional Values: It allows for the representation of fractional parts, unlike integers.

Standardization: The IEEE 754 standard ensures consistency across different computing
systems.

2. IEEE 754 Standard

The IEEE 754 standard is the most widely used format for floating-point arithmetic. It defines two
main formats:
Single Precision (32-bit)

Double Precision (64-bit)

3. Components of Floating-Point Representation

A floating-point number is typically represented in the following form:

Where:

s: Sign bit (0 for positive, 1 for negative)

mantissa (fraction): Represents the significant digits of the number.

exponent: Determines the scale or magnitude of the number.

bias: A constant used to adjust the range of the exponent (127 for single precision, 1023 for
double precision).

4. Single Precision (32-bit)

In single precision, a floating-point number is divided into three parts:

Sign (1 bit): Indicates the sign of the number.

Exponent (8 bits): Encodes the exponent with a bias of 127.

Mantissa (23 bits): Encodes the significant digits of the number.

Example: Representing the number -5.75 in IEEE 754 single precision.

1. Convert to Binary:

2. Normalize:

3. Determine Components:

Sign bit (s): 1 (since the number is negative)

Exponent: 2 + 127 (bias) = 129 = 10000001210000001_2100000012

Mantissa: 01110000000000000000000 (23 bits)

4. Combine:

1 | 10000001 | 01110000000000000000000

Explanation:

Sign bit is 1.

Exponent is 129, which in binary is 10000001.

Mantissa is the binary digits after the decimal point, padded to 23 bits.

5. Double Precision (64-bit)

In double precision, a floating-point number is divided into three parts:


Sign (1 bit): Indicates the sign of the number.

Exponent (11 bits): Encodes the exponent with a bias of 1023.

Mantissa (52 bits): Encodes the significant digits of the number.

Example: Representing the number -5.75 in IEEE 754 double precision.

1. Convert to Binary:

2. Normalize:

3. Determine Components:

Sign bit (s): 1 (since the number is negative)

Exponent: 2 + 1023 (bias) = 1025 = 10000000001210000000001_2100000000012

Mantissa: 0111000000000000000000000000000000000000000000000000 (52 bits)

4. Combine:

1 | 10000000001 | 0111000000000000000000000000000000000000000000000000

Explanation:

Sign bit is 1.

Exponent is 1025, which in binary is 10000000001.

Mantissa is the binary digits after the decimal point, padded to 52 bits.

6. Special Values

IEEE 754 defines several special values:

Zero: Represented by all bits in the exponent and mantissa being zero.

Positive Zero: 0 | 00000000 | 00000000000000000000000

Negative Zero: 1 | 00000000 | 00000000000000000000000

Infinity: Represented by all bits in the exponent being ones and all bits in the mantissa being
zero.

Positive Infinity: 0 | 11111111 | 00000000000000000000000

Negative Infinity: 1 | 11111111 | 00000000000000000000000

NaN (Not a Number): Represented by all bits in the exponent being ones and at least one
bit in the mantissa being non-zero.

Example: 0 | 11111111 | 10000000000000000000000

7. Precision and Rounding

Precision: Single precision can represent approximately 7 decimal digits, while double
precision can represent about 15 decimal digits.

Rounding: When performing arithmetic operations, results might need to be rounded to fit
the available precision. IEEE 754 specifies several rounding modes (e.g., round to nearest,
round toward zero).
Example Calculation

Let's convert a simple decimal number to its floating-point representation and back to understand
the process.

Example: Convert the decimal number 10.375 to IEEE 754 single precision.

1. Convert to Binary:

10 in binary is 1010 .

0.375 in binary is 0.011 (since 0.375 = 0.50 + 0.251 + 0.125*1).

Combining these gives: .

2. Normalize:

3. Determine Components:

Sign bit (s): 0 (since the number is positive)

Exponent: 3 + 127 (bias) = 130 = .

Mantissa: 01001100000000000000000 (23 bits)

4. Combine:

0 | 10000010 | 01001100000000000000000

Converting Back to Decimal

Given the IEEE 754 single precision representation 0 | 10000010 | 01001100000000000000000 :

1. Sign Bit: 0 (positive)

2. Exponent: 10000010210000010_2100000102 = 130. Subtract bias (127): 130 - 127 = 3.

3. Mantissa: 1.010011 (normalized form)

Combine these to get:

Convert back to decimal:

Character Representation and Encoding in


Computers
Basics of Character Representation

Characters (letters, digits, symbols) in computers are represented using numeric codes. Each
character is assigned a unique number, which is stored in memory as binary data. This system
allows computers to process text.
Common Character Encoding Standards

There are several encoding standards used to represent characters. The most common ones
include:

ASCII (American Standard Code for Information Interchange)

Extended ASCII

Unicode

UTF-8

1. ASCII (American Standard Code for Information


Interchange)
Description: ASCII is one of the oldest character encoding standards. It uses 7 bits to
represent each character, allowing for 128 unique characters.

Range: 0 to 127.

Characters: Includes control characters (e.g., newline, tab) and printable characters (e.g.,
letters, digits, punctuation).

Example:

The character 'A' in ASCII:

Decimal: 65

Binary: 01000001

Explanation:

ASCII uses 7 bits, so 'A' (65 in decimal) is represented as 01000001 in binary.

2. Extended ASCII
Description: Extended ASCII uses 8 bits to represent each character, allowing for 256 unique
characters. It includes the standard ASCII set plus additional characters (e.g., accented letters,
symbols).

Range: 0 to 255.

Example:

The character 'é' in Extended ASCII:

Decimal: 233

Binary: 11101001

Explanation:

Extended ASCII uses 8 bits, so 'é' (233 in decimal) is represented as 11101001 in binary.
3. Unicode
Description: Unicode is a comprehensive standard designed to support characters from all
writing systems around the world. It assigns a unique code point to every character,
independent of how it is encoded.

Range: Over 1.1 million code points, covering most of the world's writing systems.

Example:

The character 'A' in Unicode:

Code Point: U+0041

The character '汉' (Chinese character for "Han") in Unicode:

Code Point: U+6C49

Explanation:

Unicode uses a code point to represent each character. The encoding specifies how these
code points are stored in memory.

4. UTF-8 (Unicode Transformation Format - 8-bit)


Description: UTF-8 is a variable-length encoding standard that encodes Unicode characters
using one to four bytes. It is backward compatible with ASCII and efficient for representing
English text while also supporting all Unicode characters.

Range: Each character can be 1 to 4 bytes.

Example:

The character 'A' in UTF-8:

1 byte: 01000001

The character '汉' in UTF-8:

3 bytes: 11100110 10110001 10001001

Explanation:

UTF-8 is designed to be efficient for ASCII characters (using only one byte) and flexible
enough to handle all Unicode characters with variable-length encoding.

Example: Encoding and Decoding


Let's go through an example of encoding and decoding a character using different standards.

Example: Encoding and decoding the character 'A'

1. ASCII:

Encoding: 'A' -> Decimal 65 -> Binary 01000001

Decoding: Binary 01000001 -> Decimal 65 -> 'A'

2. Extended ASCII:

Encoding: 'A' -> Decimal 65 -> Binary 01000001


Decoding: Binary 01000001 -> Decimal 65 -> 'A'
3. Unicode:

Encoding: 'A' -> Code Point U+0041

Decoding: Code Point U+0041 -> 'A'

4. UTF-8:

Encoding: 'A' -> Code Point U+0041 -> UTF-8 01000001 (1 byte)

Decoding: UTF-8 01000001 -> Code Point U+0041 -> 'A'

Importance of Character Encoding

Text Processing: Proper character encoding is essential for correctly displaying and
processing text in different languages.

Data Exchange: Ensures consistent interpretation of text data across different systems and
platforms.

Compatibility: UTF-8's backward compatibility with ASCII allows for seamless integration
with legacy systems.

Instruction Encoding in a Computer


Basics of Instruction Encoding

In a computer, instructions are encoded as binary numbers that the CPU can decode and execute.
These instructions are part of a machine language, which is a low-level language specific to a
computer's architecture. Each instruction tells the CPU what operation to perform and on which
data.

Components of an Instruction

An instruction typically consists of several components:

Opcode (Operation Code): Specifies the operation to be performed (e.g., add, subtract, load,
store).

Operands

: Specifies the data or the addresses of the data to be operated on. Operands can be:

Registers: Small, fast storage locations within the CPU.

Immediate values: Constants embedded in the instruction itself.

Memory addresses: Locations in RAM.

Instruction Formats

Different CPU architectures have different instruction formats. Common formats include:

RISC (Reduced Instruction Set Computing): Simple instructions that execute in a single
clock cycle.
CISC (Complex Instruction Set Computing): More complex instructions that can execute
multiple low-level operations.

Program Compilation in a Computer


Compilation is the process of converting high-level programming code into machine code that a
computer's CPU can execute. This process involves several stages, each transforming the source
code closer to executable machine code.

The compilation process typically involves the following stages:

1. Preprocessing

2. Compilation

3. Assembly

4. Linking

Stages of Compilation
1. Preprocessing

The preprocessing stage involves preparing the source code for compilation. This step includes:

Macro Expansion: Expanding macros defined with #define .

File Inclusion: Including header files specified with #include .

Conditional Compilation: Evaluating conditional directives such as #if , #ifdef , and


#endif .

2. Compilation

The compilation stage translates the preprocessed source code into assembly language. This
involves:

Syntax Analysis: Checking the syntax of the code.

Semantic Analysis: Ensuring the code makes sense semantically.

Intermediate Code Generation: Generating an intermediate representation of the code.

Optimization: Improving the efficiency of the intermediate code.

Code Generation: Translating the optimized intermediate code to assembly code.

3. Assembly

The assembly stage converts the assembly code into machine code (binary format). This is done
by the assembler, which translates each assembly instruction into its corresponding machine
instruction.

4. Linking

The linking stage combines multiple object files and libraries into a single executable file. This
involves:
Symbol Resolution: Resolving references to functions and variables across different object
files.

Address Binding: Assigning memory addresses to code and data.

Library Linking: Including external libraries required by the program.

Role of the Operating System in a Computer


Overview of the Operating System

The operating system (OS) is a fundamental piece of software that manages computer hardware
and software resources and provides services for computer programs. It acts as an intermediary
between users and the computer hardware.

Functions of the Operating System


1. Process Management

The OS manages processes in the system, including:

Process Scheduling: Allocating CPU time to various processes.

Process Creation and Termination: Creating and terminating processes as needed.

Process Synchronization and Communication: Ensuring processes can communicate and


operate without conflict.

Example: When you open a web browser, the OS creates a new process for it, allocates CPU time,
and manages its execution until you close the browser.

2. Memory Management

The OS handles the allocation and deallocation of memory spaces as needed by programs. It
ensures efficient use of memory and manages:

Main Memory: The RAM available for running programs.

Virtual Memory: Extending the available memory using disk space.

Example: When you run multiple applications, the OS allocates memory to each application and
uses virtual memory to handle situations where RAM is insufficient.

3. File System Management

The OS manages files and directories on storage devices. It provides:

File Creation and Deletion: Enabling users to create, delete, and modify files.

Directory Management: Organizing files into directories (folders).

File Access Control: Setting permissions to control access to files.

Example: When you save a document, the OS writes the data to the storage device and updates
the file directory.
4. Device Management

The OS manages hardware devices through device drivers, which are software components that
enable the OS to communicate with hardware peripherals. It handles:

Device Drivers: Software that communicates with hardware devices.

I/O Operations: Managing input/output operations and data transfers.

Example: When you print a document, the OS sends data to the printer through the printer driver.

5. User Interface

The OS provides user interfaces (UIs) for interaction, such as:

Command-Line Interface (CLI): Text-based interface for entering commands.

Graphical User Interface (GUI): Visual interface with windows, icons, and menus.

Example: Windows OS provides a GUI with a desktop, start menu, and taskbar for easy
interaction.

6. Security and Access Control

The OS ensures system security and controls access to resources by:

User Authentication: Verifying user identities (e.g., login credentials).

Access Control: Setting permissions for files and resources to ensure only authorized users
can access them.

Example: The OS requires a password to log in and allows setting file permissions to restrict
access.

Booting
Definition

Booting is the process of starting up a computer and loading the operating system into memory
so that the computer becomes ready for use.

Steps

1. Power-On: The computer is powered on, and the power supply activates.

2. POST (Power-On Self-Test): The BIOS checks the hardware components to ensure they are
functioning correctly.

3. Boot Loader: The BIOS locates and loads the boot loader from a bootable device.

4. OS Loading: The boot loader loads the operating system kernel into memory.

5. Initialization: The operating system initializes system settings and loads necessary drivers
and services.

Example
When you press the power button on your computer, the system undergoes the booting process,
eventually displaying the login screen for the operating system.

Bootstrap
Definition

Bootstrapping is the process by which a computer loads and initializes the operating system from
a powered-off state, starting from the BIOS executing initial instructions to loading the OS into
memory.

Steps

1. CPU Initialization: The CPU begins executing instructions from the BIOS.

2. POST: The BIOS performs hardware checks.

3. Boot Sequence: The BIOS follows the boot order to find a bootable device.

4. Boot Loader: The BIOS loads the boot loader from the bootable device.

5. OS Loading: The boot loader loads the operating system kernel.

6. System Handover: Control is handed over to the operating system.

Example

The bootstrapping process involves the BIOS loading the boot loader from the hard drive, which
then loads the operating system like Windows or Linux.

BIOS (Basic Input/Output System)


Definition

BIOS is firmware stored on a chip on the motherboard, responsible for initializing hardware
during the booting process and providing runtime services for operating systems and applications.

Functions

1. POST (Power-On Self-Test): Checks the integrity and functionality of hardware components.

2. Boot Loader Location: Identifies and loads the boot loader from a bootable device.

3. BIOS Setup Utility: Allows users to configure hardware settings and system parameters.

4. Hardware Initialization: Initializes hardware components before the operating system takes
over.

5. System Firmware Interface: Provides an interface between the operating system and the
hardware.

Example

When you start your computer, the BIOS performs a POST, loads the boot loader, and then hands
control over to the operating system.
Weekk-2 Week-4

Week 3 Notes
Week 3 Notes
C Program Structure
Keywords in C
Variables in C
Data Types in C
Operators in C
Expressions:
Operator Precedence and associativity
Input/Output (I/O) in C

C Program Structure
A C program consists of several components that determine its structure and behavior:

1. Preprocessor Directives:

Preprocessor directives are instructions to the preprocessor, which is a separate


program that processes the source code before actual compilation.

They start with a # symbol.

Common directives include #include for including header files and #define for
defining constants.

Example:

1 #include <stdio.h>
2 #define PI 3.14159

2. Global Declarations:

Global declarations include variable and function declarations that are accessible
throughout the program.

Global variables are defined outside of any function.

Global functions are declared before the main() function.

Example:

1 int globalVar = 10; // Global variable


2 int add(int a, int b); // Global function declaration

3. Function Declarations and Definitions:

Functions are blocks of code that perform specific tasks.


They can be declared and defined.

The main() function is the entry point of the program.

Example:

1 // Function declaration
2 int add(int a, int b);
3
4 // Function definition
5 int add(int a, int b)
6 {
7 return a + b;
8 }
9
10 int main()
11 {
12 // Main function code
13 return 0;
14 }

4. Statements and Expressions:

Statements are individual lines of code that perform actions.

Expressions are combinations of values, operators, and function calls.

Example:

1 int x = 5; // Statement
2 int sum = add(3, 4); // Expression using the add() function

5. Comments:

Comments are used for documentation and to improve code readability.

Single-line comments start with // , and multi-line comments are enclosed in /* */ .

Example:

1 // This is a single-line comment


2
3 /*
4 This is a
5 multi-line comment
6 */

6. Return Statement:

The return statement is used to specify the value to be returned from a function.

In the main() function, it indicates the program's exit status.

Example:
1 int add(int a, int b)
2 {
3 return a + b; // Return the sum of a and b
4 }
5
6 int main()
7 {
8 return 0; // Indicates successful program execution
9 }

Example Program:

Here's a complete C program with all the components discussed:

1 #include <stdio.h>
2
3 // Global variable declaration
4 int globalVar = 10;
5
6 // Function declaration
7 int add(int a, int b);
8
9 int main()
10 {
11 // Local variable declaration
12 int x = 5;
13
14 // Function call
15 int result = add(x, globalVar);
16
17 // Output
18 printf("Result: %d\n", result);
19
20 return 0; // Indicates successful program execution
21 }
22
23 // Function definition
24 int add(int a, int b)
25 {
26 return a + b;
27 }

Keywords in C
Keywords, also known as reserved words, are special words in C that have predefined meanings
and cannot be used as identifiers (variable names, function names, etc.). They serve as
fundamental building blocks of the language.

1. auto

2. break

3. case

4. char
5. const

6. continue

7. default

8. do

9. double

10. else

11. enum

12. extern

13. float

14. for

15. goto

16. if

17. inline

18. int

19. long

20. register

21. restrict

22. return

23. short

24. signed

25. sizeof

26. static

27. struct

28. switch

29. typedef

30. union

31. unsigned

32. void

33. volatile

34. while

Please note that the list above includes the standard C keywords, and some compilers or
environments may introduce additional keywords or extensions. It's important to avoid using
these reserved keywords as identifiers in your C programs to ensure correct and predictable
behavior.
Variables in C
1. What Are Variables:

Variables are named storage locations in computer memory that hold data.

They are used to store and manipulate data in a program.

2. Variable Declaration:

Before using a variable, you must declare it, specifying its data type.

Syntax: data_type variable_name;

Example:

1 int age; // Declaring an integer variable named 'age'

3. Variable Initialization:

Variables can be assigned initial values at the time of declaration.

Syntax: data_type variable_name = initial_value;

Example:

1 int count = 0; // Initializing an integer variable 'count' with the value


0

4. Naming Rules:

Variable names must follow certain rules:

They can include letters, digits, and underscores.

They must start with a letter or an underscore.

Variable names are case-sensitive (e.g., myVar and myvar are different).

C has reserved keywords that cannot be used as variable names (e.g., int , if ,
while , etc.).

Data Types in C
Data types define the type of data that can be stored in a variable. C provides several fundamental
data types:

1. int (Integer):

Used to store whole numbers (positive, negative, or zero).

Typically, 4 bytes in most systems.

Example:

1 int age = 25;

2. float (Floating-Point):

Used to store decimal numbers with single precision.

Typically, 4 bytes.
Example:

1 float price = 19.99;

3. double (Double Precision):

Used to store decimal numbers with double precision.

Typically, 8 bytes.

Example:

1 double pi = 3.14159265359;

4. char (Character):

Used to store single characters, enclosed in single quotes.

Typically, 1 byte.

Example:

1 char grade = 'A';

5. _Bool (Boolean):

Used for Boolean values, which are true (1) or false (0).

Typically, 1 byte.

Example:

1 _Bool isTrue = true;


2 _Bool isFalse = false;

6. void (Void):

Represents the absence of a value.

Typically used for functions that do not return a value.

Example:

1 void printMessage()
2 {
3 printf("Hello, World!\n");
4 }

7. Custom Data Types:

Programmers can define their own custom data types using struct , enum , and
typedef keywords.

Example (using struct ):


1 struct Point
2 {
3 int x;
4 int y;
5 };
6 struct Point p1;
7 p1.x = 5;
8 p1.y = 3;

Modifiers for Data Types:

C also provides modifiers that can be applied to data types:

1. short:

Used to reduce the storage size of an integer.

Example:

1 short int smallNumber = 100;

2. long:

Used to increase the storage size of an integer.

Example:

1 long int bigNumber = 1000000;

3. signed and unsigned:

Used with integer data types to indicate whether they can represent negative numbers
( signed ) or only non-negative numbers ( unsigned ).

Example:

1 unsigned int positiveNumber = 42;


2 signed int anyNumber = -10;

4. const:

Used to define constants that cannot be modified.

Example:

1 const double pi = 3.14159;

Operators in C
1. Arithmetic Operators:

Perform basic arithmetic operations.

Examples:

+ (Addition)
- (Subtraction)

* (Multiplication)

/ (Division)

% (Modulo, remainder)

Example:

1 int x = 5;
2 int y = 3;
3 int sum = x + y; // Addition
4 int diff = x - y; // Subtraction
5 int product = x * y; // Multiplication
6 int quotient = x / y; // Division
7 int remainder = x % y; // Modulo

2. Relational Operators:

Compare values and return true (1) or false (0).

Examples:

== (Equal to)

!= (Not equal to)

< (Less than)

> (Greater than)

<= (Less than or equal to)

>= (Greater than or equal to)

Example:

1 int a = 10;
2 int b = 5;
3 _Bool isEqual = (a == b); // Equal to (false)
4 _Bool isNotEqual = (a != b); // Not equal to (true)

3. Logical Operators:

Combine conditions and return true (1) or false (0).

Examples:

&& (Logical AND)

|| (Logical OR)

! (Logical NOT)

Example:

1 _Bool isTrue = 1;
2 _Bool isFalse = 0;
3 _Bool result1 = (isTrue && isFalse); // Logical AND (false)
4 _Bool result2 = (isTrue || isFalse); // Logical OR (true)
5 _Bool result3 = !isTrue; // Logical NOT (false)

4. Assignment Operators:
Assign values to variables and perform operations in one step.

Examples:

= (Assignment)

+= (Add and assign)

-= (Subtract and assign)

*= (Multiply and assign)

/= (Divide and assign)

%= (Modulo and assign)

Example:

1 int num = 5;
2 num += 3; // Add and assign (num is now 8)
3 num -= 2; // Subtract and assign (num is now 6)

5. Increment and Decrement Operators:

Increase or decrease variable values by 1.

Examples:

++ (Increment by 1)

-- (Decrement by 1)

Example:

1 int count = 10;


2 count++; // Increment by 1 (count is now 11)
3 count--; // Decrement by 1 (count is now 10 again)

Pre-increment ( ++var ) and Post-increment ( var++ ) Operators:

In C, the increment operator ( ++ ) is used to increase the value of a variable by 1. There are two
forms of the increment operator: pre-increment and post-increment.

1. Pre-increment ( ++var ):

In pre-increment, the value of the variable is incremented before its current value is
used in an expression.

The variable is increased by 1, and the updated value is used immediately.

Example:

1 int x = 5;
2 int y = ++x; // Pre-increment: x is incremented to 6, and then assigned
to y
3 // x is now 6, y is 6

2. Post-increment ( var++ ):

In post-increment, the value of the variable is used in an expression first, and then it is
incremented by 1.

The current value is used, and then the variable is increased.

Example:
1 int x = 5;
2 int y = x++; // Post-increment: x (5) is assigned to y first, then x is
incremented to 6
3 // x is now 6, y is 5

Key Points:

Both pre-increment and post-increment operators increase the value of the variable by 1.

The key difference lies in when the increment occurs in relation to the use of the variable in
an expression.

Pre-increment updates the variable and then uses it, while post-increment uses the variable
and then updates it.

Expressions:
An expression is a combination of values, variables, operators, and function calls that results in a
single value.

Example:

1 int x = 5;
2 int y = 3;
3 int result = x + y; // Expression that calculates the sum of x and y

Operator Precedence and associativity


Operator precedence defines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated first. Here is a summary of operator precedence
in C:

1. Parentheses () (highest precedence)

2. Unary Operators ++ , -- , + , - , !

3. Multiplication \* , Division / , Modulo %

4. Addition + , Subtraction -

5. Relational Operators < , <= , > , >=

6. Equality Operators == , !=

7. Logical AND &&

8. Logical OR ||

9. Assignment Operators = , += , -=

10. Comma , (lowest precedence)

Example:

1 int a = 5, b = 3, c = 10;
2 int result = (a + b) * c; // Parentheses have the highest precedence

Associativity in C:
Associativity refers to the order in which operators with the same precedence are evaluated in an
expression. In C, most operators have left-to-right associativity, meaning they are evaluated from
left to right within the expression. However, there are exceptions where operators have right-to-
left associativity.

Left-to-Right Associativity:

Operators with left-to-right associativity are evaluated from left to right when they have the same
precedence. Some common operators with left-to-right associativity include:

1. Arithmetic Operators:

Addition ( + )

Subtraction ( - )

Multiplication ( * )

Division ( / )

Modulo ( % )

Example:

1 int result = 5 + 3 - 2; // Left-to-right: (5 + 3) - 2 = 6

2. Logical Operators:

Logical AND ( && )

Logical OR ( || )

Example:

1 _Bool a = 1, b = 0, c = 1;
2 _Bool result = a && b || c; // Left-to-right: (a && b) || c

Right-to-Left Associativity:

Operators with right-to-left associativity are evaluated from right to left when they have the same
precedence. The most common operator with right-to-left associativity is the assignment operator
( = ).

Example:

1 int x, y, z;
2 x = y = z = 5; // Right-to-left: z is assigned 5, then y is assigned the
value of z (5), and finally x is assigned the value of y (5)

Input/Output (I/O) in C
Input and output operations are fundamental for interacting with users and handling data in C
programs. The C standard library provides functions for performing I/O operations.

Standard I/O Functions:

1. printf():
Used for formatted output.

Format specifiers are placeholders for values.

Example:

1 int age = 25;


2 printf("My age is %d years old.", age);

2. scanf():

Used for formatted input.

Requires format specifiers to read data into variables.

Example:

1 int num;
2 printf("Enter a number: ");
3 scanf("%d", &num);

3. getchar() and putchar():

Used for character input and output.

getchar() reads a single character from input.

putchar() displays a single character as output.

Example:

1 char ch;
2 printf("Enter a character: ");
3 ch = getchar();
4 putchar(ch);
Weekk-3 Week-5

Week 4 - Control Statements

Week 4 - Control Statements


Control Statements
Conditional Statement in C
1. if Statement:
2. if-else Statement:
3. if-else if-else Statement:
4. switch Statement:
Nested conditional statements
Loop in C
1. for loop
2. while loop
3. do-while loop
Nested Loop
break, continue, goto statements
1. break Statement:
2. continue Statement:
3. goto Statement:
Control Statement Writing Format
1. Single-Line Statement Format:
2. Multi-Line Statement Format:

Control Statements
Conditional Statement in C
1. if Statement:
The if statement allows you to execute a block of code based on a condition. If the condition is
true, the code block is executed; otherwise, it's skipped.

Control Flow:
Syntax:

1 if (condition)
2 {
3 // Code to be executed if the condition is true
4 }

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 int x = 10;
6 if (x > 5)
7 {
8 printf("x is greater than 5\n");
9 }
10 return 0;
11 }

2. if-else Statement:
The if-else statement is used to execute if block of code when the if condition is true
otherwise else block will be execute.

Control flow:
Syntax:

1 if (condition)
2 {
3 // Code to be executed if the condition is true
4 }
5 else
6 {
7 // Code to be executed if the condition is false
8 }

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 int x = 3;
6 if (x > 5)
7 {
8 printf("x is greater than 5\n");
9 }
10 else
11 {
12 printf("x is not greater than 5\n");
13 }
14 return 0;
15 }
3. if-else if-else Statement:
The if-else if-else statement is used to check multiple conditions in sequence. It comes after
the initial if statement and is executed only if the previous conditions are false.

Control flow:

Syntax:

1
2 if (condition1)
3 {
4 // Code to be executed if condition1 is true
5 }
6 else if (condition2)
7 {
8 // Code to be executed if condition2 is true
9 }
10 else
11 {
12 // Code to be executed if none of the conditions are true
13 }

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 int x = 10;
6 if (x > 15)
7 {
8 printf("x is greater than 15\n");
9 }
10 else if (x > 5)
11 {
12 printf("x is greater than 5 but not greater than 15\n");
13 }
14 else
15 {
16 printf("x is not greater than 5\n");
17 }
18 return 0;
19 }

4. switch Statement:
The switch statement is a powerful control structure that allows you to select one of many code
blocks to be executed based on the value of an expression. It's especially useful when you have
multiple cases to handle and want to avoid using a series of if-else statements.

Control Flow:

Syntax:
1 switch (expression)
2 {
3 case value1:
4 // Code to be executed if expression is equal to value1
5 break;
6 case value2:
7 // Code to be executed if expression is equal to value2
8 break;
9 // ...
10 default:
11 // Code to be executed if none of the cases match
12 }

Here are some important points to note about the switch statement:

1. The switch statement evaluates the expression and then checks it against each case
label. It compares the expression with the value associated with each case . If a match is
found, the corresponding code block is executed. If no match is found, the code within the
default block (if present) is executed.

2. The break statement is crucial in each case . Without it, the execution will "fall through" to
the next case , and all subsequent code blocks will be executed until a break is encountered
or until the end of the switch statement. This behavior can be used intentionally in some
cases, but it's important to be aware of it.

3. The default case is optional. If none of the case values matches the expression , the code
block within the default case is executed.

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 int day = 2;
6 switch (day)
7 {
8 case 1:
9 printf("Monday\n");
10 break;
11 case 2:
12 printf("Tuesday\n");
13 break;
14 case 3:
15 printf("Wednesday\n");
16 break;
17 default:
18 printf("Other day\n");
19 }
20 return 0;
21 }
In this example, the switch statement evaluates the day variable, which is set to 2. Since day
matches the case 2 , "Tuesday" is printed. The break statements ensure that only the code block
corresponding to the matched case is executed.

If we had omitted the break statements, the program would continue to execute code for
all subsequent cases after matching the first one.

The switch statement is a clean and efficient way to handle multiple conditions, especially when
you have a lot of cases to consider, making your code more readable and maintainable.

Nested conditional statements


Nested conditional statements in C refer to the use of one or more conditional statements (such
as if , else if , or else ) inside another conditional statement. They allow for more complex
decision-making within your code, enabling you to evaluate multiple conditions in a hierarchical
manner. Here are some short notes on nested conditional statements along with examples:

1. Structure: In nested conditional statements, you have one or more conditional statements
inside another conditional statement. The inner conditionals are entirely contained within the
body of the outer conditional.

2. Execution: The outer conditional statement is evaluated first. Depending on its result, the
code inside the corresponding block is executed. Within each block, you may have additional
conditional statements to further refine the decision-making process.

3. Example 1: Nested if Statements:

1 #include <stdio.h>
2
3 int main()
4 {
5 int age = 25;
6 int hasID = 1;
7 int hasTicket = 0;
8
9 if (age >= 18)
10 {
11 if (hasID)
12 {
13 printf("You can enter the event.\n");
14 }
15 else
16 {
17 printf("You need an ID to enter.\n");
18 }
19 }
20 else
21 {
22 printf("You are too young to enter.\n");
23 }
24
25 return 0;
26 }
In this example, nested if statements are used to determine if a person can enter an event.
The outer if checks the age, and the inner if checks for an ID.
4. Use Cases:

Nested conditional statements are helpful when you need to evaluate multiple
conditions in a hierarchical manner.

They are used to handle more complex decision-making logic, especially when different
conditions need to be checked one after another.

5. Example 2: Nested if-else Statements:

1 #include <stdio.h>
2
3 int main() {
4 int num = 15;
5
6 if (num > 0)
7 {
8 printf("The number is positive.\n");
9 }
10 else if (num < 0)
11 {
12 printf("The number is negative.\n");
13 }
14 else
15 {
16 printf("The number is zero.\n");
17 }
18
19 return 0;
20 }

In this example, nested if-else statements are used to determine whether a number is
positive, negative, or zero.

6. Proper Indentation: To enhance code readability, it's crucial to use proper indentation when
working with nested conditional statements. Each level of indentation should reflect the
nesting level of the conditionals.

Nested conditional statements allow for more complex and structured decision-making within
your code. Proper organization, indentation, and comments (where necessary) are essential to
maintain code clarity and readability in such cases.

Loop in C
1. for loop
A for loop in C is a control structure used for repetitive execution of a block of code. It is
particularly useful when you know in advance how many times you want a certain set of
instructions to be repeated. The for loop is made up of three parts: initialization, condition, and
increment/decrement, each separated by a semicolon.

Control Flow:
Syntax:

The basic structure of a for loop is as follows:

1 for (initialization; condition; update(increment/decrement))


2 {
3 // Code to be executed repeatedly as long as the condition is true
4 }

Here are detailed notes on the for loop in C along with examples:

1. Initialization: The initialization part is executed only once at the beginning of the loop. It is
typically used to initialize loop control variables. This is where you set the starting value for
the loop.

2. Condition: The condition is a Boolean expression that is evaluated before each iteration of
the loop. If the condition is true, the loop continues; if it's false, the loop terminates.

3. Increment/Decrement: The increment/decrement part is executed at the end of each loop


iteration, just before the condition is checked again. It is typically used to modify the loop
control variable, progressing toward the loop termination condition.

Example 1: Counting from 1 to 5


1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 1; i <= 5; i++)
6 {
7 printf("%d\n", i);
8 }
9 return 0;
10 }

In this example, the loop initializes i to 1, checks if i is less than or equal to 5, and increments i
by 1 in each iteration. The loop continues to execute until i is no longer less than or equal to 5.

Loop Body: The code inside the curly braces {} is the body of the loop. It contains the statements
to be executed repeatedly as long as the condition is true. You can have multiple statements in the
loop body, and they are executed sequentially.

Example 2: Sum of First 10 Natural Numbers

1 #include <stdio.h>
2
3 int main() {
4 int sum = 0;
5 for (int i = 1; i <= 10; i++)
6 {
7 sum += i; // Equivalent to: sum = sum + i;
8 }
9 printf("Sum of the first 10 natural numbers: %d\n", sum);
10 return 0;
11 }

In this example, the for loop calculates the sum of the first 10 natural numbers by iteratively
adding each number to the sum variable.

Termination: The for loop continues to execute as long as the condition is true. When the
condition becomes false, the loop terminates, and program control moves to the code following
the loop.

Example 3: Printing Numbers in Reverse

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 10; i >= 1; i--)
6 {
7 printf("%d\n", i);
8 }
9 return 0;
10 }

In this example, the for loop counts down from 10 to 1, printing the numbers in reverse order.
Infinite Loops: Be cautious when using for loops to avoid infinite loops, where the condition
never becomes false. This can lead to a program that never terminates.

Example 4: Infinite Loop (Avoid This)

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 1; i <= 5;)
6 {
7 printf("%d\n", i);
8 }
9 return 0;
10 }

In this example, variable i is not updating to reach till termination condition, the loop will never
terminate because i is always 1.

2. while loop
A "while loop" in C is a control structure used for repetitive execution of a block of code as long as
a certain condition is true. It is particularly useful when you don't know in advance how many
times the loop should execute and want to keep executing as long as a specific condition holds.

Control Flow:
Syntax:

The basic structure of a while loop is as follows:

1 while (condition)
2 {
3 // Code to be executed repeatedly as long as the condition is true
4 }

Here are detailed notes on the while loop in C along with examples:

Condition: The loop begins by evaluating the condition . If the condition is true, the code inside
the loop's body is executed. If the condition is false, the loop terminates, and program control
moves to the code following the loop.

Example 1: Counting from 1 to 5

1 #include <stdio.h>
2
3 int main()
4 {
5 int i = 1;
6 while (i <= 5)
7 {
8 printf("%d\n", i);
9 i++;
10 }
11 return 0;
12 }

In this example, the while loop starts with i set to 1 and checks if i is less than or equal to 5. As
long as this condition is true, the loop body is executed.

Loop Body: The code inside the curly braces {} is the body of the loop. It contains the statements
to be executed repeatedly as long as the condition is true. You can have multiple statements in the
loop body, and they are executed sequentially.

Example 2: Sum of Numbers

1 #include <stdio.h>
2
3 int main()
4 {
5 int sum = 0;
6 int number;
7 printf("Enter numbers (enter 0 to stop): ");
8 scanf("%d", &number);
9 while (number != 0)
10 {
11 sum += number;
12 scanf("%d", &number);
13 }
14 printf("Sum: %d\n", sum);
15 return 0;
16 }

In this example, the while loop reads numbers from the user and calculates their sum. The loop
continues until the user enters 0.

Infinite Loops: Be cautious when using while loops to avoid infinite loops, where the condition
never becomes false. This can lead to a program that never terminates.

Example 3: Infinite Loop (Avoid This)

1 #include <stdio.h>
2
3 int main()
4 {
5 while(1)
6 {
7 printf("This is an infinite loop.\n");
8 }
9 return 0;
10 }

In this example, the loop's condition is always true ( 1 is always true), and the loop will continue
indefinitely. It should be avoided or have a termination condition inside the loop.

Termination Condition: A while loop should have a well-defined termination condition to


ensure that it eventually ends. Without a termination condition, the loop will run indefinitely.

Example 4: Termination Condition

1 #include <stdio.h>
2
3 int main()
4 {
5 int i = 10;
6 while (i > 0)
7 {
8 printf("%d\n", i);
9 i--;
10 }
11 return 0;
12 }

In this example, the loop continues as long as i is greater than 0. It decrements i in each
iteration, ensuring the loop will eventually terminate.
3. do-while loop
A do-while loop in C is a control structure used for repetitive execution of a block of code as long
as a certain condition is true, similar to the "while loop." However, the key difference is that the
"do-while loop" guarantees that the code inside the loop is executed at least once, even if the
condition is initially false.

Control flow:

Syntax:

The basic structure of a do-while loop is as follows:

1 do
2 {
3 // Code to be executed repeatedly
4 } while (condition);

Here are detailed notes on the do-while loop in C along with examples:

Execution: In a do-while loop, the code inside the loop is executed first, and then the condition
is checked. If the condition is true, the loop continues; if it's false, the loop terminates.

Example 1: Counting from 1 to 5


1 #include <stdio.h>
2
3 int main()
4 {
5 int i = 1;
6 do
7 {
8 printf("%d\n", i);
9 i++;
10 } while (i <= 5);
11 return 0;
12 }

In this example, the do-while loop starts with i set to 1. The code inside the loop body is
executed at least once before the condition is checked.

Loop Body: The code inside the curly braces {} is the body of the loop. It contains the statements
to be executed repeatedly as long as the condition is true, similar to the "while loop."

Example 2: Sum of Numbers

1 #include <stdio.h>
2
3 int main()
4 {
5 int sum = 0;
6 int number;
7 do
8 {
9 printf("Enter a number (enter 0 to stop): ");
10 scanf("%d", &number);
11 sum += number;
12 } while (number != 0);
13 printf("Sum: %d\n", sum);
14 return 0;
15 }

In this example, the do-while loop reads numbers from the user and calculates their sum. The
loop continues until the user enters 0.

Infinite Loops: Just like in the "while loop," be cautious when using do-while loops to avoid
infinite loops. Make sure the termination condition is eventually met to prevent indefinite
execution.

Example 3: Infinite Loop (Avoid This)


1 #include <stdio.h>
2
3 int main()
4 {
5 do
6 {
7 printf("This is an infinite loop.\n");
8 } while (1);
9 return 0;
10 }

In this example, the loop's condition is always true ( 1 is always true), and the loop will continue
indefinitely. It should be avoided or have a termination condition inside the loop.

Termination Condition: A do-while loop should have a well-defined termination condition to


ensure that it eventually ends. Without a termination condition, the loop may run indefinitely.

Example 4: Termination Condition

1 #include <stdio.h>
2
3 int main()
4 {
5 int i = 10;
6 do
7 {
8 printf("%d\n", i);
9 i--;
10 } while (i > 0);
11 return 0;
12 }

In this example, the loop continues as long as i is greater than 0, ensuring that it will eventually
terminate.

Use Cases: do-while loops are useful when you want to ensure that a block of code is executed
at least once, even if the initial condition is false. It is also beneficial when you need to repeatedly
prompt the user for input until a specific condition is met.

Nested Loop
Nested loops in C refer to the use of one or more loops inside another loop. These nested loops
are particularly useful when you need to handle more complex patterns, multi-dimensional data
structures, or situations that require multiple levels of iteration. Here are some short notes on
nested loops along with examples:

1. Structure: In nested loops, you have one loop (e.g., for , while , or do-while ) inside
another loop. The inner loop is entirely contained within the body of the outer loop.

2. Execution: The outer loop executes the inner loop repeatedly as long as its condition
remains true. Each iteration of the outer loop triggers multiple iterations of the inner loop.
3. Example 1: Printing a Rectangle Pattern (Using Nested for Loops):

1 #include <stdio.h>
2
3 int main()
4 {
5 int rows = 4;
6 int columns = 6;
7
8 for (int i = 1; i <= rows; i++)
9 {
10 for (int j = 1; j <= columns; j++)
11 {
12 printf("* ");
13 }
14 printf("\n");
15 }
16
17 return 0;
18 }

In this example, nested for loops are used to print a rectangle pattern of asterisks. The
outer loop controls the number of rows, and the inner loop controls the number of asterisks
in each row.

4. Use Cases:

Nested loops are helpful for handling multi-dimensional data structures like matrices,
arrays, or tables.

They are used to traverse and manipulate two-dimensional or multi-dimensional arrays.

Nested loops are commonly used to create patterns, such as triangles, rectangles, and
more complex shapes.

5. Example 2: Multiplication Table (Using Nested for Loops):

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 1; i <= 10; i++)
6 {
7 for (int j = 1; j <= 10; j++)
8 {
9 printf("%3d ", i * j);
10 }
11 printf("\n");
12 }
13
14 return 0;
15 }

In this example, nested for loops are used to create a multiplication table from 1 to 10. The
outer loop controls the multiplicand ( i ), and the inner loop controls the multiplier ( j ).
6. Proper Indentation: To enhance code readability, it's crucial to use proper indentation when
working with nested loops. Each level of indentation should reflect the nesting level of the
loop.

Nested loops allow for more intricate and structured control over iterations, especially when
dealing with multi-dimensional data or complex patterns. Proper organization and indentation are
essential to maintain code clarity and readability in such cases.

break, continue, goto statements


1. break Statement:

Purpose: The break statement is used to exit a loop prematurely, even if the loop's
condition is still true. It is often used to break out of loops based on specific conditions.

Usage: In a loop, when the break statement is encountered, the loop is terminated, and the
program control moves to the statement immediately following the loop.

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 1; i <= 10; i++)
6 {
7 if (i == 5)
8 {
9 break; // Exit the loop when i is 5
10 }
11 printf("%d ", i);
12 }
13 return 0;
14 }

In this example, the loop terminates early when i equals 5, and the program control moves to the
statement after the loop.

2. continue Statement:

Purpose: The continue statement is used to skip the current iteration of a loop and
immediately proceed to the next iteration. It is often used to bypass specific actions within a
loop for certain conditions.

Usage: When a continue statement is encountered in a loop, the current iteration is


skipped, and the loop proceeds with the next iteration.

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 1; i <= 10; i++)
6 {
7 if (i % 2 == 0)
8 {
9 continue; // Skip even numbers
10 }
11 printf("%d ", i);
12 }
13 return 0;
14 }

In this example, the continue statement is used to skip even numbers ( i % 2 == 0 ), resulting in
the printing of only odd numbers.

3. goto Statement:

Purpose: The goto statement is used to transfer program control to a specific labeled
statement within the same function. It provides a way to create non-linear control flow in
your code.

Usage: You use the goto statement with a label and a colon. When the goto statement is
encountered, program control jumps to the labeled statement.

Example:

1 #include <stdio.h>
2
3 int main()
4 {
5 int i = 1;
6
7 start: // Label
8 if (i <= 10)
9 {
10 printf("%d ", i);
11 i++;
12 goto start; // Jump to the 'start' label
13 }
14
15 return 0;
16 }

In this example, the goto statement is used to create a loop-like structure. It jumps back to the
start label as long as the condition is true.

Caution: The use of goto is discouraged in modern programming practices because it can lead to
complex and hard-to-maintain code. It's generally considered a best practice to use structured
control flow constructs like for , while , and if whenever possible.
Control Statement Writing Format
1. Single-Line Statement Format:
Definition:

In the single-line statement format, control statements are written on a single line without
enclosing the block of code within curly braces {} .

This format is typically used when you have a single statement to execute based on a
condition or iteration.

It is concise and suitable for simple, one-liner statements.

Syntax:

1 if (condition) statement;

Example 1 (Single-Line if statement):

1 #include <stdio.h>
2 int main()
3 {
4 int num = 10;
5 if (num > 0) printf("Number is positive\n");
6 return 0;
7 }

Example 2 (Single-Line for loop):

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 0; i < 5; i++) printf("%d ", i);
6 return 0;
7 }

Use Cases:

This format is suitable for simple and concise code where only one statement needs to be
executed.

It is useful when code brevity is a priority.

Pros:

Compact and space-efficient.

Suitable for straightforward and short statements within control structures.

Reduces visual clutter when dealing with short statements.

Cons:

Less readable for complex logic or code with multiple statements.

Not suitable for organizing and grouping extensive code sections.


2. Multi-Line Statement Format:
Definition:

In the multi-line statement format, control statements are enclosed within curly braces {} to
represent a block of code.

This format is used for complex logic or code sections that include multiple statements.

It enhances code readability and maintainability by providing a structured way to group


multiple statements.

Syntax:

1 if (condition)
2 {
3 statement1;
4 statement2;
5 // ...
6 }

Example 1 (Multi-Line if statement):

1 #include <stdio.h>
2
3 int main()
4 {
5 int num = 10;
6 if (num > 0)
7 {
8 printf("Number is positive\n");
9 printf("This is a multi-line statement.\n");
10 }
11 return 0;
12 }

Example 2 (Multi-Line for loop):

1 #include <stdio.h>
2
3 int main()
4 {
5 for (int i = 0; i < 5; i++)
6 {
7 printf("%d ", i);
8 printf("This is a multi-line statement.\n");
9 }
10 return 0;
11 }

Use Cases:
This format is essential for organizing and grouping multiple statements, especially in
complex logic.

It enhances code readability and maintainability for code with extensive logic or multiple
statements.

Pros:

Provides a structured way to group and organize multiple statements.

Improves code readability for complex logic.

Cons:

Takes up more space in the source code compared to single-line blocks.

You might also like