0% found this document useful (0 votes)
5 views19 pages

Intro To Prog.-2

c prog

Uploaded by

Suman Chatterjee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views19 pages

Intro To Prog.-2

c prog

Uploaded by

Suman Chatterjee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

Computational aspects of Programming (2)

A computer system is a complex arrangement of various components that work together to


process data and produce meaningful results. Let us break down each part, diving deep into the
individual components and how they collaborate to make a computer function.

1. Input Devices

Input devices allow a user to send data or commands to the computer. They serve as the interface
between the external environment (you) and the computer system.

Key Input Devices

● Keyboard: The most common input device, it allows users to input text, commands, and
control a computer. Each key on the keyboard represents an individual character or
function.
● Mouse: A pointing device that allows the user to interact with the graphical user interface
(GUI) by selecting items, clicking buttons, and performing drag-and-drop operations.
● Scanner: Converts physical documents into digital images or text. Often used in
applications like optical character recognition (OCR).
● Microphone: Captures audio input, enabling the computer to process and store voice
data.
● Touchscreen: Combines the functionality of an input and output device, allowing users
to interact with the system directly by touching the display screen.
● Camera/Webcam: Captures visual data (images or video) for applications like video
conferencing, photography, or machine vision.

Each of these devices translates human actions into a language that the computer can understand,
usually through binary signals or specific device drivers that interpret input into
machine-readable data.

2. Output Devices

Once the computer processes data, it needs a way to communicate the results to the user or
another system. Output devices are responsible for this.

Key Output Devices

● Monitor/Display: The most common output device, it visually presents the results of
computer operations. There are several types of displays, including—
○ LCD (Liquid Crystal Display)
○ LED (Light Emitting Diode)
○ OLED (Organic Light Emitting Diode)
○ QLED (Quantum Light Emitting Diode)
● Printer: Converts digital documents into physical form on paper. Printers come in
various types, like inkjet, laser, and dot matrix, each serving different purposes based
on speed, quality, and cost.
● Speakers/Headphones: Produce audio output, translating digital audio data into sound
waves. These are used for a range of applications, from entertainment (music, movies) to
system alerts and speech synthesis.
● Projectors: Display output on a larger scale, typically used in classrooms, meetings, or
theaters. Projectors are useful when the visual content needs to be shared with large
audiences.

These devices help users experience the result of computation in a form they can easily interpret,
whether it be through visuals, sound, or printed documents.

3. Storage Units

Storage is critical to any computer system as it holds both the data and instructions necessary for
the system to function. There are two major types of storage —

A. Primary Storage (Volatile Memory)

Primary storage refers to memory that the CPU can access directly and use for current
operations. It is fast but volatile, meaning it loses data when the power is turned off.

● RAM (Random Access Memory): This is the working memory of the computer. When
you open a program, it is loaded into RAM from your secondary storage so the CPU can
access it quickly. RAM is much faster than secondary storage but has a smaller capacity.
Data in RAM is temporary.
○ Types of RAM:
■ DRAM (Dynamic RAM): Most common; requires constant refreshing of
the data.
■ SRAM (Static RAM): Faster and more reliable but more expensive. Used
in cache memory.

B. Secondary Storage (Non-Volatile Memory)

Secondary storage refers to long-term storage that retains data even when the computer is turned
off. It is slower than primary storage but has a much larger capacity.
● Hard Disk Drive (HDD): Traditional mechanical drives that store data magnetically.
They offer large storage capacities at a relatively low cost but are slower compared to
newer storage technologies.
● Solid State Drive (SSD): Faster than HDDs, SSDs use flash memory to store data. They
have no moving parts, making them more durable and energy-efficient. However, they
are more expensive per unit of storage.
● Optical Discs (CDs, DVDs, Blu-rays): These are used for portable, removable storage
and are read by a laser. They are typically slower and store less data compared to hard
drives or SSDs.
● USB Flash Drives and External Hard Drives: Portable storage devices used for
transferring data between systems.
● Cloud Storage: Data is stored on remote servers accessible via the internet, providing
convenience and scalability but often relying on a stable network connection.

