[go: up one dir, main page]

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

Module 1 - Part1 - Removed

Uploaded by

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

Module 1 - Part1 - Removed

Uploaded by

laynadchris
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/ 136

COMPONENTS OF COMPUTER HARDWARE

Memory Unit

CPU

Input Unit Registers Output Unit

CU ALU

Asst. Prof. Sherine Sebastian, DCS, RSET 21


PROCESSOR
• The central processing unit (CPU) or Processor is
considered as the brain of the computer.
• It is also called as Microprocessor.
• It performs calculations and processing on the input data, to
generate the output
• CPU controls, co-ordinates and supervises the operations of
the computer
• The speed and efficiency of the computer mainly depends on
the CPU
• The CPU consists of Arithmetical &
Logical Unit (ALU), Control Unit (CU)
and Registers
Asst. Prof. Sherine Sebastian, DCS, RSET 22
PROCESSOR
Arithmetic and Logic Unit (ALU)
• Performs all the arithmetic and logical operations on the input

data

• The arithmetical calculations involve the use of basic arithmetic

operations like addition and subtractions.

• The logical calculations involves checking numbers and letters

for equality, less than and greater than conditions etc

• These calculations are performed on data that is stored in

internal storage areas of CPU, called registers.

• The actual processing of data occurs in the ALU.

Asst. Prof. Sherine Sebastian, DCS, RSET 24


PROCESSOR
Control Unit (CU)
• The control unit regulates and integrates the operations of
the computer

• The control unit acts as supervisor on the working of ALU.

• The sequence of different programs to be executed in the CPU


is decided by the control unit

• The control unit takes instructions stored in memory and


issues signals to ALU depending on these instructions.

• It also coordinates the functioning of various input output


devices attached to computer.

Asst. Prof. Sherine Sebastian, DCS, RSET 25


Registers

• Registers are internal storage locations inside the CPU that are used
to store instructions or data.
• The registers are used by ALU and CU for storing intermediate
results and control information.
• Number and size of registers varies with different models of CPU
• As these locations are internal to CPU, registers can be rapidly
accessed by CPU.
There are many types of registers.
– The Program Counter is used to keep the address of the next
instruction to be fetched.
– The Instruction Register is used to store the address of the
current instruction that is being processed.
– The Address Registers are used by instructions for indirectly
Asst. Prof. Sherine Sebastian, DCS, RSET 26
MEMORY

• The memory is the storage area where all the inputs are
stored before processing and the outputs are
stored after processing of inputs.

• Stores the data and instructions either temporarily or


permanently.

• The functions of memory are as follows :

(i) Stores the data and instructions to be processed.


(ii) Stores intermediate results of processing.
(iii)Stores the final results of processing before these are
released to an output device.
Asst. Prof. Sherine Sebastian, DCS, RSET 27
INPUT DEVICES
• Input devices captures information and translates it
into a form that can be processed and used by other
parts of your computer

• Functions
– It accepts (or reads) instructions and data from
outside world.
– It converts these instructions and data in
computer acceptable form
– It supplies the converted instructions and data
to computer system for further processing.

Asst. Prof. Sherine Sebastian, DCS, RSET 28


INPUT DEVICES

Types of Input Devices


● Keyboards
● Pointing devices
● Game controllers
● Scanners
● Styluses
● Microphones
● Digital cameras
● Web cams

Asst. Prof. Sherine Sebastian, DCS, RSET 29


OUTPUT DEVICES

Output devices take information within your computer


and present it to you in a form that you can understand

Hard copy Devices


● Printer
● Plotter

Soft copy Devices

● Monitors
● Speakers
Asst. Prof. Sherine Sebastian, DCS, RSET 30
Data Representation in Memory

• The computer memory stores different kinds of


data like input data, output data, intermediate
results, etc., and the instructions.
• Binary digit or bit is the basic unit of
memory.
• A bit is a single binary digit, i.e., 0 or 1.
• A bit is the smallest unit of representation
of data in a computer.
• However, the data is handled by the computer
as a combination of bits.

Asst. Prof. Sherine Sebastian, DCS, RSET 32


Data Representation in Memory(Cont.)

• A group of 8 bits form a byte.


• One byte is the smallest unit of data that is
handled by the computer.
• One byte can store 28, i.e., 256 different
combinations of bits, and thus can be used to
represent 256 different symbols.
• In a byte, the different combinations of bits fall
in the range 00000000 to 11111111.
• A group of bytes can be further combined to
form a word.
• A word can be a group of 2, 4 or 8 bytes.

Asst. Prof. Sherine Sebastian, DCS, RSET 33


Data Representation in Memory(Cont.)
Data measurement Size

Bit Single Binary Digit (1 or 0)

Nibble 4 bits
1 Byte (B) 8 bits

Kilobyte (KB) (2 10) 1,024 Bytes

Megabyte (MB) (2 20) 1,024 Kilobytes


Gigabyte (GB) (2 30) 1,024 Megabytes
Terabyte (TB) (2 40) 1,024 Gigabytes
Petabyte (PB) (2 50) 1,024 Terabytes
Exabyte (EB) (2 60) 1,024 Petabytes
Asst. Prof. Sherine Sebastian, DCS, RSET 34
Logical Representation of Memory
• Memory is logically organized as a linear array of locations.
• For a processor, the range of the memory addresses is 0 to the
maximum size of memory. Figure 3.1 shows the organization
of a 16 MB block of memory for a processor with a 32-bit
word length.

Asst. Prof. Sherine Sebastian, DCS, RSET 35


