You are on page 1of 61

II Sem(2020-21)

Programming for Problem


Solving
(CST151)

Mr. P. M. Sonsare (Assistant Professor )


Computer Science and Engineering RCOEM,
Nagpur
COURSE CONTENTS

Unit 1. Introduction to Programming

Unit 2. C Programming Language

Unit 3. Arrays and Basic Algorithms

Unit 4. Functions and Recursion

Unit 5. Pointer and Structures

Unit 6. File Handling


TEXT BOOKS

Text Books:
1. Programming in ANSI C : E. Balguruswami McGraw Hill
2. Mastering C: K. R. Venugopal and S. R. Prasad, Tata
McGraw Hill

Reference Books:
1. Programming with C: Byron Gottfried, Schaums Outline
Series.
2. Let Us C: Yashwant Kanetkar, BPB Publication
COURSE OUTCOMES:
On successful completion of course student will learn:

1. To formulate simple algorithms for arithmetic and logical problems, translate the
algorithms to programs (in C language), test and execute the programs and correct
syntax and logical errors.

2. To implement conditional branching, iteration and recursion, to decompose a


problem into functions and synthesize a complete program using divide and conquer
approach.

3. To use arrays, pointers, structures and I/O operations for the formulation of
algorithms and programs.

4. To apply programming to solve matrix addition, multiplication problems and


searching & sorting problems.
UNIT 1

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 / Pseudocode with
examples.
 Arithmetic expressions and precedence
PARTS OF A COMPUTER SYSTEM:

Hardware: Electronic Devices


Software: Instructions and Computer
Programs
HARDWARE

Input : Keyboard, Mouse


System unit:
Random Access Memory (RAM)
Central Processing Unit (CPU)
Output: Monitor, Printer
Secondary Storage: Disk Drive
SOFTWARE

 Instructions for the hardware.


 Actions to be performed
 A set of instructions is called a program.
 Driving force behind the computer
 Without a program – What is a computer?
▪ Collection of Hardware
 Two purposes:
 Tell the computer what to do
 Tell other people what we want the computer
to do.
FUNCTIONAL UNITS

Arithmetic
Input and
Logic Unit

Memory

Output Control Unit

I/O Processor

Basic functional units of a computer.


MEMORY (RAM)

 Stores data and program instructions for CPU to


execute
 A program and its data must be brought to
memory before they can be executed
 Stores intermediate and final results of
processing.
 Volatile: Contents are erased when computer is
turned off or reset.
 A memory unit is an ordered sequence of bytes,
each holds eight bits. A byte is the minimum
storage unit. No two data can share or split the
same byte.
STORAGE DEVICES

Hard Drives, CDs/DVDs, Flash Drives, etc.


Non-Volatile or Permanent Storage
Programs and data are permanently stored on
storage devices and are moved to memory
when the computer actually uses them.
COMPUTER LANGUAGE

 Digital devices have two stable states, which are


referred to as zero and one by convention
 The binary number system has two digits, 0 and 1. A
single digit (0 or 1) is called a bit, short for binary
digit. A byte is made up of 8 bits.
 Binary Language: Data and instructions (numbers,
characters, strings, etc.) are encoded as binary
numbers - a series of bits (one or more bytes made
up of zeros and ones)
COMPUTER LANGUAGE (CONT.)

 Encoding and decoding of data into binary is


performed automatically by the system based on the
encoding scheme
 Encoding schemes
 Numeric Data: Encoded as binary numbers
 Non-Numeric Data: Encoded as binary numbers using
representative code
 ASCII – 1 byte per character
 Unicode – 2 bytes per character
PROGRAMMING LANGUAGES

 Computers can not use human languages, and


programming in the binary language of computers is a
very difficult, tedious process
 Therefore, most programs are written using a
programming language and are converted to the binary
language used by the computer
 Three major categories of programming languages:
 Machine Language
 Assembly Language
 High level Language
MACHINE LANGUAGE

Natural language of a particular computer


Primitive instructions built into every
computer
The instructions are in the form of binary code
Any other types of languages must be
translated down to this level
ASSEMBLY LANGUAGES

English-like Abbreviations used for operations


(Load R1, R8)
Assembly languages were developed to make
programming easier
The computer cannot understand assembly
language - a program called assembler is used
to convert assembly language programs into
machine code
HIGH LEVEL LANGUAGES

English-like and easy to learn and program