4. Central Processing Unit (CPU)

The CPU is the "brain" of the computer and executes instructions. It performs the basic
arithmetic, logical, control, and input/output (I/O) operations specified by the instructions in the
programs.

Components of the CPU

● Arithmetic and Logic Unit (ALU): Responsible for performing arithmetic operations
(like addition, subtraction) and logical operations (such as AND, OR, NOT).
● Control Unit (CU): Directs all operations in the computer. It reads instructions from
memory, decodes them, and instructs other parts of the computer on how to execute them.
The control unit manages the flow of data between the CPU, memory, and peripherals.
● Registers: Small, fast storage locations within the CPU that hold data and instructions
that are currently being processed. Some important registers include:
○ Program Counter (PC)- Holds the address of the next instruction to be executed.
○ Instruction Register (IR)- Holds the current instruction being executed.
○ Accumulator (ACC)- Stores intermediate results from calculations.

5. Memory

Memory plays a critical role in the functioning of a computer system, serving as the area where
instructions and data are stored for immediate access by the CPU.

Types of Memory

● Volatile Memory: Data is lost when the power is turned off.


○ RAM (Random Access Memory)- Used to store the data currently being
processed.
● Non-Volatile Memory: Retains data even after the computer is shut down.
○ ROM (Read-Only Memory)- Contains essential instructions, like the BIOS,
which helps the system start up.
○ Flash Memory- Often used in SSDs and USB drives, it retains data without
power and allows both reading and writing of data.

Memory speed is critical for system performance. More RAM generally leads to faster data
processing because it reduces the need to retrieve data from slower storage (HDD/SSD).

6. Processor

The processor is synonymous with the CPU but is sometimes used to refer to the physical chip
on the motherboard that houses the CPU. Modern processors contain multiple cores (dual-core,
quad-core, etc.), which allow them to handle multiple tasks simultaneously, greatly improving
performance.

Important Concepts

● Clock Speed– Measured in gigahertz (GHz), the clock speed of a processor determines
how many cycles of instructions the CPU can execute per second.
● Multithreading– Modern processors can execute multiple threads at once, allowing for
more efficient multitasking.
● Cache– A small amount of very fast memory within the CPU that stores frequently used
instructions and data. It reduces the time the CPU takes to fetch data from the main
memory.

7. How Do These Components Work Together ?

When a user inputs data (e.g., typing on a keyboard or clicking with a mouse), the CPU
processes the input by fetching instructions from memory, performing calculations using the
ALU, and sending the results to an output device, such as displaying it on a monitor or printing it
out. Data is temporarily stored in RAM for quick access, while long-term data is stored in
secondary storage, like an HDD or SSD.

8. Communicating with a Computer & Number Systems

Computers communicate and process information using a language they understand—binary.


This fundamental form of communication is built upon different number systems, such as
binary, decimal, hexadecimal, and octal, which are crucial for encoding and processing data.
What We will learn?

1. How Computers Communicate


2. Number Systems Overview
○ Binary (Base-2)
○ Decimal (Base-10)
○ Octal (Base-8)
○ Hexadecimal (Base-16)
3. Base Conversions
○ Binary ↔ Decimal
○ Binary ↔ Octal
○ Binary ↔ Hexadecimal
○ Decimal ↔ Octal & Hexadecimal
○ Floating Point Base Conversions (integer and fraction)

9. How Computers Communicate ?

At its core, a computer is an electronic machine that processes data. The lowest-level language of
a computer is binary, meaning that all data processed by a computer is represented using only
two symbols, ‘0’ and ‘1’. This is because modern computers are built with transistors, which can
be in one of two states– on (1) or off (0).

● Bit: A binary digit, either 0 or 1.


● Byte: A collection of 8 bits (e.g., 11010110).

Everything in a computer— from text, images, and sounds to the instructions it executes— is
encoded in binary.

10. Number Systems Overview