Representing Integers in Memory
▪ Integer numbers are sequences of bits
▪ Can be signed (in most cases) or unsigned
▪ The sign == the Most Significant Bit
(MSB)
▪ Leading 0 -> positive number
▪ Leading 1-> negative number
▪ Example (8-bit signed integers)
0XXXXXXXb > 0 // 00010010b = 18
00000000b = 0
// 10010010b =
1XXXXXXXb < 0 -110

Asst. Prof. Sherine Sebastian, DCS, RSET


Representation of Signed Integers

▪ Positive 8-bit numbers have the format 0XXXXXXX


▪ The value is the decimal
value of their last 7 bits
(XXXXXXX)
▪ Negative 8-bit numbers have the format
▪ 1YYYYYYY 7
The value is -128 (-27) + the
decimal value of YYYYYYY -2
10010010b = -27 + 0010010b
=
= -128 + 18 =
= -110

Asst. Prof. Sherine Sebastian, DCS, RSET


Largest and Smallest Signed Integers

▪ The largest signed 8-bit integer 7


is:127 = (27 – 1) = 01111111
2 -1
b

▪ The smallest negative 8-bit integer 7


is:-128 = -(27) = 10000000
b
-2
▪ The largest signed 32-bit integer 31
is:2147483647 = (231 – 1) = 0111…1111b 2 -1
▪ The smallest negative 32-bit integer 31
is:-2147483648 = -(231) = 1000…0000b -2
Asst. Prof. Sherine Sebastian, DCS, RSET
Representing Real Numbers

▪ Computers use the floating-point number format,


defined by the IEEE 754 technical standard
▪ The IEEE-754 standard defines:
▪ Arithmetic and exchange formats – representations of the
binary and decimal floating-point data
▪ Rounding rules for floating-point numbers
▪ Operations – arithmetic and other operations
▪ Special numbers – such as infinity and NaN

Asst. Prof. Sherine Sebastian, DCS, RSET


Storing Floating-Point Numbers

▪ Floating-point numbers are stored as sequence of


sign bit, exponent and mantissa
bits: Play with the IEEE-754 converter online:
https://h-schmidt.net/FloatConverter/IEEE754.htm
32 Bits l

1 10000011 01010010100000000000000 ≈ -21.15625


Sign Mantissa
▪ Note: errors in calculations and precision may occur
Exponent
▪ Some numbers (e.g. 0.3) cannot be represented in the
above format without rounding (as a sum of negative
powers of 2)

Asst. Prof. Sherine Sebastian, DCS, RSET


Representing Text

▪ Computers represent text characters as


unsigned integer numbers (i.e. as sequence of
bits)
▪ Letters, digits, punctuation chars, etc.
▪ The ASCII standard represent chars as 8-bit
integers
Binary Dec Hex Char
▪ Defines
0b01000001 65code
the ASCII 0x41 A chars, e.g.
for 127
0b01000010 66 0x42 B
0b00101011 43 0x2B +

Asst. Prof. Sherine Sebastian, DCS, RSET


What is ASCII code

• ASCII (American Standard Code for


Information Interchange) is a 7-bit characters
code, with values from 0 to 127.
• The ASCII code includes control characters and
printable characters: digits, uppercase letters
and lowercase letters.

Asst. Prof. Sherine Sebastian, DCS, RSET 42


ASCII Table

Asst. Prof. Sherine Sebastian, DCS, RSET 43


Example
Character ASCII value Binary

I 73 01001001

N 78 01001110

D 68 01000100

I 73 01001001

A 65 01000001
• In memory, "INDIA" would be represented by
the following sequence of binary numbers:
01001001 01001110 01000100 01001001
01000001
Asst. Prof. Sherine Sebastian, DCS, RSET 44
Categories of Memory
● Internal Memory -CPU registers, cache memory & primary
memory
– Used by CPU to perform computing tasks
– Limited storage capacity, temporary storage, fast access,
high cost
– Registers - Fastest. Located inside CPU.
– Cache memory - placed between CPU & main memory
– Primary memory - slower than cache memory.

Asst. Prof. Sherine Sebastian, DCS, RSET 45


Categories of Memory(Cont.)

● External memory (also called secondary memory)


– Very high storage capacity
– Permanent storage unless erased by user
– Relatively slower access
– Cheapest among all memory
– Hard disk, Magnetic disk etc..

Asst. Prof. Sherine Sebastian, DCS, RSET 46


Memory Hierarchy
Two key factors – capacity and access time
Capacity - amount of information (in bits) it can store
Access time - time interval between read/write request & availability of
data

High High Low


S
t
Regist
A o er
c r
c a Cache Internal
Memories
e g Memory
C s e Primary
o s
s C Memory or
t S a Main Memory
p p
a
Magnetic Disk or
e
e c Optical Disk Secondary
i Memory
d
t Magnetic Tape
y
Low Low High

Asst. Prof. Sherine Sebastian, DCS, RSET 47


Registers

• Very high speed storage areas located


inside CPU
• Manipulated directly by Control Unit
(CU) during instruction execution
• CPU’s working memory
• Gets data & instructions from cache or RAM
• Moves data & instruction to registers for processing
• Number of registers in CPU and size of each
register affect the power and speed of CPU
• More the number of registers and bigger its size;
better performance

Asst. Prof. Sherine Sebastian, DCS, RSET 48


Cache Memory

• Placed in between CPU and RAM


• Fast memory, faster than RAM
• Storage buffer that stores the data that is used
more often, temporarily and makes them
available to CPU at a faster time.
• While processing, CPU first looks in
cache for instruction or data

Asst. Prof. Sherine Sebastian, DCS, RSET 49


Primary Memory

• Main memory of computer


• Chip mounted on motherboard of computer.
• Two types –
– Random Access Memory (RAM)
– Read Only Memory (ROM)

Asst. Prof. Sherine Sebastian, DCS, RSET 50


RAM

• Stores data & instructions during computer


operation
– Data & instructions are brought to RAM from secondary storage
– CPU interacts with RAM to get data & instructions for processing
• Volatile memory. i.e it loses its content when
computer is powered off.
• Can be read from and written to with same
speed; also known as read and write memory
• Size is limited due to high cost. Size measured
in MB or GB

Asst. Prof. Sherine Sebastian, DCS, RSET 51


• Based on technology to construct RAM has two type
– DRAM (Dynamic RAM)
– SRAM (Static RAM)
• DRAM
– Small and cheap
– Uses transistors and capacitors to form a memory cell

• SRAM
– Uses multiple transistors. No capacitor.
– Faster, More expensive.
ROM

• Non-volatile memory ;does not lose


contents when power is off.
• Read capability, no write capability
• Comes programmed by manufacturer;
Stores standard processing programs that
permanently reside in computer
• Stores Basic Input Output System (BIOS)

Asst. Prof. Sherine Sebastian, DCS, RSET 53


Computer Components

• The computer consists of two main

components:

– Hardware components

– Software components

Sherine Sebastian, Asst. Prof., DCS, RSET


Computer Hardware

• It is a general term used to describe the various


physical components that are essential part of
the every computer system.

• The computer hardware components are the actual


physical parts of the computer system that are
visible to us.

• The computer hardware includes various


mechanical, electrical and electronics
components used to build the computer system.
Sherine Sebastian, Asst. Prof., DCS, RSET
Computer Hardware

Sherine Sebastian, Asst. Prof., DCS, RSET


Software
Software refers to the set of instructions and data
that tell a computer how to perform specific tasks.
It is categorized into two main types:
System software and Application software.

Sherine Sebastian, Asst. Prof., DCS, RSET


System Software

They are programs directly related to the


computer hardware and perform tasks associated
with controlling and utilizing computer hardware.

Eg: Operating System, Utility softwares, Device


Drivers

Sherine Sebastian, Asst. Prof., DCS, RSET


System Software
• System Software is designed to operate and control the computer
Hardware .
• It provides a platform for running the application
software.
• Provide a platform to run computer’s hardware and computer
application to utilize system resources and solve their
computation problem.
• Written in a low level language, so that it can easily interact with
hardware with basic level.
• Also controls working of peripheral devices.
• It act as a scheduler for the execution of the processes and
arrange the sequence according to their priority and I/O devices
Sherine Sebastian, Asst. Prof., DCS, RSET
Categories of System Software

Sherine Sebastian, Asst. Prof., DCS, RSET


Application Software
• Deals with user inputs and helps the user to
complete the task.
• Also called end-user programs or only an app.
• It resides above system software.
• The end user uses application software for a
specific purpose.
• It is either installed or accessed online.
• It can be a single program or a group of small
programs that refers to as an application suite.

Sherine Sebastian, Asst. Prof., DCS, RSET


Application Software

• An application is a job or task a user wants


to accomplish through a computer.
• Application software are programs that help
a user perform a specific job.

• Eg: Microsoft office, VLC Media Player,


Google chrome, Adobe photoshop

Sherine Sebastian, Asst. Prof., DCS, RSET


System S/w Vs Application S/w

Sherine Sebastian, Asst. Prof., DCS, RSET


Operating System

• An operating system is software that manages the


computer hardware.
• It acts as an intermediary between the user of a
computer and the computer hardware.
– To shield programmers from the complexity of the
hardware.
– Manages all the devices/resources and provide user
programs with a simpler interface to different types of
hardware.
– Increase Portability by minimizing machine specific code
• The purpose of OS is to provide an environment in
which a user can execute programs in a
convenient and efficient manner.
Programming Language
• A programming language is a computer
language that is used by programmers
(developers) to communicate with computers.
• It is a set of instructions written in any specific
language ( C, C++, Java, Python, etc.,) to
perform a specific task.
• Programming languages are used in computer
programming to implement algorithms.

Asst. Prof. Sherine Sebastian, DCS, RSET 74


Programming Language(Cont.)
• A programming language is mainly used to
develop desktop applications, websites, and
mobile applications.
• Each programming language contains a unique
set of keywords and syntax, which are used
to create a set of instructions.

Asst. Prof. Sherine Sebastian, DCS, RSET 75


Types of Programming Language
Types of Programming Languages
• Low-level language
• High-level language
Low-level language is machine-dependent (0s and
1s) programming language.
The processor runs low- level programs directly
without the need of a compiler or interpreter, so
the programs written in low-level language can be
run very fast.
Low-level language is further divided into two
parts
Machine language
Assembly language
Asst. Prof. Sherine Sebastian, DCS, RSET 76
Machine Language
• It is also called as machine code or object code.
• Machine language is easier for computer to read
because it is normally displayed in binary or
hexadecimal form (base 16)
• It does not require a translator to convert the
programs because computers directly
understand the machine language programs.
• The advantage of machine language is that it
helps the programmer to execute the programs
faster than the high-level programming
language.
• Example:0011 1100
Asst. Prof. Sherine Sebastian, DCS, RSET 77
Assembly Language
• Develop to reduce the difficulties in writing
machine language programs.
• Also known as symbolic language.
• It represents the set of instructions in a symbolic
and human-understandable form.
• Assembly language uses mnemonic instructions
to represent machine code instructions.
• These are short, easy-to-remember words
representing specific instructions that the
computer’s processor can understand.
• For example, the mnemonic ‘MOV’ stands for
‘move’ and is used to move data from one
location to another.
Asst. Prof. Sherine Sebastian, DCS, RSET 78
Direct access to hardware

• Assembly language provides direct access to


hardware resources such as the CPU, memory,
and I/O ports.
• This allows programmers to write code that can
control these resources directly.
• For instance, assembly language can be used to
write a code (i.e., a device driver) that interacts
directly with a piece of hardware such as a
printer or network card.

Asst. Prof. Sherine Sebastian, DCS, RSET 79


Assembly Language
• It uses an assembler to convert the assembly
language to machine language.
• The advantage of assembly language is that it
requires less memory and less execution time to
execute a program.
• Eg: ADD A, B
SUB C, 5

Asst. Prof. Sherine Sebastian, DCS, RSET 80


Asst. Prof. Sherine Sebastian, DCS, RSET 81
High Level Programming Language
▪ High-level language is a programming
language that allows a programmer to write the
programs which are independent of a
particular type of computer.

▪ The high-level languages are considered as


high-level because they are closer to human
languages than machine-level languages.

▪ A compiler is required to translate a high-level


language into a low-level language.
Asst. Prof. Sherine Sebastian, DCS, RSET 83
High Level Programming Language- Advantage

• The high-level language is easy to read,


write, and maintain as it is written in
English like words.
• The high-level languages are designed to
overcome the limitation of low-level
language, i.e., portability.
• The high-level language is portable; i.e.,
these languages are
machine-independent.

Asst. Prof. Sherine Sebastian, DCS, RSET 84


Programming Language

Asst. Prof. Sherine Sebastian, DCS, RSET 85


Compilers
It is a software program that transforms
high-level source code that is written by a
developer in a high level programming
language into a low level object code which
can be understood by the processor.

High Level source code —>Low level


object code
The process of converting high-level
programming into machine language is
known as compilation.
Asst. Prof. Sherine Sebastian, DCS, RSET 86
Interpreters
• An Interpreter directly executes
instructions written in a programming or
scripting language without previously
converting them to an object code or
machine code.
• Examples of interpreted languages are
Perl, Python and Matlab.
• The interpreter reads each statement of
code and then converts or executes it
directly.
• Interpreted programs run slower than the
compiled programs.
Asst. Prof. Sherine Sebastian, DCS, RSET 87
Compiler Vs Interpreters

Asst. Prof. Sherine Sebastian, DCS, RSET 88


ALGORITHM - Definition

• An algorithm is a procedure or formula for solving a problem, based

on conducting a sequence of specified actions.

• It is a step by step procedure to solve a particular problem.

• It consists of English like statements.

• Each statement must be precise and well defined to perform a specific

operation.
Characteristics of Algorithms

• Every algorithm should have the following 5 characteristic features:

1. Input
2. Output
3. Definiteness
4. Effectiveness
5. Finiteness
Characteristics of Algorithms (Contd…)

1) Input:- an algorithm accepts zero or more inputs.

2) Output:- it produces at least one output.

3) Definiteness: - each step in algorithm is unambiguous. This means


that the action specified by the step cannot be interpreted (explain
the meaning of) in multiple ways & can be performed without any
confusion.

4) Effectiveness:- it consists of basic instructions that are realizable.


This means that the instructions can be performed by using the
given inputs in a finite amount of time.

5) Finiteness: - an algorithm terminates after a finite numbers of


steps.
Algorithm Examples
Algorithm to print “Hello World.” on Screen.

Step 1 : Start

Step 2 : Print “ Hello World.”

Step 3 : Stop
Algorithm Examples
Algorithm to find out the sum of two numbers.

Step 1 : Start

Step 2 : Read the values for two numbers to be added and store it in
variables num1 and num2

Step 3 : Initialize sum =0

Step 4 : Add two numbers and store the result into another variable, sum

Step 5 : Print the value of sum

Step 6 : Stop
Algorithm Examples
Algorithm to calculate the average of two numbers.

Step 1 : Start
Step 2 : Read the values for two numbers to be added and store it in the
variables num1 and num2
Step 3: Initialize sum and avg with “0”.
Step 4 : Add two numbers and store the result into the variable, sum
Step 5 : Divide the sum by 2 and store it in the variable avg
Step 6 : Print the value of avg
Step 7 : Stop
Algorithm Examples
1. Algorithm to find the largest among three different numbers entered by
the user
Step 1 : Start
Step 2: Read the three numbers from user and assign it to a, b, c
Step 3: Check if a is greater than b. If true, goto step 4. Otherwise goto
step 5.
Step 4: Check if a is greater than c.
Step 4.1 : If true, then print ‘a’ as the greatest number. Goto step 6.
Step 4.2 : Otherwise print ‘c’ as the greatest number. Goto step 6.
Step 5: Check if b is greater than c.
Step 5.1 : If true, then print ‘b’ as the greatest number. Goto step 6
Step 5.2 : Otherwise print ‘c’ as the greatest number. Goto step 6
Step 6: Stop
Algorithm Examples
2. Algorithm to find the area and perimeter of the circle.

Step 1 : Start
Step 2: Read the radius from the user to the variable r.
Step 3: Initialize pi = 3.14.
Step 4: Calculate area = pi * radius * radius
Step 6: Calculate perimeter = 2 * pi * radius
Step 7: print area and perimeter.
Step 7: stop
Algorithm Examples
3. Algorithm for calculator functions
Step 1: Start
Step 2: Print "Choose an operator (+, -, *, /) to perform an
operation in C calculator"
Step 3: Read the input operator and store it in opt
Step 4: Print "Enter the first number:"
Step 5: Read the first number and store it in num1
Step 6: Print "Enter the second number:"
Step 7: Read the second number and store it in num2
Algorithm for calculator functions(cont.)

Step 8: Check if opt is +. If true, go to Step 9. Otherwise, go to


Step 10.
Step 9: Calculate result as num1 + num2
Step 9.1: Print "Addition of num1 and num2 is: result"
Step 9.2: Go to Step 17
Step 10: Check if opt is -. If true, go to Step 11. Otherwise, go
to Step 12.
Step 11: Calculate result as num1 - num2
Step 11.1: Print "Subtraction of num1 and num2 is:
result"
Step 11.2: Go to Step 17
Step 12: Check if opt is *. If true, go to Step 13. Otherwise, go
to Step 14.
Algorithm for calculator functions(cont.)
Step 13: Calculate result as num1 * num2
Step 13.1: Print "Multiplication of num1 and num2 is: result"
Step 13.2: Go to Step 17
Step 14: Check if opt is /. If true, go to Step 15. Otherwise, go to Step 16.
Step 15: Check if num2 is 0
Step 15.1: If true, print "Divisor cannot be zero. Please enter another value"
Step 15.1.1: Read a new value for num2
Step 15.2: Calculate result as num1 / num2
Step 15.3: Print "Division of num1 and num2 is: result"
Step 15.4: Go to Step 17
Step 16: Print "You have entered wrong inputs"
Step 16.1: Go to Step 17
Step 17: End
Algorithm Examples
4. Algorithm to find all the roots of a quadratic
equation ax2+bx+c=0.
Step 1: Start
Step 2: Print "Enter coefficients a, b, and c:"
Step 3: Read the coefficients and store them in a, b, and c
Step 4: Calculate the discriminant using the formula discriminant = b*b -
4*a*c
Step 5: Check if discriminant is greater than 0. If true, go to Step 6. Otherwise,
go to Step 7.
Step 6:a Calculate the roots (real and different)

•root1 = (-b + sqrt(discriminant)) / (2*a)


•root2 = (-b - sqrt(discriminant)) / (2*a)
•Step 6.1: Print the values of root1 and root2.
Algorithm for the roots of a quadratic equation
Step 7: Check if discriminant is equal to 0. If true, go to Step 8. Otherwise, go
to Step 9.
Step 8: Calculate the roots (real and same)
root1 = root2 = -b / (2*a)
Step 8.1: Print "root1 = root1 and root2 = root1"
Step 8.2: Go to Step 11
Step 9: If discriminant is less than 0, Calculate the real and imaginary parts
realPart = -b / (2*a)
imaginaryPart = sqrt(-discriminant) / (2*a)
Step 9.1: Print "root1 = realPart + imaginaryPart i and root2 = realPart
- imaginaryPart i"
Step 9.2: Go to Step 11
Step 10: If none of the above conditions are met, Print "Invalid input or no
real roots exist"
Step 11: End
Factorial of a number
Algorithms - Examples

Algorithm for calculating factorial of a number


Step 1: Start
Step 2: Print "Enter a non-negative integer"
Step 3: Read the value of n from the user
Step 4: Initialize fact to 1
Step 5: Set i to 1
Step 6: Check if i is less than or equal to n
Step 6.1: If true, multiply fact by i and store the result
in fact
Step 6.2: Increment i by 1
Step 6.3: Repeat Step 6
Step 7: After the loop ends, print "Factorial of n is fact"
Step 8: End
Leap Year
Algorithms - Examples
• Algorithm for checking if the given year is a leap year or
not
Step 1: Start
Step 2: Print "Input a year :"
Step 3: Read the value of chk_year from the user
Step 4: Check if chk_year is divisible by 400
Step 4.1: If true, print "chk_year is a leap year."
Step 5: If not divisible by 400, check if chk_year is divisible by 100
Step 5.1: If true, print "chk_year is not a leap year."
Step 6: If not divisible by 100, check if chk_year is divisible by 4
Step 6.1: If true, print "chk_year is a leap year."
Step 7: If not divisible by 4, print "chk_year is not a leap year."
Step 8: End
Algorithms - Examples

Algorithm for reading number from user


and checking if they are odd or even

Step 1: Start
Step 2: Read the number from user and assign it to ‘a’
Step 3: Calculate the remainder of ‘a’ when divided by 2
Step 4: Check if the remainder is 0
Step 4.1: If true, print "It is even". Go to Step 6.
Step 4.2: Otherwise, print "It is odd". Go to Step 6.
Step 6: Stop
Algorithms - Examples
Algorithm to find the Fibonacci series up to 100
Step 1: Start
Step 2: Initialize a = 0, b = 1, c
Step 3: Print a and b
Step 4: Loop while c <= 100:
Step 4.1: c = a + b
Step 4.2: If c > 100, goto step 5 to break the loop.
Step 4.3: Print c
Step 4.4: a = b
Step 4.5: b = c
Step 5: Stop
Algorithms - Examples
Algorithm for Celsius to Fahrenheit conversion
and vice versa.
Step 1: Start
Step 2: Prompt the user to choose the type of conversion:
•Option 1: Celsius to Fahrenheit
•Option 2: Fahrenheit to Celsius
Step 3: Read the user's choice and assign it to choice
Step 4: Check the value of choice
Step 4.1: If choice is 1 (Celsius to Fahrenheit):
Step 4.1.1: Prompt the user to enter the temperature in
Celsius and assign it to celsius
Step 4.1.2: Calculate fahrenheit using the formula:
fahrenheit = (celsius * 9/5) + 32
Algorithm for Celsius to Fahrenheit conversion
and vice versa.(cont.)
Step 4.1.3: Print the value of fahrenheit
Step 4.1.4: Go to Step 6
Step 4.2: If choice is 2 (Fahrenheit to Celsius):
Step 4.2.1: Prompt the user to enter the temperature in
Fahrenheit and assign it to fahrenheit
Step 4.2.2: Calculate celsius using the formula: celsius =
(fahrenheit - 32) * 5/9
Step 4.2.3: Print the value of celsius
Step 4.2.4: Go to Step 6
Step 5: If choice is neither 1 nor 2, print an error message and go back
to Step 2
Step 6: Stop
Flowchart

The flowchart is a means of visually presenting the flow of control


through an information processing systems.

It depicts the operations performed within the system and the


sequence in which they are performed.

It is a graphic representation of how a process works, in a minimum


sequence of steps.

Flowcharts are generally drawn in the early stages of formulating


computer solutions.
Flowchart Symbols

The flowchart is a means of visually presenting the flow of control


through an information processing systems.

It depicts the operations performed within the system and the


sequence in which they are performed.

It is a graphic representation of how a process works, in a minimum


sequence of steps. Flowcharts are generally drawn in the early stages
of formulating computer solutions.
Flowchart Symbols
·Parallelograms are used to represent input and output
operations.
·Rectangles are used to indicate any processing operation
such as storage and arithmetic.
·Diamond shaped boxes are used to indicate questions
asked or conditions tested based on whose answers
appropriate exits are taken by a procedure. The exits from
the diamond shaped box are labeled with the answers to the
questions.
·Rectangles with rounded ends are used to indicate the
beginning or the end points of a procedure.
·A circle is used to join different parts of a flowchart like
subroutines. This is called a connector.
Arrows indicate the direction to be followed in a flow chart.
Every line in a flow chart must have an arrow on it.
Flowchart Examples
Flowchart to add two
numbers Start

Enter A & B

Sum = A + B

Print Sum

Stop
Flowchart for Three Constructs
Advantages
Limitations
Flowchart Examples
Largest numbers Start

Read A & B

No
Yes Is A>
B

Print A Print B

Stop
Flowchart Examples - Odd or Even
Flowchart Examples – Average of 3 Numbers

Yes
Largest of three numbers
Find the Fibonacci series upto 100.
Start

Initialize a =0, b =1and c=0

Input the limit

Print : Fibonacci Series


Print a and b

Set i =2

No Yes
If i<=n?
c= a + b
a=b
b=c
i = i+1

Print c

Stop
Find all the roots of a quadratic equation ax2+bx+c=0.
Part 2

Introduction to C Programming
Introduction to C
∙C was evolved from ALGOL, BCPL (Basic Combined
Programming Language) and B by Dennis Ritchie.

∙A computer program is nothing but an ordered collection of


instructions or statements.

∙ These instructions perform some useful “operations” on data


which are represented as constants or variables.

∙ This chapter is concerned with the basic elements used to


construct simple C statements. These elements include the C
character set, constants, variables, keywords, expressions,
statements etc.
Structure of a C program

• A C program basically consists of the following parts:

• Preprocessor Directives

• Functions

• Variables

• Statements & Expressions

• Comments
Structure of C Program

MAX 100
A simple Program
#include <stdio.h>

int main()

/* my first Program in C */

printf("Hello, World! \n");

return 0;

}
Explanation
• The first line of the program #include<stdio.h> is a preprocessor

command, which tells a C compiler to include stdio.h file before going to


actual compilation.

• Preprocessor- A C Preprocessor is just a text substitution tool and it

instructs the compiler to do required pre-processing before the actual


compilation. All preprocessor commands begin with a hash symbol (#).
Some of the pre-processor directives are

• # define- substitute a macro(Macros in C are used to create constants

or function-like constructs that are replaced by their corresponding


definitions before the actual compilation of the code begins.

• # include- inserts a particular header from another file.


Explanation(cont.)

• Header Files- A header file is a file with


extension .h which contains C function declarations and
macro definitions to be shared between several source
files. There are two types of header files: the files that the
programmer writes and the files that comes with our
compiler. Can use a header file in our program by
including it with the C preprocessing directive #include.

•The syntax is #include<headerfile.h>


•eg #include<stdio.h>
Explanation(cont.)

• The next line int main() is the main function where the program execution
begins.

• The next line /*...*/ will be ignored by the compiler and it has been put to
add additional comments in the program. So such lines are called comments
in the program.

• The next line printf(...) is another function available in C which causes the
message "Hello, World!" to be displayed on the screen.

• The next line return 0; terminates the main() function and returns the value
0.
Compile and Execute C Program
• Following are the steps to save the source code in a file, and to
compile and run it.

1. Open a text editor and add the above-mentioned code.

2. Save the file as hello.c

3. Open a command prompt and go to the directory where you have saved the file.

4. Type gcc hello.c and press enter to compile your code.

5. If there are no errors in your code, the command prompt will take you to the next line
$ gcc hello.c
and would generate a.out executable file. $ ./a.out
Hello, World!

6. Now, type ./a.out to execute your program.


C Fundamentals

• Character set
• Tokens
• Identifiers in C
• Variables and Data Types
• Constants
Character Set

• As every language contains a set of characters


used to construct words, statements, etc.

• C language also has a set of characters which


include alphabets, digits, and special symbols.

• C language supports a total of 256 characters.


Character Set (cont.)
Alphabets

• C language supports all the alphabets from the English language.


Lower and upper case letters

• Together support 52 alphabets.

• Lower case letters - a to z

• Upper case letters - A to Z

Digits

• C language supports 10 digits which are used to construct numerical


values in C language. Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special Symbols

• Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > ,<


Tokens
• Every C program is a collection of instructions and every
instruction is a collection of some individual units. Every
smallest individual unit of a c program is called token.

• Every instruction in a c program is a collection of tokens.


Tokens are used to construct c programs and they are said
as the basic building blocks of a c program.
Tokens (cont.)

• In a c program tokens may contain the following:-


1. Data types
2. Identifiers
3. Variables
4. Keywords
5. Constants
6. Operators
7. Special Symbols
8. Strings
Data types

Data types in the c programming language are used to specify what kind
of value can be stored in a variable. The memory size and type of the
value of a variable are determined by the variable’s data type.
Data Types

Memory
Data type Description
requirements
char single character 1 byte
2 bytes( 4 bytes
int an integer in some
machines)
floating-point number (i.e., a number containing a
float decimal point and/or an exponent) 4 bytes
double-precision floating-point number
(i.e., more significant figures, and an exponent
double 8 bytes
which may be larger in magnitude)
Data Types (cont.)
•All variables must be declared before they can be used.
•A declaration consists of a data type, followed by one or more
variable names, ending with a semicolon. Following are some
examples.
• int a, b;
• float f;
• char c;

•Here a and b are variables of integer type

•f is of floating-point type and


• c is a character.
Identifiers
• An identifier is a string of alphanumeric characters that begins
with an alphabetic character or an underscore character that are
used to represent various programming elements such as:

• variables,
• functions,
• arrays,
• structures,
• unions and so on.
Actually, an identifier is a user-defined word. There are 63
characters, to represent identifiers. They are 52 alphabetic
characters and 10 digits and underscore.
Rules for Identifier
• The first character in an identifier must be an alphabet or an
underscore and can be followed only by any number of alphabets, or
digits or underscores.
• They must not begin with a digit.
• Uppercase and lowercase letters are distinct. That is, identifiers are
case sensitive.
• Commas or blank spaces are not allowed within an identifier.
• Keywords cannot be used as an identifier.
• Identifiers should not be of length more than 31 characters.
• Identifiers must be meaningful, short, quickly and easily typed and
Variables
• A variable is a data name that may be used to store a data value.

• Eg: int a;

• A variable may take different values at different times during


execution.

• Each variable has a specific storage location in memory where its


value is stored. The variables are called symbolic variables

because these are named.


Variable Declaration

• A declaration associates a group of variables with a


specific data type.
• Declaration of variables must be done before they are used
in the program.
Syntax:-
Data_ type variable_ name;
• Eg: int a;
float b;
char name;
int a, b, c;
Few rules when choosing names for your variables:

1. Must start with a letter or underscore ( _)


2. Can be followed by any number of letters, digits, or
underscores.
3. Both upper-case and lower-case letters are
permitted, although lower case letters are common.
4. Variable names are case sensitive.
5. Cannot be a keyword.
Memory allocation for Variables

• There are two values associated with a symbolic

variable.

• Data value: stored at some location in memory. This

is sometimes referred to as a variable’s r- value.

• Location value: This is the address in memory at

which its data value is stored. This is sometimes

referred to as variable’s l-value.

Asst. Prof. Sherine Sebastian, DCS, RSET 147


Memory allocation for Variables

1052 - 1055 1056 1057 1058

• r-value of A=10 and l-value of A=1052


• r-value of c=25 and l-value of c=1058

Whenever we use the assignment operator, the expression to the left of


an assignment operator must be an l-value. That is, it must provide an
accessible memory address where the data can be written to.
Example
Example
Keywords
•There are certain reserved words, called keywords, that have
standard, predefined meanings in C. These keywords are
listed in the following table and can be used only for their
intended purpose; they cannot be used as variable names.
auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while
Constants
Constants (literals): These are data items that never change their value
during a program run. These are fixed values. The types of constants are
a) Integer constant: These are whole numbers without any fractional part. It
must have at least one digit and must not contain any decimal point. It can
be either positive or negative.

• Examples are 426,+200,-760

b) Character constant: A character constant is one character enclosed in


single quotes. Examples are ‘A’, ’5’ ,’=’ . A character constant have
corresponding ASCII (American Standard Code for Information
Interchange) values. For example ASCII value of ‘A’ is 65 and ASCII

value of ‘a’ is 97. Eg: ‘a’ ,‘6’


Constants (cont.)

c. Floating-Point Constants – numbers with a decimal point. A


floating-point number can be written using either ordinary decimal
notation or scientific notation. Scientific notation is often useful
for representing very large numbers. In scientific notation, the
letter E (or e) denotes the base 10. See the examples below:
Number Decimal notation Scientific notation
3.146 × 100 314.6 3.146e2
3.146 × 10 31.46 3.146E1
3.146 × 10−1 0.3146 3.146E-1
3.146 × 10−3 0.003146 3.146e-3
Constants (cont.)
d. String Constants – consists of any number (possibly zero) of
consecutive characters, enclosed in double quotation marks.

• Eg: "program", "c", ""

• The string " " is called a null or empty string.