Common mathematical notation
Total Cost = Price + Tax;
area = 5 * 5 * 3.1415;
Java, C, C++, FORTRAN, VISUAL BASIC,
PASCAL
COMPILING SOURCE CODE

A program written in a high-level language is


called a source program (or source code). Since a
computer cannot understand a source program.
Program called a compiler is used to translate
the source program into a machine language
program called an object program. The object
program is often then linked with other
supporting library code before the object can be
executed on the machine.
Source File Compiler Object File Linker Excutable File

18
PROGRAMMING

 Programming – the creation of an ordered


set of instructions to solve a problem with a
computer.
 Only about 100 instructions that the
computer understands - Different programs
will just use these instructions in different
orders and combinations.
 The most valuable part of learning to
program is learning how to think about
arranging the sequence of instructions to
solve the problem or carry out the task
PROGRAMMING FUNDAMENTALS:
PUTTING THE INSTRUCTIONS TOGETHER
 Sequential Processing
 A List of Instructions
 Conditional Execution
 Ifs
 Repetition
 Looping / Repeating
 Stepwise Refinement / Top-Down Design
 Breaking Things into Smaller Pieces
 Calling Methods / Functions / Procedures /
Subroutines
 Calling a segment of code located elsewhere
 Reuse of previously coded code segment
METHODS OF PROGRAMMING

 Procedural
 Defining set of steps to transform inputs into outputs
 Translating steps into code
 Constructed as a set of procedures
 Each procedure is a set of instructions

 Object-Oriented
 Defining/utilizing objects to represent real-world entities
that work together to solve problem
 Basic O-O Programming Components
 Class
 Object/Instance
 Properties
 Methods
PROBLEM SOLVING

 The process of defining a problem, searching for relevant


information and resources about the problem, and of
discovering, designing, and evaluating the solutions for
further opportunities. Includes:
 Finding an Answer to a Question
 Figuring out how to Perform a Task
 Figure out how to Make Things Work

 Not enough to know a particular programming language…


Must be able to problem solve…
 Very desirable to be a good Problem Solver in any CIS
discipline.
FOUR STEPS OF PROBLEM SOLVING

U – Understand the Problem


D – Devise a Good Plan to Solve

I – Implement the Plan

E – Evaluate the Solution


EXAMPLE:
SOLVING MATH WORD PROBLEM

Read the Problem: Understand the


description of problem or scenario, identifying
the knowns and unkowns
Decide how to go about solving the problem:
Determine what steps need to be taken to
reach the solution
Solve the Problem: Write the solution
Test the Answer: Make sure the answer is
correct
SOLVING COMPUTING PROBLEMS

In general, when we solve a computing


problem we are taking some inputs,
processing (performing some actions on) the
inputs, and then outputting the solution or
results.
This is the classic view of computer
programming – computation as calculation.
Four steps (UDIE) can be very effective when
applied to solving computing problems
STEP 1 - UNDERSTAND THE PROBLEM

 What is the Problem to be solved? What is the


unknown? What is the condition? What is the data?
What is needed to solve the problem? What actions
need to take place?
 Identify the inputs and outputs
 Identify the processes needed to produce the outputs
from the given inputs
 Draw a figure. Introduce suitable notation.
 Isolate Principle parts of the problem.
STEP 2 - DEVISE A PLAN

Find connections between the knowns and


unknowns.
Simplify: Break the problem into smaller sub-
problems
Design a solution
Make a plan or list of actions to implement
the solution
Algorithm / Flowchart / Psuedocode
STEP 2 - DEVISE A PLAN (CONT.)
 Algorithm
A FINITE set of clear, executable steps that will
eventually terminate to produce the desired
outcome
Logical design used to solve problems – usually a
list of actions required to perform task
 Pseudocode
Written like program code but more “English Like”
and doesn’t have to conform to language syntax
 Flowchart
Diagram that visually represents the steps to be
performed to arrive at solution.
STEP 3 - IMPLEMENT THE PLAN

Implement in a Programming Language.

Carry out the plan checking the


preliminary results at each step.

Code A Little Test A lot.


STEP 4 - EVALUATE THE SOLUTION

Run the Code


Check results repeatedly and thoroughly
Use numerous test cases or data sets
Use highly varied test case, including expected
as well as and unexpected cases
Look for new solutions
Is there a better, easier, or more efficient
solution
Can other problems be solved using these
techniques?
OPERATING SYSTEM

• It is the collection of system programs which acts