Computers use different number systems depending on the context and purpose. Understanding
these systems helps in interpreting how data is stored and processed.

A. Binary (Base-2)

● Digits Used: 0, 1
● Base: 2
● In the binary system, each digit represents a power of 2.

Example:

● Binary: 1011
● Decimal Equivalent:
○ 1 × 2^3 + 0 × 2^2 + 1 × 2^1 + 1 × 2^0
○ = 8 + 0 + 2 + 1 = 11 (decimal)

Binary is critical for computers because it directly maps to the two states (on and off) in digital
logic. Every instruction, number, or character must be converted into binary for the computer to
process it.

B. Decimal (Base-10)

● Digits Used: 0-9


● Base: 10
● This is the number system humans most commonly use in everyday life.

Example:

● Decimal: 1234
○ 1 × 10^3 + 2 × 10^2 + 3 × 10^1 + 4 × 10^0
○ = 1000 + 200 + 30 + 4 = 1234

Decimal is not efficient for computer processing because a computer’s circuits work best with
two states (binary).

C. Octal (Base-8)

● Digits Used: 0-7


● Base: 8
● In octal, each digit represents a power of 8. Octal is sometimes used in computing as a
shorthand for binary because each octal digit maps neatly to three binary digits.

Example:

● Octal: 345
● Decimal Equivalent:
○ 3 × 8^2 + 4 × 8^1 + 5 × 8^0
○ = 3 × 64 + 4 × 8 + 5 = 192 + 32 + 5 = 229 (decimal)

D. Hexadecimal (Base-16)

● Digits Used: 0-9, A-F (where A = 10, B = 11, C = 12, D = 13, E = 14, F =
15)
● Base: 16
● Hexadecimal is often used in computing because it provides a more compact
representation of binary. Each hexadecimal digit corresponds to four binary digits.

Example:

● Hexadecimal: 1F3
● Decimal Equivalent:
○ 1 × 16^2 + F × 16^1 + 3 × 16^0
○ = 1 × 256 + 15 × 16 + 3
○ = 256 + 240 + 3 = 499 (decimal)

E. Quick Mapping of Binary to Octal & Hexadecimal

● Binary to Octal: Every 3 binary digits map to 1 octal digit.


○ Example: 101110 (binary) = 56 (octal)
● Binary to Hexadecimal: Every 4 binary digits map to 1 hexadecimal digit.
○ Example: 11011010 (binary) = DA (hexadecimal)

11. Base Conversions

Now, we need to explore how to convert numbers between different bases. These conversions are
essential in computer programming, especially when dealing with low-level data representation
and debugging.

A. Binary to Decimal

To convert a binary number to decimal, we sum the powers of 2 for each 1 in the binary number.

Example: Convert 101101(binary) to decimal.

● Step 1– Start from the right and assign powers of 2 to each binary digit.
○ 101101 = 1 × 2^5 + 0 × 2^4 + 1 × 2^3 + 1 × 2^2 + 0 ×
2^1 + 1 × 2^0
● Step 2– Calculate the powers of 2.
○ 32 + 0 + 8 + 4 + 0 + 1 = 45 (decimal)

B. Decimal to Binary

To convert a decimal number to binary, repeatedly divide the number by 2 and record the
remainder. Write the remainders in reverse order to get the binary equivalent.

Example: Convert 45(decimal) to binary.


● Step 1– Divide by 2 and record the remainders:
○ 45 ÷ 2 = 22 remainder 1
○ 22 ÷ 2 = 11 remainder 0
○ 11 ÷ 2 = 5 remainder 1
○ 5 ÷ 2 = 2 remainder 1
○ 2 ÷ 2 = 1 remainder 0
○ 1 ÷ 2 = 0 remainder 1
● Step 2– Read the remainders in reverse order: 101101(binary).

C. Binary to Octal

Binary to octal is straightforward. Group the binary digits in sets of 3, starting from the right. If
necessary, pad with extra 0s on the left.

Example: Convert 110110(binary) to octal.

● Step 1– Group into sets of 3 i.e. 110 110.


