Notes 1-4
Notes 1-4
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.
Volatile memory, meaning data is lost when the computer is powered off.
3. Storage Devices:
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:
5. Output Devices:
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.
Input devices such as keyboards, mice, and touchscreens are used to enter data.
2. Processing Stage:
Data and instructions are sent to the Central Processing Unit (CPU).
The CPU decodes instructions and performs calculations and logical operations.
3. Memory Storage:
RAM (Random Access Memory): Temporary storage used for active processes.
Secondary Storage (Hard Drives, SSDs): Long-term storage for files and programs.
4. Control Unit:
It fetches instructions from memory, decodes them, and directs the CPU accordingly.
The ALU performs arithmetic operations (addition, subtraction, multiplication, division) and
logical operations (AND, OR, NOT).
6. Output Stage:
8. Communication:
This allows data exchange over the internet, LANs, and WANs.
9. Software:
Software consists of programs and instructions that tell the computer what to do.
Computers use binary code (0s and 1s) to represent data and instructions.
The CPU (Central Processing Unit) is the primary component of a computer responsible for
executing instructions and performing calculations.
Source: WikiPedia
Key Components:
Controls the flow of data and instructions within the CPU and between other hardware
components.
3. Registers:
Includes the program counter (PC), instruction register (IR), and general-purpose
registers.
Functions:
1. Instruction Execution:
2. Data Processing:
3. Control of Peripherals:
Communicates with input and output devices to manage data transfer.
Accesses and manages data stored in RAM and other memory locations.
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.
1. Registers:
Purpose:
Registers are the smallest and fastest memory units within the CPU.
Usage:
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:
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.
2. Algorithms:
3. Data Structures:
Data structures are ways to organize and store data efficiently, making it easier to
manipulate and access.
4. Software Development Cycle:
Purpose of Programming:
1. Automation:
2. Problem Solving:
It provides tools to tackle complex problems in various fields, from science and
engineering to finance and entertainment.
3. Creating Software:
4. Innovation:
Programming Process:
3. Writing Code:
Verify that the program works correctly and fix any errors (bugs).
5. Optimization:
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:
2. Text Editors:
Simple tools for writing and editing code, often used by experienced programmers.
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).
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:
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.
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:
Control Structures: Statements for making decisions (if-else), loops (for, while), and
branching.
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.
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:
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)
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:
Explanation:
Conversion Example:
Example:
Explanation:
To convert an octal number to decimal, sum the products of each digit and its corresponding
power of 8.
Conversion Example:
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:
Conversion Example:
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).
Example:
To convert a hexadecimal number to decimal, sum the products of each digit and its
corresponding power of 16.
Conversion Example:
2. Decimal to Octal:
3. Octal to Binary:
Result:
4. Decimal to Hexadecimal:
255 ÷ 16 = 15 remainder 15
15 ÷ 16 = 0 remainder 15
Write remainders in reverse: FF
255 = FF in hexadecimal.
5. Hexadecimal to Decimal:
1 * 256 + 10 * 16 + 3 * 1
256 + 160 + 3
419
6. Binary to Hexadecimal:
Result:
7. Hexadecimal to Binary
3 = 0011
F = 1111
Result: 00111111
Example:
+18: 00010010
-18: 10010010
Explanation:
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:
+18: 00010010
Explanation:
This is the most commonly used method because it simplifies arithmetic operations.
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.
The IEEE 754 standard is the most widely used format for floating-point arithmetic. It defines two
main formats:
Single Precision (32-bit)
Where:
bias: A constant used to adjust the range of the exponent (127 for single precision, 1023 for
double precision).
1. Convert to Binary:
2. Normalize:
3. Determine Components:
4. Combine:
1 | 10000001 | 01110000000000000000000
Explanation:
Sign bit is 1.
Mantissa is the binary digits after the decimal point, padded to 23 bits.
1. Convert to Binary:
2. Normalize:
3. Determine Components:
4. Combine:
1 | 10000000001 | 0111000000000000000000000000000000000000000000000000
Explanation:
Sign bit is 1.
Mantissa is the binary digits after the decimal point, padded to 52 bits.
6. Special Values
Zero: Represented by all bits in the exponent and mantissa being zero.
Infinity: Represented by all bits in the exponent being ones and all bits in the mantissa being
zero.
NaN (Not a Number): Represented by all bits in the exponent being ones and at least one
bit in the mantissa being non-zero.
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 .
2. Normalize:
3. Determine Components:
4. Combine:
0 | 10000010 | 01001100000000000000000
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:
Extended ASCII
Unicode
UTF-8
Range: 0 to 127.
Characters: Includes control characters (e.g., newline, tab) and printable characters (e.g.,
letters, digits, punctuation).
Example:
Decimal: 65
Binary: 01000001
Explanation:
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:
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:
Explanation:
Unicode uses a code point to represent each character. The encoding specifies how these
code points are stored in memory.
Example:
1 byte: 01000001
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.
1. ASCII:
2. Extended ASCII:
4. UTF-8:
Encoding: 'A' -> Code Point U+0041 -> UTF-8 01000001 (1 byte)
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.
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
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:
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.
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:
2. Compilation
The compilation stage translates the preprocessed source code into assembly language. This
involves:
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.
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.
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:
Example: When you run multiple applications, the OS allocates memory to each application and
uses virtual memory to handle situations where RAM is insufficient.
File Creation and Deletion: Enabling users to create, delete, and modify 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:
Example: When you print a document, the OS sends data to the printer through the printer driver.
5. User Interface
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.
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.
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.
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 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:
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.
Example:
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 }
Example:
1 int x = 5; // Statement
2 int sum = add(3, 4); // Expression using the add() function
5. Comments:
Example:
6. Return Statement:
The return statement is used to specify the value to be returned from a function.
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:
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.
2. Variable Declaration:
Before using a variable, you must declare it, specifying its data type.
Example:
3. Variable Initialization:
Example:
4. Naming Rules:
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):
Example:
2. float (Floating-Point):
Typically, 4 bytes.
Example:
Typically, 8 bytes.
Example:
1 double pi = 3.14159265359;
4. char (Character):
Typically, 1 byte.
Example:
5. _Bool (Boolean):
Used for Boolean values, which are true (1) or false (0).
Typically, 1 byte.
Example:
6. void (Void):
Example:
1 void printMessage()
2 {
3 printf("Hello, World!\n");
4 }
Programmers can define their own custom data types using struct , enum , and
typedef keywords.
1. short:
Example:
2. long:
Example:
Used with integer data types to indicate whether they can represent negative numbers
( signed ) or only non-negative numbers ( unsigned ).
Example:
4. const:
Example:
Operators in C
1. Arithmetic Operators:
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:
Examples:
== (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:
Examples:
|| (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)
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)
Examples:
++ (Increment by 1)
-- (Decrement by 1)
Example:
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.
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.
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
2. Unary Operators ++ , -- , + , - , !
4. Addition + , Subtraction -
6. Equality Operators == , !=
8. Logical OR ||
9. Assignment Operators = , += , -=
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:
2. Logical Operators:
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.
1. printf():
Used for formatted output.
Example:
2. scanf():
Example:
1 int num;
2 printf("Enter a number: ");
3 scanf("%d", &num);
Example:
1 char ch;
2 printf("Enter a character: ");
3 ch = getchar();
4 putchar(ch);
Weekk-3 Week-5
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.
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.
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.
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:
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.
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.
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.
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.
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:
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.
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.
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.
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.
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:
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.
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."
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.
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.
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.
Nested loops are commonly used to create patterns, such as triangles, rectangles, and
more complex shapes.
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.
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.
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.
Syntax:
1 if (condition) 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 }
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.
Pros:
Cons:
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.
Syntax:
1 if (condition)
2 {
3 statement1;
4 statement2;
5 // ...
6 }
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 }
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:
Cons: