Download as pdf or txt
Download as pdf or txt
You are on page 1of 109

Programming for Problem

Solving
B. Tech – 2nd Semester
Unit I: Introduction

Introduction to Programming, Introduction to components


of a computer system (disks, memory, processor, where a
program is stored and executed, operating system,
compilers etc.), Idea of Algorithm: steps to solve logical
and numerical problems. Representation of Algorithm:
Flowchart, Pseudo code and Source code with examples.
Text Books:

 1. Byron Gottfried, Schaum's


Outline of Programming with
C, McGraw-Hill.

 2. E. Balaguruswamy,
Programming in ANSI C, Tata
McGraw-Hill
Reference Books:
 Brian W. Kernighan and
Dennis M. Ritchie, The C
Programming Language,
Prentice Hall of India
Other Book
 Let’s Us C by Yashwant Kanetkar,
INTRODUCTION TO COMPUTERS

 Any programming language is implemented on a


computer. Right from its inception, to the present day, all
computer system (irrespective of their shape & size)
perform the following 5 basic operations.

 It converts the raw input data into information, which is


useful to the users.
INTRODUCTION TO COMPUTERS

1. Input: It is the process of entering data & instructions to


the computer system.

2. Storing: The data & instructions are stored for either initial
or additional processing, as & when required.

3. Processing: It requires performing arithmetic or logical


operation on the saved data to convert it into useful
information.
INTRODUCTION TO COMPUTERS

4. Output: It is the process of producing the output data to


the end user.

5. Controlling: The above operations have to be directed


in a particular sequence to be completed.

Based on these 5 operations, we can sketch the block


diagram of a computer.
INTRODUCTION TO COMPUTERS

Block Diagram of a Computer


Input Unit
Input Unit:
 We need to first enter the data & instruction in the
computer system, before any computation begins.

 This task is accomplished by the input devices. (The data


accepted is in a human readable form. The input
device converts it into a computer readable form.

 Input device: The input device is the means through


which data and instructions enter in a computer.
Input Unit:

1. Camera - most cameras like this are


used during live conversations. The
camera transmits a picture from one
computer to another, or can be used
to record a short video.
Input Unit:
2. Keyboard - The keyboard is a way to input letters or
numbers into different applications or programs. A keyboard
also has special keys that help operate the computer.
Input Unit:
3. Mouse - The mouse is used to open
and close files, navigate web sites,
and click on a lot of commands (to
tell the computer what to do) when
using different applications.
Input Unit:
4. Microphone - A microphone is
used to record sound. The sound is
then saved as a sound file on the
computer.

5. Scanner - A scanner is used to


copy pictures or other things and
save them as files on the computer.
Input Unit:
6. Compact Disc (CD) - CDs store
information. The CD can then be put
into another computer, and the
information can be opened and
added or used on the second
computer.

Note: A CD-R or CD-RW can also be


used as an OUTPUT device.
Input Unit:
7. Joystick - A joystick is used to
move the cursor from place to place,
and to click on various items in
programs. A joystick is used mostly
for computer games.
Input Unit:
8. Bar Code Scanner - A bar code
scanner scans a little label that has a
bar code on it. The information is
then saved on the computer. Bar
code scanners are used in libraries a
lot.
Storage Unit
Storage Unit:
 The data & instruction that are entered have to be
stored in the computer. Similarly, the end results & the
intermediate results also have to be stored somewhere
before being passed to the output unit.

 The storage unit provides solution to all these issues. This


storage unit is designed to save the initial data, the
intermediate result & the final result.

 Storage unit has 2 units: Primary & Secondary storage.


Primary Storage:
 The primary storage, also called as the main memory,
holds the data when the computer is currently on.
 As soon as the system is switched off or restarted, the
information held in primary storage disappears (i.e. it is
volatile in nature).
 Moreover, the primary storage normally has a limited
storage capacity, because it is very expensive as it is
made up of semiconductor devices.
 Types of primary storage: RAM and ROM
Primary Storage:
Random Access Memory (RAM) –
 It is also called read-write memory or the main
memory or the primary memory.
 The programs and data that the CPU requires during the
execution of a program are stored in this memory.
 It is a volatile memory as the data lost when the power is
turned off.
 RAM is further classified into two types- SRAM (Static
Random Access Memory) and DRAM (Dynamic
Random Access Memory).
Primary Storage:
Read Only Memory (ROM) –
 Stores crucial information essential to operate the
system, like the program essential to boot the computer.
 It is not volatile.
 Always retains its data.
 Used in embedded systems or where the programming
needs no change. Used in calculators and peripheral
devices.
 ROM is further classified into 3 types-
PROM, EPROM, and EEPROM.
Primary Storage:
 PROM (Programmable read-only memory) – It can be
programmed by the user. Once programmed, the data
and instructions in it cannot be changed.

 EPROM (Erasable Programmable read only memory) – It


can be reprogrammed. To erase data from it, expose it
to ultraviolet light. To reprogram it, erase all the previous
data.

 EEPROM (Electrically erasable programmable read only


memory) – The data can be erased by applying an
electric field, with no need for ultraviolet light. We can
erase only portions of the chip.
Secondary Storage:
 The secondary storage, also called as the auxiliary
storage, handles the storage limitation & the volatile
nature of the primary memory.

 It can retain information even when the system is off.

 It is basically used for holding the program instructions &


data on which the computer is not working on currently,
but needs to process them later.
Magnetic Disk

 The Magnetic Disk is Flat,


circular platter with metallic
coating that is rotated
beneath read/write heads.

 It is a Random access device;


read/write head can be
moved to any location on the
platter.
Floppy Disk

 These are small removable disks that are plastic coated


with magnetic recording material.

 Floppy disks are typically 3.5″ in size (diameter) and can


hold 1.44 MB of data.

 This portable storage device is a rewritable media and


can be reused a number of times.

 Floppy disks are commonly used to move files between


different computers.
Hard Disk
 A hard disk consists of one or more rigid
metal plates coated with a metal oxide
material that allows data to be
magnetically recorded on the surface of
the platters.

 The hard disk platters spin at a high rate of


speed, typically 5400 to 7200 revolutions
per minute (RPM).
CD
 Compact Disk (CD) is portable disk having data storage
capacity between 650-700 MB. I
 t can hold large amount of information such as music,
full-motion videos, and text etc.
 It contains digital information that can be read, but
cannot be rewritten. Separate drives exist for reading
and writing CDs.
 Since it is a very reliable storage media, it is very often
used as a medium for distributing large amount of
information to large number of users. In fact today most
of the software is distributed through CDs
DVD
 Digital Versatile Disk (DVD) is similar to a CD but has
larger storage capacity and enormous clarity.
 Depending upon the disk type it can store several
Gigabytes of data (as opposed to around 650MB of a
CD).
 DVDs are primarily used to store music or movies and
can be played back on your television or the computer
too.
 They are not rewritable media. It‘s also termed DVD
(Digital Video Disk)
Memory Organization in Computer
 A memory unit is the collection of storage units or
devices together.

 The memory unit stores the binary information in the form


of bits. Generally, memory/storage is classified into 2
categories:

 Volatile Memory: This loses its data, when power is


switched off.

 Non-Volatile Memory: This is a permanent storage and


does not lose any data when power is switched off.
Memory Organization in Computer

The total memory capacity of a computer can be visualized by


hierarchy of components.
Memory Organization in Computer
 The memory hierarchy system consists of all storage
devices contained in a computer system from the slow
Auxiliary Memory to fast Main Memory and to smaller
Cache memory.

 Auxiliary memory access time is generally 1000 times


that of the main memory, hence it is at the bottom of
the hierarchy.
Memory Organization in Computer
 The main memory occupies the central position
because it is equipped to communicate directly with
the CPU and with auxiliary memory devices through
Input/output processor (I/O).
 When the program not residing in main memory is
needed by the CPU, they are brought in from auxiliary
memory.
Memory Organization in Computer
 The cache memory is used to store program data which
is currently being executed in the CPU.

 Approximate access time ratio between cache memory


and main memory is about 1 to 7~10
Memory Organization in Computer

S. No. Unit Description

Byte 1 byte= 8 bit


1

Kilo byte (KB) 1 KB = 1024 Bytes


2

Mega byte (MB) 1 MB = 1024 KB


3

Giga byte (GB) 1 GB = 1024 MB


4

Tera byte (TB) 1 TB = 1024 GB


5

Peta byte (PB) 1 PB = 1024 TB


6
CPU
Central Processing Unit
 Together the Control Unit & the Arithmetic Logic Unit are
called as the Central Processing Unit (CPU).

 The CPU is the brain of the computer. Like in humans, the


major decisions are taken by the brain itself & other
body parts function as directed by the brain.

 Similarly in a computer system, all the major calculations


& comparisons are made inside the CPU.

 The CPU is responsible for activating & controlling the


operation of other units of the computer system.
Arithmetic Logic Unit
 The actual execution of the instructions (arithmetic or
logical operations) takes place over here.

 The data & instructions stored in the primary storage are


transferred as & when required.

 Intermediate results that are generated in ALU are


temporarily transferred back to the primary storage, until
needed later.
Arithmetic Logic Unit
 Hence, data may move from the primary storage to ALU
& back again to storage, many times, before the
processing is done.
Control Unit
 This unit controls the operations of all parts of the
computer but does not carry out any actual data
processing.

 It is responsible for the transfer of data and instructions


among other units of the computer.

 It manages and coordinates all the units of the system.

 It also communicates with Input/Output devices for


transfer of data or results from the storage units.
Output unit
Output Unit
 The job of an output unit is just the opposite of an input
unit. It accepts the results produced by the computer in
coded form.

 It converts these coded results to human readable form.


Finally, it displays the converted results to the outside
world with the help of output devices ( Eg :monitors,
printers, projectors etc..).

 Output device: Device that lets you see what the


computer has accomplished
Output Unit
 1. Monitor - A monitor is the screen on which words,
numbers, and graphics can be seem. The monitor is the
most common output device.
Output Unit
 2. Printer - A printer prints whatever is on the monitor
onto paper. Printers can print words, numbers, or
pictures.
Output Unit
 3. Speaker - A speaker gives you sound output from your
computer. Some speakers are built into the computer
and some are separate.
Output Unit
 4. Headphones - Headphones give sound output from
the computer. They are similar to speakers, except they
are worn on the ears so only one person can hear the
output at a time.
Hardware and Software
Hardware
 The physical components of computer system is called
hardware.

 This hardware is responsible for all the physical work of


the computer.

 Ex: CPU, monitor, mouse, keyboard, computer data


storage, graphics card, sound card, speaker and
motherboard.
Software
 The logical components of computer system is called
software.

 This software commands the hardware what to do &


how to do it. Together, the hardware &

 software form the computer system. This software is


further classified as system software & application
software.
Software
Application software

 Application software is a set of programs designed to


solve a particular problem for users.

 It allows the end user to do something besides simply


running the hardware. E.g.: Web Browser, MS Office,
Gaming Software, etc.
Software
System Software-
 System software are a set of programs, responsible for
running the computer, controlling various operations of
computer systems and management of computer
resources.

 They act as an interface between the hardware of the


computer & the application software. E.g.: Operating
System.
Operating System
Operating system
 An operating system (OS) is a
collection of software that
manages computer hardware
resources and provides
common services for computer
programs.

 An Operating System (OS) is an


interface between a computer
user and computer hardware.
Operating system
Operating Systems
1. MS-Windows
2. Ubuntu
3. Android OS
4. Mac OS
5. Fedora
6. Solaris
7. Free BSD
8. Chrome OS
Operating system
Operating System functions:
1. Process Management
2. Main Memory management
3. I/O device management
4. File Management
5. Secondary storage management
6. Network Management
7. System Protection
8. Command interpretation
Operating system
Classification of operating systems:
 Batch System
 Interactive System
 Time Sharing System
 Real Time System
 Multiprocessor system
 Multiuser System
Operating system
Batch System:
 Program, its related data and relevant control
command should be submitted together, in the form of
a job.

 No interaction between the users and the executing


programs, very simple, transfer control automatically.

 Scheduling of jobs is in the order of FCFS

 Good for the programs which have long execution time.


Operating system
Interactive System:
 An operating system that allows users to run interactive
programs.

 Pretty much all operating systems that are on PCs are


interactive OS.
Operating system
Time Sharing System:
 Time sharing (multitasking) is a logical extension of
multiprogramming.

 The CPU executes multiple jobs by switching among


them, but the switches occur so frequently that the users
can interact with each program while it is running

 CPU bound is divided into different time slots depending


upon the number of users using the system.
Operating system
Real Time System:
 This type of operating systems are used to control
Scientific devices and similar small instruments where
memory and resources are crucial.

 Provide quick response time and thus to meet a


scheduling deadline (time constraint).

 Applicable to Rocket launching, flight control, robotics.


Operating system
Multiprocessor system:
 Multiprocessor System consists of a set of processors that
shares a set of physical memory blocks over an
interconnection network.

 Controls and manage the hardware and software


resources such that user can view the entire system as a
powerful uniprocessor system.
 Design is too complex.
Operating system
Multiuser System:
 Multi-user is a term that defines an operating system or
application software that allows concurrent access by
multiple users of a computer.

 Time-sharing systems are multi-user systems. Most batch


processing systems for mainframe computers may also
be considered "multi-user", to avoid leaving the CPU idle
while it waits for I/O operations to complete.
Algorithm
Algorithm
 Algorithm is an ordered sequence of finite, well defined,
unambiguous instructions for completing a task.

or

It is a step- by-step procedure for solving a task or a


problem. The steps must be ordered, unambiguous and
finite in number.

 Algorithm is an English-like representation of the logic


which is used to solve the problem.
Algorithm
 A programming algorithm is a procedure or formula
used for solving a problem.

 It is based on conducting a sequence of specified


actions in which these actions describe how to do
something, and your computer will do it exactly that
way every time.
Algorithm
Characteristics of an algorithm:
 Precision – the steps are precisely stated.
 Uniqueness – results of each step are uniquely defined
and only depend on the input and the result of the
preceding steps.
 Finiteness – the algorithm stops after a finite number of
instructions are executed.
 Input – the algorithm receives input.
 Output – the algorithm produces output.
 Generality – the algorithm applies to a set of inputs.
Algorithm
For example,

An algorithm to add two numbers:

 Take two number inputs

 Add numbers using the + operator

 Display the result


Algorithm
An algorithm to add two numbers:

Step 1: Start

Step 2: Declare variables num1, num2 and sum.

Step 3: Read values num1 and num2.

Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2

Step 5: Display sum Step 6: Stop.


Algorithm
An algorithm to add two numbers:

Step 1: Start

Step 2: Declare variables num1, num2 and sum.

Step 3: Read values num1 and num2.

Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2

Step 5: Display sum

Step 6: Stop.
Algorithm
 Control Structures are just a way to specify flow of
control in programs.

 Any algorithm can be more clear and understood if they


use self-contained modules called as logic or control
structures.
 There are three basic types of logic, or flow of control,
 Sequence logic, or sequential flow
 Selection logic, or conditional flow ( if….else)
 Iteration logic, or repetitive flow (Repeat-For, while, until)
Algorithm
 Sequential Logic (Sequential Flow) Sequential logic

follows a serial or sequential flow in which the flow

depends on the series of instructions given to the

computer.
Algorithm
 Selection Logic (Conditional Flow)Selection Logic simply
involves a number of conditions or parameters which
decides one out of several written modules. The
structures which use these type of logic are known
as Conditional Structures.

If (condition A), then:


If (condition) then: If (Condition), then:
[Module A]
[Module A]
[Module A] Else if (condition B), then:
Else:
[Module B]
[End of If structure] [Module B]
..
[End if structure]
..
Else if (condition N), then:
[Module N]
[End If structure]
Algorithm
 Iteration Logic (Repetitive Flow)

The Iteration logic employs a loop which involves a repeat


statement followed by a module known as the body of a
loop.

Repeat for i = A to N by I: Repeat while condition:


[Module] [Module]
[End of loop] [End of Loop]
Algorithm
Algorithm: greatest between two numbers
Step 1: Start
Step 2: Declare variables A, B
Step 3: Read the two numbers A, B
Step 4: Compare A and B. If A is greater
output “A is greatest”.
Step 5: else
output “B is greatest”.
Step 6: Stop
Algorithm
 For accomplishing a particular task, different algorithms
can be written. The different algorithms differ in their
requirements of time and space.

 The programmer selects the best-suited algorithm for the


given task to be solved.

 Two simple algorithms to find the greatest among three


numbers, as follows:
Algorithm
Algorithm 1 greatest among three numbers
Step 1: Start
Step 2: Read the three numbers A, B, C
Step 3: Compare A and B. If A is greater
perform step 4
else
perform step 5.
Step 4: Compare A and C. If A is greater,
output “A is greatest”
Algorithm
Algorithm 1 greatest among three numbers
else
output “C is greatest”.
Perform step 6.
Step 5: Compare B and C. If B is greater,
output “B is greatest”
else
output “C is greatest”.
Step 6: Stop
Algorithm
Algorithm 2 greatest among three numbers
Step 1: Start
Step 2: Read the three numbers A, B, C
Step 3: Compare A and B. If A is greater,
store A in MAX,
else
store B in MAX.
Step 4: Compare MAX and C. If MAX is greater,
output “MAX is greatest”
else
output “C is greatest”.
Step 5: Stop
Algorithm
Some more example algorithms

 Algorithm of Fibonacci series

 Algorithm to find all the roots of the quadratic equation

 Algorithm to find the factorial

 Algorithm to check prime number


Algorithm of Fibonacci series

Step 1: Start
Step 2: Declare variable a, b, c, n, i
Step 3: Initialize variable a=0, b=1, i=2
Step 4: Read n from user
Step 5: Print a and b
Step 6: Repeat until i &lt n (&lt- less than)
6.1 c = a + b
6.2 print c
6.3 a=b, b=c
6.4 i=i+1
Step 7: Stop
Algorithm to find all the roots of the quadratic equation

Step 1: Start
Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;
Step 3: Calculate discriminant D ← b2-4ac
Step 4: If D ≥ 0
r1 ← (-b+√D)/2a and r2 ← (-b-√D)/2a
Display r1 and r2 as roots.
Else Calculate real part and imaginary part
rp ← - b/2a
ip ← √(-D)/2a
Display rp+j(ip) and rp-j(ip) as roots
Step 5: Stop
Algorithm to find the factorial

Step 1: Start
Step 2: Declare variables n, factorial and i.
Step 3: Initialize variables
factorial ← 1
i←1
Step 4: Read value of n
Step 5: Repeat the steps until i <= n
5.1: factorial ← factorial * i
5.2: i ← i+1
Step 6: Display factorial
Step 7: Stop
Algorithm to check prime number

Step 1: Start

Step 2: Declare variables n, i, flag.

Step 3: Initialize variables

flag ← 1

i←2

Step 4: Read n from the user.


Algorithm to check prime number

Step 5: Repeat the steps until i=(n/2)


5.1 If remainder of n÷i equals 0
flag ← 0
Go to step 6
5.2 i ← i+1
Step 6: If flag = 0
Display n is not prime
else
Display n is prime
Step 7: Stop
Advantages and Disadvantages Algorithm

 Advantages of Algorithms:

 It is easy to understand.

 Algorithm is a step-wise representation of a solution to a given


problem.

 In Algorithm the problem is broken down into smaller pieces or


steps hence, it is easier for the programmer to convert it into an
actual program.

 Disadvantages of Algorithms:

 Writing an algorithm takes a long time so it is time-consuming.

 Branching and Looping statements are difficult to show in


Algorithms.
Flowchart
Flowchart

 A flowchart is a diagrammatic representation of the


logic for solving a task.

 A flowchart is drawn using boxes of different shapes with


lines connecting them to show the flow of control.

 The purpose of drawing a flowchart is to make the logic


of the program clearer in a visual form.

 “A photograph is equivalent to thousand words”. The


same can be said of flowchart.
Flowchart

 The logic of the program is communicated in a much


better way using a flowchart. Since flowchart is a
diagrammatic representation, it forms a common
medium of communication.

 A flowchart may be simple or complex.

 A flowchart is drawn using different kinds of symbols. A


symbol used in a flowchart is for a specific purpose.
Flowchart

 The most common symbols that are used to draw a


flowchart are—Process, Decision, Data, Terminator,
Connector and Flow lines
Flowchart
Flowchart
 Process - operation or action step
 Alternate Process - alternate to normal process
 Document - a document
 Multi document - more than one document
 Preparation - set-up process
 Punched Tape - I/O from punched tape
 Collate - organize in a format
 Merge - merge in a predefined order
 Sort - sort in some order
 Display - display output
Flowchart
 Decision - decision or a branch
 Data - I/O to or from a process
 Manual Input - Data entry from a form
 Manual Operation - operation to be done manually
 Connector - join flow lines
 Off page connector - continue on another page
 Summing Junction - Logical AND OR—Logical OR
 Sequential Access storage - stored on magnetic tape
 Stored Data - general data storage
Flowchart
 Predefined process - process previously specified
 Internal Storage - stored in memory
 Termination - Start or stop point
 Delay - wait
 Magnetic Disk - I/O from magnetic disk
 Direct access storage - storing on hard disk
 Flow lines - indicates direction of flow
 Extract - split process
 Card - I/O from a punched car
Flowchart rules

While drawing a flowchart, some rules need to be followed

(1) A flowchart should have a start and end,

(2) The direction of flow in a flowchart must be from top to


bottom and left to right, and

(3) The relevant symbols must be used while drawing a


flowchart.
Flowchart Example
Draw a flow chart to find average of two number
Start

Enter num1, num2

Average =
(num1+num2)/2

Print Average

Stop
Control structures in flowchart

1. Sequential 2. Selection 3. Iteration


Flowchart Example
Draw a flow chart for greatest among three numbers
Flowchart Example
Draw a flow chart to find factorial of a number
Start

Enter n

Set
Factorial=1

Yes
Is Print
n=1 Factorial
No

Factorial=Factorial*n
Stop

n=n-1
Advantages Of Using FLOWCHARTS
 Communication: - Flowcharts are better way of
communicating the logic of a system to all concerned.
 Effective analysis: - With the help of flowchart, problem
can be analyzed in more effective way.
 Proper documentation: - Program flowcharts serve as a
good program documentation, which is needed for
various purposes.
 Efficient Program Maintenance: - The maintenance of
operating program becomes easy with the help of
flowchart. It helps the programmer to put efforts more
efficiently on that part
Pseudocode
Pseudocode

 Pseudocode is an informal way of programming


description that does not require any strict programming
language syntax or underlying technology
considerations.

 It is used for creating an outline or a rough draft of a


program.

 Pseudocode summarizes a program’s flow, but excludes


underlying details.
Pseudocode

 Pseudocode is not an actual programming language.


So it cannot be compiled into an executable program.

 It uses short terms or simple English language syntaxes to


write code for programs before it is actually converted
into a specific programming language.

 System designers write Pseudocode to ensure that


programmers understand a software project's
requirements and align code accordingly.
Pseudocode

 Pseudo code for finding a number is even or odd

Step1:Start
Step2:Print "Enter Any Number to Check, Even or Odd"
Step3:Read input of a number
Step4:If number mod 2 = 0
Print "Number is Even“
else
Print "Number is Odd“
Step5:End
Pseudocode
 Pseudocode for Factorial of a number :
Step 1: Start.
Step 2: Declare N and F as integer variable.
Step 3: Initialize F=1.
Step 4: Enter the value of N.
Step 5: Check whether N>0, if not then F=1.
Step 6: If yes then, F=F*N
Step 7: Decrease the value of N by 1 .
Step 8: Repeat step 6 and 7 until N=0.
Step 9: Now print the value of F.
Step 10: Stop.
Advantages of Pseudocode

 Pseudocode is understood by the programmers of all


types.

 it enables the programmer to concentrate only on the


algorithm part of the code development.

 It cannot be compiled into an executable program.


Example:

Java code : if (i < 10) { i++; }

Pseudocode : if i is less than 10, increment i by 1.


Source code
Source Code

 Source code is the language or string of words, numbers,


letters and symbols that a computer programmer uses.

“or”

 Code written by a programmer in a high-level language


and readable by people but not computers. Source
code must be converted to object code or machine
language before a computer can read or execute the
program.
Thank you

You might also like