● Step 2– Convert each group,
○ 110 (binary) = 6 (octal)
○ 110 (binary) = 6 (octal)
● Result– 110110 (binary) = 66 (octal).

D. Binary to Hexadecimal

To convert binary to hexadecimal, group the binary digits in sets of 4, starting from the right.

Example: Convert 10111011(binary) to hexadecimal.

● Step 1– Group into sets of 4 i.e. 1011 1011.


● Step 2– Convert each group,
○ 1011 (binary) = B (hex)
○ 1011 (binary) = B (hex)
● Result– 10111011 (binary) = BB (hex).

E. Decimal to Hexadecimal

To convert a decimal number to hexadecimal, divide by 16 and record the remainders.

Example: Convert 1234(decimal) to hexadecimal.

● Step 1– Divide by 16 and record the remainders i.e.


○ 1234 ÷ 16 = 77 remainder 2
○ 77 ÷ 16 = 4 remainder 13 (D in hex)
○ 4 ÷ 16 = 0 remainder 4
● Step 2– Write the remainders in reverse order i.e. 4D2(hex).

F. Floating Point Base Conversions

Converting floating-point numbers (numbers with a fractional part) involves separate


conversions for the integer and fractional parts.

Example: Convert 13.625(decimal) to binary.

● Step 1– Convert the integer part (13)


○ 13(decimal) = 1101(binary)
● Step 2– Convert the fractional part (0.625)
○ Multiply by 2: 0.625 × 2 = 1.25 (take the integer part 1)
○ Multiply the remainder 0.25 by 2 0.25 × 2 = 0.5 (take the integer part 0)
○ Multiply the remainder 0.5 by 2 0.5 × 2 = 1.0 (take the integer part 1)
● Result: 0.625(decimal) = .101(binary).

Thus, 13.625(decimal) = 1101.101(binary).

Note— Understanding these number systems and how to convert between them is critical in C
programming, especially when dealing with low-level operations like bit manipulation, memory
addressing, and hardware interfacing. Binary is the language of computers, and hexadecimal and
octal provide more human-readable shortcuts to represent binary data.

Now we dive into some base conversion practice to solidify your understanding of different
number systems. Try to solve the problems below for your upcoming assessment.

12. Base Conversion Practice Problems

12.1 Convert Decimal to Binary

Convert the following decimal numbers to binary.

● a. 45
● b. 156
● c. 5.75 (floating point)

12.2 Convert Binary to Decimal


Convert the following binary numbers to decimal.

● a. 101101
● b. 11011010
● c. 1001.101 (floating point)

12.3 Convert Decimal to Octal

Convert the following decimal numbers to octal.

● a. 78
● b. 255
● c. 33

12.4 Convert Binary to Octal

Convert the following binary numbers to octal.

● a. 110010
● b. 10101111
● c. 11110101

12.5 Convert Decimal to Hexadecimal

Convert the following decimal numbers to hexadecimal.

● a. 123
● b. 1024
● c. 2500

12.6 Convert Hexadecimal to Decimal

Convert the following hexadecimal numbers to decimal.

● a. 1A3
● b. F1
● c. 3B4

12.7 Convert Binary to Hexadecimal

Convert the following binary numbers to hexadecimal.


● a. 1101011011
● b. 1111100001
● c. 101011011111

12.8 Convert Octal to Decimal

Convert the following octal numbers to decimal.

● a. 127
● b. 64
● c. 77

Let us dive deep into float conversions between various bases. Converting floating-point
numbers involves handling both the integer part and the fractional part separately.

13. Steps for Converting Floating-Point Numbers


Float conversions are a crucial part of understanding how fractional numbers are represented in
computers, particularly when dealing with low-level data representation. The key lies in breaking
down the integer and fractional parts and converting them step by step using multiplication.

1. Integer Part Conversion


○ Convert the integer part as you would normally for any base.
2. Fractional Part Conversion
○ Multiply the fractional part by the base you're converting to.
○ Record the integer portion of the result (either 0 or 1 in binary, for example).
○ Keep multiplying the fractional remainder until it becomes zero or reaches the
desired precision.