• Each string constant is by default (automatically) added with a

special character ’\0’ which marks the end of a string. Thus the size

of a string is:-

• Number of characters + null character (‘\0’)

• Eg:length of String “Hello” =6


Expressions and statements
• The expression may consist of a single entity, such as a constant or a variable or

may also consist of a combination of such entities, interconnected by one or more


operators.

Eg: a + b, x = y, 78, c=a+7


• An expression statement consists of an expression followed by a semicolon. The
execution of an expression statement causes the expression to be evaluated.
Following are some examples:

• a = 3;
• c = a + b;
• A compound statement consists of several individual statements enclosed within a
pair of braces { }.
{
a=2;
b=5;
Data input and output
C provides many in-built functions available for
performing I/O operations. These functions can
be divided into two categories:

1. Unformatted
2. Formatted
Unformatted I/O
1. Unformatted I/O functions are used only for character
data type or character array/string and cannot be
used for any other datatype. These functions are used to
read single input from the user at the console and it
allows to display the value at the console.
1. Single character input output (getchar(), putchar())
variable name=getchar( );
putchar ( variable-name)
Eg: char c;
c=getchar();
putchar(c);
2. Multi character input and output( gets(), puts())
1. gets(str); //here str is the name of a string.
2. puts(str); // to display the string str, we write:

Eg: char vehicle [40];


printf(“Enter your vehicle name”);
gets (vehicle);
puts (vehicle);

Asst. Prof. Sherine Sebastian, DCS, RSET 160


Formatted I/O Functions

• Formatted I/O functions are used to take various


inputs from the user and display multiple outputs to
the user.
• These types of I/O functions can help to display the
output to the user in different formats using the
format specifiers.
• These I/O supports all data types like int, float, char,
and many more.
• These functions are called formatted I/O functions
because we can use format specifiers in these
functions and hence, we can format these functions
according to our needs.
List of some format specifiers-
S
Format Specifier Type Description
NO.

1 %d int/signed int used for I/O signed integer value

2 %c char Used for I/O character value

Used for I/O decimal floating-point


3 %f float
value

4 %s string Used for I/O string/group of characters

5 %ld long int Used for I/O long signed integer value

6 %u unsigned int Used for I/O unsigned integer value

7 %i signed int used for the I/O integer value

8 %lf double Used for I/O fractional or floating data

9 %n prints prints nothing


Formatted Input

1. scanf ( ) : The scanf() function can be used to enter any type


of data - numerical values, single characters and strings. It can
be used to input multiple values at a single go
Syntax:
scanf(“control string”, list of addresses of variables);

where control string refers to a string containing certain required


formatting information and list of addresses of variables refers
to the addresses of variables (addresses are obtained by using &,
called the ‘‘address of" operator)

Eg: scanf (“%d”, &a);


scanf (“%d%f”,&num1,&num2);
control string/format specifiers/declaration specifier.

• The control string is actually a group of format specifiers.


• The format specifier is also called declaration specifier.
• Each such specifier has two characters - a % sign and a conversion
character which tells what type of datum is to be read.
• There should be a format specifier for each data item entered.
• Within the control string, the format specifiers are separated by white
spaces.

The following code fragment inputs an int, char and float values.
int i;
char c;
float f;
scanf("%d %c %f",&i,&c,&f);
Formatted strings are
1. %d -integers
2. %f- float
3. %c -character
4. %o- octal number
5. %s -string
6. %e -exponential notation
7. %u -unsigned integer
8. %x -hexadecimal integer
9. % i -signed decimal integer
10. %p -display a pointer
11. %% -prints a percent sign (%)
Formatted Output
2. printf ( ) : For outputting the result we use printf( ) function.
• It is a pre-defined function that is already declared in the
stdio.h(header file).
Syntax 1 : To display any variable value.
printf(“control string”, list of variables);
where control string refers to a string containing the required formatting
information and list of variables denote the variables whose values are to be
displayed.

Eg: printf (“%d”, a);

Syntax 2:
To display any string or a message
printf(“Enter the text which you want to display”);
Eg: printf (“WELCOME MY FRIEND”);
Escape sequences
• An escape sequence refers to a combination of characters beginning with a

back slash (\) followed by letters or digits. It is used to indicate that the
character immediately following it should be interpreted differently than it
normally would. Escape Sequence Represents
\a Bell (alert)
\b Backspace
\f Formfeed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\’ Single quotation mark
\" Double quotation mark
\\ Backslash
\? Question mark
\0 Null character
Examples
The output is shown below:
• printf("Hello\tWorld"); • Hello World

• Hello
• printf("\nHello\nWorld");
World

• printf("\nHello\"World"); • Hello"World
Symbolic Constants/Macro Substitution

• We can define a symbolic constant using #define. It has the


following form
• Syntax
• #define symbolic_ name value_ of_ constant
• Eg: #define NUMVAL 100
#define statement must not end with semi colon. Symbolic
names are written in CAPITALS.
When a constant is used at many places in a program, due to some
reason if the value of that constant needs to be changed, then the
change is to be made at every statement where that constant occurs
in the program. If it were a symbolic constant, you just need to
change at one place – the place where it is defined.
Comments

• As programs get bigger and more complicated, they


get more difficult to read and understand. For this
reason, it is a good idea to add notes to your programs
to explain in English what the program is doing.
• These notes are called comments.
• Comments can be single line comments or can span
over multiple lines.
• Single line comments start with // symbol.
• Multi-line comments start with /* and end with */.
• Anything written after // symbol or between /* and
*/ symbols are ignored by compiler.

You might also like