as an interface between user and the computer and
computer hardware.
• The purpose of an operating system is to provide an
environment in which A user can execute programs
in a convenient manner

31
FUNCTIONS OF OPERATING SYSTEM

• File handling and management.


• Storage management (Memory management).
• Device scheduling and management.
• CPU scheduling.
• Information management.
• Process control (management).
• Error handling
• Protecting itself from user & protecting user from
other users.
32
ALGORITHM

 A set of sequential steps usually written in Ordinary


Language to solve a given problem is called
Algorithm.
 The choice of various algorithms depends on the
factors like reliability, accuracy and easy to modify.
 The most important factor in the choice of algorithm
is the time requirement to execute it, after writing
code in High-level language with the help of a
computer.
 The algorithm which will need the least time when
executed is considered the best.
33
STEPS INVOLVED IN ALGORITHM
DEVELOPMENT

An algorithm can be defined as “a complete, unambiguous,


finite number of logical steps for solving a specific problem “
Step1. Identification of input.
Step2: Identification of output.
Step3 : Identification the processing
operations.
Step4 : Processing Definiteness.
Step5 : Processing Finiteness.
Step6 : Possessing Effectiveness.
34
PROPERTIES OF ALGORITHM

1. Finiteness
2. Definiteness
3. Effectiveness
4. Generality
5. Input/output

35
Suppose we want to find the average of three numbers, the
algorithm is as follows:

Step 1:Read the numbers a, b, c, s, avg, d


Step 2:Compute the sum of a, b and c.
s= a + b + c
Step 3 :Divide the sum by 3
avg =s/3
Step 4 :Store the result in variable d
d= avg
Step 5:Print the value of d
Step 6 :STOP

36
Write an algorithm to calculate the simple interest using the
formula Simple interest = P*N* R/100. Where P is principle
Amount, N is the number of years and R is the rate of interest.

Step 1: Read the three input quantities’ P, N and R.


Step 2 : Calculate simple interest as
Simple interest = P* N* R/100
Step 3: Print simple interest.
Step 4: Stop.

37
Write an algorithm to find the area of the triangle.

38
Write an algorithm to find the largest of three numbers X, Y,Z.

Step 1: Read the numbers X,Y,Z.


Step 2:
if (X > Y)
Big = X
else
Big = Y
Step 3 :
if (Big < Z)
Big = Z

Step 4: Print the largest number i.e. Big

Step 5: Stop.

39
Write down an algorithm to find the largest data value of a set
of given data values.

Step 1: LARGE=0
Step 2: read NUM
Step 3:
While NUM > = 0 do
if NUM > LARGE then
LARGE=NUM
read NUM
Step 4: Write “largest data value is”, LARGE
Step 5: STOP

40
 Write algorithm to find the factorial of a given number N

Step 1: Fact=1
Step 2: I=1
Step 3: read N
Step 4:
While I < N do
Fact =Fact* I
I=I + 1
Step 5: Write “Factorial of”, N, “is”, Fact
Step 6: end.

41
 Algorithm to check Prime Number.

 Step 1 → Take integer variable A


 Step 2 → Divide the variable A with (2 to A-1)

FOR loop = 2 to A - 1
check if number is divisible by loop
IF divisible
RETURN "NOT PRIME"
END IF
END FOR
RETURN "PRIME"
 Step 3 → STOP

42
 Find Root of the quadratic equation ax 2 + bx + c = 0
S te p 1 : S t a r t
S te p 2 : D e c l a r e v a r i a b le s a , b , c , D , r 1 , r 2 , r p a n d i p ;
S te p 3 : C a l c ula te
D ← b2-4ac
S te p 4 : I f ( D = = 0 )
r1=-b/2a
r2=-b/2a
D i spl ay r 1 a n d r 2 a s r o o t s .
e l s e i f (D > 0 )
r 1 ← ( - b + √D ) / 2 a
r 2 ← ( - b - √D ) / 2 a
D i s p lay r 1 a n d r 2 a s r o o t s .
else
C a l c ula te r e a l p a r t a n d i m a g i n a r y p a r t
rp ← -b/2a
ip ← √(-D)/2a
D i s p lay r p + j ( i p ) a n d r p - j ( i p ) a s r o o t s

S te p 5 : S to p
43
FLOWCHART

A flow chart is a step by step diagrammatic


representation of the logic paths to solve a
given problem.
A flowchart is visual or graphical
representation of an algorithm.
 The flowcharts are pictorial representation of
the methods to be used to solve a given
problem and help a great deal to analyze the
problem and plan its solution in a systematic
and orderly manner.

44
ADVANTAGES OF FLOWCHARTS

 The flowchart shows the logic of a problem displayed


in pictorial fashion which felicitates easier checking
of an algorithm.
 The Flowchart is good means of communication to
other users. It is also a compact means of recording
an algorithm solution to a problem.
 The flowchart allows the problem solver to break the
problem into parts. These parts can be connected to
make master chart.
 The flowchart is a permanent record of the solution
which can be consulted at a later time.
45
FLOWCHART NOTATION

Name Symbol Purpose


Terminal Oval start/stop/begin/end

Input/output Input/output of data

Parallelogram

Process Rectangle Any processing to be


performaed can be
represented
Decision box Diamond Decision operation that
determine which of the
alternative paths to be
followed
Connector Circle Used to connect different
parts of flowchart
FLOWCHART NOTATION

Name Symbol Purpose


Flow Arrows Join 2 symbols and also
represents flow of
execution
Pre defined process Double Sided Rectangle Module (or) subroutines
specified else where

Page connector Pentagon Used to connect


flowchart in 2 different
pages
For loop symbol Hexagon shows initialization,
condition and
incrementation of loop
variable
Document Printout Shows the data that is
ready for printout
ADD T WO NUMBERS ENTERED BY THE USER.

48
FIND THE LARGEST AMONG THREE DIFFERENT
NUMBERS ENTERED BY THE USER.

49
CHECK WHETHER YEAR IS LEAP OR NOT

50
PSEUDO CODE

 The Pseudo code is neither an algorithm nor a program. It is


an abstract form of a program. It consists of English like
statements which perform the specific operations.
 It is defined for an algorithm. It does not use any graphical
representation.
 In pseudo code, the program is represented in terms of words
and phrases, but the syntax of program is not strictly
followed.

Advantages: * Easy to read, * Easy to understand, * Easy to


modify.

51
 Example: Write a pseudo code to perform the basic arithmetic
operations.

Read n1 , n2
Sum = n1 + n2
Dif f = n1 – n2
Mult = n1 * n2
Div = n1/n2
Print Sum, Dif f, Mult, Div
End.

52
PSEUDOCODE & ALGORITHM

 Example 1: Write an algorithm to determine a student’s final


grade and indicate whether it is passing or failing. The final
grade is calculated as the average of four marks.
PSEUDOCODE & ALGORITHM

Pseudocode:
Input a set of 4 marks
Calculate their average by summing and
dividing by 4
if average is below 50
Print “FAIL”
else
Print “PASS”
PSEUDOCODE & ALGORITHM

Detailed Algorithm
 Step 1: Input M1,M2,M3,M4
Step 2: GRADE  (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
EXAMPLE

START
Step 1: Input M1,M2,M3,M4
Step 2: GRADE  (M1+M2+M3+M4)/4
Input
M1,M2,M3,M4
Step 3: if (GRADE <50) then
Print “FAIL”
else
GRADE(M1+M2+M3+M4)/4 Print “PASS”
endif
N IS Y
GRADE<50

PRINT PRINT
“PASS” “FAIL”

STOP
EXAMPLE 2

 Write an algorithm and draw a flowchart to convert the length


in feet to centimeter.
Pseudocode:
 Input the length in feet (Lf t)
 Calculate the length in cm (Lcm) by multiplying LFT with 30
 Print length in cm (LCM)
EXAMPLE 2

Algorithm Flowchart
 Step 1: Input Lft
START
 Step 2: Lcm  Lft x 30
 Step 3: Print Lcm Input
Lft

Lcm  Lft x 30

Input
Lcm

STOP
EXAMPLE 3

Write an algorithm and draw a flowchart that


will read the two sides of a rectangle and
calculate its area.
Pseudocode
Input the width (W) and Length (L) of a
rectangle
Calculate the area (A) by multiplying L with W
Print A
EXAMPLE 3

Algorithm
START
 Step 1: Input W,L
 Step 2: AL x W Input
 Step 3: Print A W, L

ALxW

Print A

STOP
EXAMPLE 4

Write an algorithm and draw a flowchart that will find sum of


digit of number.

 Step 1: Get number by user


 Step 2: Get the modulus/remainder of the number
 Step 3: sum the remainder of the number
 Step 4: Divide the number by 10
 Step 5: Repeat the step 2 while number is greater than 0.

61

You might also like