13.1 Decimal to Binary (Floating Point)

Convert the following decimal floating-point numbers to binary.

● a. 12.625
● b. 7.375
● c. 45.6875

13.2 Binary to Decimal (Floating Point)

Convert the following binary floating-point numbers to decimal.

● a. 101.101
● b. 111.011
● c. 1101.1101

13.3 Decimal to Octal (Floating Point)

Convert the following decimal floating-point numbers to octal.

● a. 23.75
● b. 56.3125
● c. 19.875

13.4 Decimal to Hexadecimal (Floating Point)

Convert the following decimal floating-point numbers to hexadecimal.

● a. 22.375
● b. 0.8125
● c. 100.625

14. Worked Examples for Float Conversions

14.1 Convert 12.625 (Decimal) to Binary

● Integer Part–
○ Convert 12 to binary, 12 ÷ 2 = 6 remainder 0
○ 6 ÷ 2 = 3 remainder 0
○ 3 ÷ 2 = 1 remainder 1
○ 1 ÷ 2 = 0 remainder 1
○ So, 12 (decimal) = 1100 (binary).
● Fractional Part–
○ Multiply 0.625 by 2, 0.625 × 2 = 1.25 (record 1).
○ Multiply the remainder 0.25 by 2, 0.25 × 2 = 0.5 (record 0).
○ Multiply the remainder 0.5 by 2, 0.5 × 2 = 1.0 (record 1).
● So, 0.625 (decimal) = .101 (binary).
● Final Binary Result– 12.625 (decimal) = 1100.101 (binary).
14.2 Convert 7.375 (Decimal) to Binary

● Integer Part–
○ Convert 7 to binary: 7 ÷ 2 = 3 remainder 1
○ 3 ÷ 2 = 1 remainder 1
○ 1 ÷ 2 = 0 remainder 1
○ So, 7 (decimal) = 111 (binary).
● Fractional Part–
○ Multiply 0.375 by 2, 0.375 × 2 = 0.75 (record 0).
○ Multiply 0.75 by 2, 0.75 × 2 = 1.5 (record 1).
○ Multiply 0.5 by 2, 0.5 × 2 = 1.0 (record 1).
● So, 0.375 (decimal) = .011 (binary).
● Final Binary Result– 7.375 (decimal) = 111.011 (binary).

14.3 Convert 0.8125 (Decimal) to Hexadecimal

● Integer Part– 0 in decimal is still 0 in hexadecimal.


● Fractional Part–
○ Multiply 0.8125 by 16: 0.8125 × 16 = 13.0 (integer part = 13 = D in
hex).
● Final Hexadecimal Result– 0.8125 (decimal) = 0.D (hexadecimal).

14.4 Convert 0.375 (Decimal) to Binary

● Multiply 0.375 by 2, 0.375 × 2 = 0.75 (record 0).


● Multiply 0.75 by 2, 0.75 × 2 = 1.5 (record 1).
● Multiply 0.5 by 2, 0.5 × 2 = 1.0 (record 1).
● Final Binary Result– 0.375 (decimal) = 0.011 (binary).

15. Binary Math in C Programming

In C, binary math involves operations directly on the bit-level (bits being 0 or 1). This is
extremely powerful for low-level programming, such as handling hardware, optimizing
performance, or manipulating data efficiently.
C provides several bitwise operators that allow us to perform binary operations on integers.

15.1 Bitwise Operators in C

Here are the common binary (bitwise) operators you can use in C—

Operator Name Description

& AND Compares each bit and returns 1 if both bits are 1

| | OR

^ XOR (Exclusive OR) Compares each bit and returns 1 if the bits are
different

~ NOT (Complement) Inverts all the bits (turns 1 into 0 and vice versa)

<< Left Shift Shifts bits to the left, filling with zeros

>> Right Shift Shifts bits to the right, filling with zeros (or sign bit)

15.2 How Binary Math Works in C

Let us break down how binary math can be implemented using the bitwise operators.

1. AND Operator (&)

The & operator compares two bits and results in 1 if both bits are 1, otherwise it results in 0.

Example:
#include <stdio.h>

int main() {

int a = 5; // 5 in binary: 0101

int b = 3; // 3 in binary: 0011

int result = a & b; // result: 0001 (1 in decimal)

printf("AND Operation: %d\n", result); // Output: 1

return 0;

2. OR Operator (|)

The | operator compares two bits and results in 1 if at least one of the bits is 1.

Example:

#include <stdio.h>

int main() {

int a = 5; // 5 in binary: 0101

int b = 3; // 3 in binary: 0011

int result = a | b; // result: 0111 (7 in decimal)

printf("OR Operation: %d\n", result); // Output: 7

return 0;

}
3. XOR Operator (^)

The ^ operator results in 1 if the two bits are different, and 0 if they are the same.

Example:

#include <stdio.h>

int main() {

int a = 5; // 5 in binary: 0101

int b = 3; // 3 in binary: 0011

int result = a ^ b; // result: 0110 (6 in decimal)

printf("XOR Operation: %d\n", result); // Output: 6

return 0;

4. NOT Operator (~)

The ~ operator flips all the bits in a number, turning 1s to 0s and 0s to 1s. This operation is also
known as bitwise negation or complement.

Example:

#include <stdio.h>

int main() {

int a = 5; // 5 in binary: 0101

int result = ~a; // result: 1010 (in 2's complement form,


this is -6)

printf("NOT Operation: %d\n", result); // Output: -6

return 0;
}

5. Left Shift Operator (<<)

The << operator shifts the bits of the number to the left by the specified number of positions. The
vacant right positions are filled with 0s.

Example:

#include <stdio.h>

int main() {

int a = 5; // 5 in binary: 0101

int result = a << 1; // result: 1010 (10 in decimal)

printf("Left Shift: %d\n", result); // Output: 10

return 0;

6. Right Shift Operator (>>)

The >> operator shifts the bits of the number to the right by the specified number of positions.
The left positions are filled with zeros for unsigned integers and with the sign bit for signed
integers.

Example:

#include <stdio.h>

int main() {

int a = 5; // 5 in binary: 0101

int result = a >> 1; // result: 0010 (2 in decimal)


printf("Right Shift: %d\n", result); // Output: 2

return 0;

Practical Uses of Binary Math in C

1. Masking– Extract specific bits from a number.


○ For example, mask = 0x0F; result = a & mask; (This will extract the
lower 4 bits of a).

Example of Masking in C

Masking is used to extract specific bits from a number. Here's a simple example:

#include <stdio.h>

int main() {

int num = 77; // 77 in binary: 01001101

int mask = 0x0F; // Mask: 00001111 (Extract lower 4 bits)

int result = num & mask; // result: 00001101 (13 in decimal)

printf("Masked result: %d\n", result); // Output: 13

return 0;

In this example, the mask 0x0F extracts the lower 4 bits of the number 77.

2. Bit Manipulation– Turn specific bits on or off using masking.


○ Example: a |= (1 << 3); (This will turn the 4th bit of a to 1).
3. Shifting Operations– Multiply/divide numbers by powers of 2.
○ Example: a << 1 is equivalent to multiplying a by 2.
Swapping Two Numbers Without Temporary Variable (Using XOR):

int a = 5, b = 3;

a = a ^ b;

b = a ^ b;

a = a ^ b;

Hands-On Practice

Try these exercises to practice binary math in C.

1. AND, OR, XOR Practice

Write a C program that takes two integers as input and displays the result of performing AND,
OR, and XOR operations on them.

2. Bitwise Shifting Practice

Write a C program that shifts an integer left by 3 bits and right by 2 bits and prints the results.

3. Binary to Decimal Conversion Practice

Write a C program that converts a binary number (entered as a string) to its decimal equivalent
using bitwise operations.

4. Toggle a Bit

Write a C program that toggles the n-th bit of a number.

You might also like