You are on page 1of 154

SUBJECT

20ESCS101
CODE

TYPE THE SUBJECT


PROBLEM NAME
SOLVING HERE
AND PROGRAMMING IN C (common to All Branches)

UNIT NO 1

INTRODUCTION TO PROGRAMMING AND


ALGORITHMS FOR PROBLEM SOLVING
1.1 The Basic Models of Computation ,
Programming paradigms
I I

20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C
(common to All Branches)
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)

1.1 THE BASIC MODEL OF COMPUTATION - INTRODUCTION


❖ Before any machine is designed, a prototype or a model is constructed.
❖ This model gives an overview of what the machine will do, what will be the inputs and what
will be the outputs.
❖ The inner working of the machine depends on the relation between inputs and outputs.
❖ A model is not the real thing, a model is created to understand how to build the real machine.
❖ The basic model of computation (also called the Model of Computing), serves the same
purpose.
❖ A model of computing defines the capabilities of an abstract computer.
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)

WHAT IS A MODEL?
❖ An abstract description of a real world entity
❖ Attempts to capture the essential features while suppressing the less important details.
❖ Important to have a model that is both precise and as simple as possible to support theoretical
studies of the entity modelled.
WHAT DOES COMPUTATION MEAN?
❖ A computation is any type of calculation that includes both arithmetical and non-arithmetical
steps and which follows a well-defined model (e.g. an algorithm).
❖ Mechanical or electronic devices (or, historically, people) that perform computations are
known as computers.
❖ An especially well-known discipline of the study of computation is computer science.
THEN WHAT IS MODEL OF COMPUTATION ?
❖ Describes a class of computers and allows algorithms to be written for a general model
rather than for a specific computer.
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)

A MODEL OF COMPUTING SPECIFIES:


❖ What operations an algorithm can do (like addition, subtraction, moving data from one
memory location to another)
❖ Cost of operation. (Involves CPU time and Memory)
❖ A model of computation is not a physical device, it is a mathematical idea. Based on this
model of computation we build an algorithm.
❖ A computer does not only do calculations, it also communicates with its environment. The
environment of a computer is its memory and CPU. So a computer exchanges data between
memory and CPU.
❖ Of course, a model of computing should be implementable by a physical machine.
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)

❖ We know that a program is written in a computer


language (like Python, Java, etc) and a computer is
needed to run a program.
❖ This relation between program, programming language
and a computer is shown on the left side in the diagram.
❖ In a similar way, the relation between an algorithm,
pseudo code and model of computation is shown on the
right side of this diagram.
❖ The double-headed arrows indicate that there is an
equivalence between the two blocks.
So, from this diagram we see that:
❖The mathematical equivalent of a program is an algorithm (and vice-versa),
❖The mathematical equivalent of a programming language is pseudo code or statements steps in
structured English, and
❖The mathematical equivalent of a computer is the model of computation.
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)

VARIOUS MODELS OF COMPUTATION

There are many models of computation but we shall state only a few here as follows:
❖ Random Access Machines

❖ Straight Line Programs and Circuits

❖ Turing Machines

❖ Pointer Machines

❖ Decision Trees

Real Scientists Test Powerful Devices


20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)

RANDOM ACCESS MACHINE:


❖ A simple model of computation.
❖ Its memory consists of an unbounded sequence of registers.
❖ Each of the registers may hold an integer value.
❖ The control unit of a RAM holds a program, i.e. a numbered
list of statements.
❖ The program counter determines which statement (registar) is
to be executed next.

STRAIGHT LINE PROGRAMS AND CIRCUITS

❖ A straight-line program is set of steps each of which is an input step, denoted (s READ x),
an output step, denoted (s OUTPUT i), or a computation step, denoted (s OP i . . . k).
❖ Here s is the number of a step, x denotes an input variable, and the keywords READ, OUTPUT,
and OP identify steps in which an input is read, an output produced, and the operation OP is
performed.
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)


TURING MACHINES:
❖A mathematical model which consists of an infinite length tape
divided into cells on which input is given.
❖It consists of a head which reads the input tape.
❖A state register stores the state of the Turing machine.
❖After reading an input symbol, it is replaced with another symbol,
its internal state is changed, and it moves from one cell to the right or
left.
❖If the TM reaches the final state, the input string is accepted,
otherwise rejected.
POINTER MACHINE:
❖A model of computation whose memory consists of an unbounded collection of registers, or records,
connected by pointers.
❖Each register may contain an arbitrary amount of additional information. No arithmetic is allowed to
compute the address of a register. The only way to access a register is by following pointers.
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)

DECISION TREES:
❖ A decision tree is a decision support tool that uses a tree-like model of decisions and their
possible consequences, including chance event outcomes, resource costs, and utility.
❖ It is one way to display an algorithm that only contains conditional control statements.
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)

NEED FOR STUDYING MODELS OF COMPUTATION:


❖Natural languages like English, Hindi are rich languages because a wide variety of ideas can be
expressed through these languages. But the drawback of these languages are that they can be
ambiguous. So a word or a sentence may have more than one meaning which can cause confusion.
❖A programming language should be able to express complex ideas in a simple and unambiguous
way.
❖Expressiveness of a programming language means how easily the programmer can express a
complex idea.
❖The expressiveness of a programming language is concerned with its semantics and not with
syntax. Syntax is concerned with grammar of the language like whether to put a semicolon or colon,
etc) and semantics is concerned with the meaning of the statement.
❖Different languages have different levels of expressiveness.
❖A language like Python or R is more expressive than C language.
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)

PROGRAMMING PARADIGMS:
❖Paradigm can also be termed as method to solve some problem or do some task.
❖Programming paradigm is an approach to solve problem using some programming language or
also we can say it is a method to solve a problem using tools and techniques that are available to
us following some approach.
❖There are lots for programming language that are known but all of them need to follow some
strategy when they are implemented and this methodology/strategy is paradigms.
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)

1. IMPERATIVE (HOW TO DO) PROGRAMMING PARADIGM:


❖ It is one of the oldest programming paradigm.
❖ It works by changing the program state through assignment statements.
❖ It performs step by step task by changing state.
❖ The main focus is on how to achieve the goal.
❖ The paradigm consist of several statements and after execution of all the result is stored.
Advantages:
❖ Very simple to implement
❖ It contains loops, variables etc.
Disadvantages:
❖ Complex problem cannot be solved
❖ Less efficient and less productive
❖ Parallel programming is not possible
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)


❖ Imperative programming is divided into three broad categories:
Procedural, OOP and parallel processing.
❖ These paradigms are as follows:
Procedural programming paradigm – This paradigm emphasizes on procedure in terms of under
lying machine model. There is no difference in between procedural and imperative approach. It
has the ability to reuse the code and it was boon at that time when it was in use because of its
reusability.
Object oriented programming –The program is written as a collection of classes and object which
are meant for communication. The smallest and basic entity is object and all kind of computation
is performed on the objects only. It can handle almost all kind of real life problems which are
today in scenario.
Parallel processing approach – Parallel processing is the processing of program instructions by
dividing them among multiple processors. A parallel processing system posses many numbers of
processor with the objective of running a program in less time by dividing them. This approach
seems to be like divide and conquer.
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)

2. DECLARATIVE (WHAT TO DO) PROGRAMMING PARADIGM:


❖The declarative programming is a style of building programs that expresses logic of computation
without talking about its control flow.
❖It often considers programs as theories of some logic.
❖It may simplify writing parallel programs.
❖The focus is on what needs to be done rather how it should be done basically emphasize on what
code is actually doing.
❖It just declare the result we want rather how it has be produced.
Advantages:
❖Short, efficient code
❖Easy optimization as implementation is controlled by an algorithm
Disadvantages:
❖Sometimes hard to understand for external people
❖Based on an unfamiliar conceptual model for people (solution state)
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)

❖ Declarative programming paradigm is divided into three broad categories


Logic, Functional, Database.
❖ These paradigms as follows:
Logic programming paradigms – It can be termed as abstract model of computation. It would solve
logical problems like puzzles, series etc. In logic programming we have a knowledge base which we
know before and along with the question and knowledge base which is given to machine, it
produces result. In logical programming the main emphasize is on knowledge base and the problem.
Functional programming paradigms – The functional programming paradigms has its roots in
mathematics and it is language independent. The key principal of this paradigms is the execution of
series of mathematical functions. The central model for the abstraction is the function which are
meant for some specific computation and not the data structure. The function hide their
implementation. Function can be replaced with their values without changing the meaning of the
program.
Database/Data driven programming approach – This programming methodology is based on data
and its movement. Program statements are defined by data rather than hard-coding a series of steps.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

https://www.youtube.com/watc
h?v=vJqBBh2XFTM

https://www.youtube.com/w
atch?v=Zc54gFhdpLA
https://forms.gl
e/v3wzWpXvw
https://www.youtube.com/wa U8hqJJ68
tch?v=4mjhQahK3GU
20ESCS101

PROBLEM SOLVING AND PROGRAMMING IN C (common to All Branches)

Thank you
SUBJECT CODE

TYPE THE SUBJECT NAME HERE

UNIT NO 1
INTRODUCTION TO PROGRAMMING AND
ALGORITHMS FOR PROBLEM SOLVING

1.2 Program Development Life Cycle

I I

20ESCS101
Problem Solving and Programming in C
(Common to ALL Departments)
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Program Development Life Cycle


Program Development Life Cycle (PDLC/SDLC) is a systematic way of developing
quality software.
It provides an organized plan for breaking down the task of program development into
manageable chunks, each of which must be successfully completed before moving on to
the next phase.

The Problem Development Life Cycle contains 6 Phases

1. Problem Definition
2. Problem Analysis
3. Algorithm Development
4. Coding & Documentation
5. Testing & Debugging
6. Maintenance
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Program Development Life Cycle


1. Problem Definition
In this phase, we define the problem statement and we decide the boundaries of the problem.
In this phase we need to understand the problem statement, what is our requirement, what
should be the output of the problem solution. These are defined in this first phase of the
program development life cycle.

2. Problem Analysis
In phase 2, we determine the requirements like variables, functions, etc. to solve the problem.
That means we gather the required resources to solve the problem defined in the problem
definition phase. We also determine the bounds of the solution.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Program Development Life Cycle


3. Algorithm Development
During this phase, we develop a step by step procedure to solve the problem using the
specification given in the previous phase. This phase is very important for program
development. That means we write the solution in step by step statements.

4. Coding & Documentation


This phase uses a programming language to write or implement the actual programming
instructions for the steps defined in the previous phase. In this phase, we construct the actual
program. That means we write the program to solve the given problem using programming
languages like C, C++, Java, etc.,
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Program Development Life Cycle


5. Testing & Debugging
During this phase, we check whether the code written in the previous step is solving the
specified problem or not. That means we test the program whether it is solving the problem for
various input data values or not. We also test whether it is providing the desired output or not.

6. Maintenance
During this phase, the program is actively used by the users. If any enhancements found in
this phase, all the phases are to be repeated to make the enhancements. That means in this
phase, the solution (program) is used by the end-user. If the user encounters any problem or
wants any enhancement, then we need to repeat all the phases from the starting, so that the
encountered problem is solved or enhancement is added.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Video Link

Program development life cycle


SUBJECT CODE

TYPE THE SUBJECT NAME HERE

UNIT NO. 1

INTRODUCTION TO PROGRAMMING AND ALGORITHMS


FOR PROBLEM SOLVING

1.3 ALGORITHMS

I I

20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C
(Common to CSE & IT)
20PCSPC101
ADVANCED DATA STRUCTURES AND ALGORITHMS

ALGORITHMS

- An algorithm can be defined as “a complete, unambiguous, finite number of


logical steps for solving a specific problem “

● Sequence of instructions to be followed to solve a problem


● Algorithm is generally developed before the actual coding is done
● Independent of underlying programming languages
● It is written in English language statements so that it is to be understood
even by non-programmers.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Characteristics and Properties of Good Algorithms:

● Clear and unambiguous


● Well defined input and output
● Finiteness
● Definiteness
● Effectiveness
● Correctness
● Feasible
● Language Independent
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Steps involved in Algorithm Development:

1. The problem that is to be solved by this algorithm


2. Identification of input
3. Identification of output
4. The constraints of the problem that must be considered
5. Identification of the processing steps
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Algorithms ---- Examples :

1. Design an algorithm to add two numbers and display the result

Step 1 − START

Step 2 − declare three integers a, b & c

Step 3 − define values of a & b

Step 4 − add values of a & b

Step 5 − store output of step 4 to c

Step 6 − print c

Step 7 − STOP
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Algorithms ---- Examples (Contd.,) :

2. Algorithm to convert temperature from Celsius to Fahrenheit

C : temperature in Celsius F : temperature Fahrenheit Algorithm

Step-1 Start

Step-2 Input temperature in Celsius say C

Step-3 F = (9.0/5.0 x C) + 32

Step-4 Display Temperature in Fahrenheit F

Step-5 Stop
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Algorithms ---- Examples (Contd.,) :

3. Algorithm to find Area and Perimeter of Square

L : Side Length of Square AREA : Area of Square PERIMETER : Perimeter


of Square

Step-1 Start
Step-2 Input Side Length of Square say L
Step-3 Area = L x L
Step-4 PERIMETER = 4 x L
Step-5 Display AREA, PERIMETER
Step-6 Stop
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Algorithms ---- Examples (Contd.,) :

4. Algorithm to find Biggest of Two Numbers

Step 1: Start
Step 2: Declare variables a,b
Step 3: Read variables a,b
Step 4: If a > b
Display a is the largest number.
Else
Display b is the largest number.
Step 5: Stop
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Algorithms ---- Examples (Contd.,) :

5. Write an algorithm to find all roots of a quadratic equation ax2+bx+c=0

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
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
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Algorithms ---- Examples (Contd.,) :

6.Write an algorithm to find the factorial of a number entered by the user.

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
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Algorithms ---- Examples (Contd.,) :

7. Write an algorithm to find the Fibonacci series till term≤1000

Step 1: Start
Step 2: Declare variables first_term,second_term and temp.
Step 3: Initialize variables first_term ← 0 second_term ← 1
Step 4: Display first_term and second_term
Step 5: Repeat the steps until second_term ≤ 1000
5.1: temp ← second_term
5.2: second_term ← second_term + first_term
5.3: first_term ← temp
5.4: Display second_term
Step 6: Stop
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Thank You
SUBJECT CODE

TYPE THE SUBJECT NAME HERE

UNIT NO 1
INTRODUCTION TO PROGRAMMING AND
ALGORITHMS FOR PROBLEM SOLVING

1.4 Pseudo code

I I

20ESCS101
Problem Solving and Programming in C
(Common to ALL Departments)
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Pseudocode

❖ Pseudocode is a combination of two words Pseudo and Code.’Pseudo’ means imitation


and ‘code’ refer to instruction written in the programming language.
❖ Pseudo code is not a real programming language.It is the generic way of describing an
algorithm without using any specific programming language-related notations.
❖ Purpose- to define the procedural logic of an algorithm in a simple, easy-to- understand
for its readers.
❖ Consists of natural language-like statements that precisely describe the steps of an
algorithm or program.
❖ Pseudo code cannot be compiled and executed and there are no real formatting or
syntax rules for writing pseudo codes.
The key difference between an algorithm and pseudocode is that an algorithm is a
formal, step-by-step set of instructions for solving a problem or accomplishing a task,
while pseudocode is a less formal description of an algorithm that is often used as a
design tool.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )
101

Features of Pseudocode

1. It uses plain English statements


2. It emphasizes on the design of the computer program
3. Focuses on the logic of the algorithm or program
4. It uses Structured English
5. Avoids language-specific elements
6. It is detailed and readable to draw an inference
7. It enables the programmers to concentrate on the algorithms.
8. Free of syntactical complications of programming language.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Preparing a pseudo code

1. Pseudo code is written using structured English.


2. In a pseudo code, some terms are commonly used to represent the various actions.
3. For example, for inputting data the terms may be (INPUT,GET, READ,OBTAIN), for
outputting data ( OUTPUT, PRINT, DISPLAY), for calculations ( COMPUTE,
CALCULATE,DETERMINE), for incrementing ( INCREMENT), initialization-
INITIALIZE,SET.
4. ADD, SUBTRACT used for addition and subtraction
5. For conditional statements uses terms like IF, ELSE, ENDIF and looping
statements like WHILE, DO WHILE etc.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Pseudo code Examples


Major constructions in pseudo code structures are sequence and
selection(decision). sequence indicates the continuous flow of the program,whereas
selection uses logical comparison or conditional check for making decisions.

Example:
IF(condition) THEN
List of Actions
ELSE
List of different Actions
END IF
Example: pseudo code for Multiplying two numbers
READ a,b
COMPUTE C=a*b
PRINT C
STOP
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Example: pseudo code for greatest of three numbers

BEGIN

READ a,b,c

IF (a>b) and (a>c) THEN

WRITE a is big

ELSE IF (B>C) THEN

WRITE b is big

ELSE

WRITE c is big

END IF

END
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Example: find sum of first 100 integers

BEGIN

INITIALIZE SUM to zero

INITIALIZE I to zero

DO WHILE (I <100)

INCREMENT I

ADD I to SUM and store in SUM

END DO WHILE

PRINT SUM

STOP
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Example: Pseudocode to Calculate Area and Perimeter of Rectangle

BEGIN

NUMBER b1,b2,area,perimeter

INPUT b1

UNPUT b2

area=b1*b2

perimeter=2*(b1+b2)

OUTPUT area

OUTPUT perimeter

END
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Example: pseudo code to Print Numbers from 1 to 100

BEGIN

NUMBER counter

FOR counter = 1 TO 100 STEP 1 DO

OUTPUT counter

ENDFOR

END
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Example: pseudocode to find sum and average of given two


numbers.

BEGIN
WRITE “Please enter two numbers to add”
READ num1
READ num2
COMPUTE Sum = num1+num2
COMPUTE Avg = Sum/2
WRITE Sum, Avg
END
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Advantages of Pseudo code

1. Since,it is language independent,it can be used by most


programmers
2. It is easier to develop the program from pseudo code than with a
flowchart
3. It is easier to translate to the programming language
4. Its simple structure and readability makes it easier to modify as
well

Disadvantages of Pseudo code

1. It does not provide the visual representation of the program logic


2. There are no accepted standards for writing pseudo code
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

VIDEO LINK

1. https://www.youtube.com/watch?v=preyTbKXDoQ
2. https://www.youtube.com/watch?v=6fHRtZC_kXU
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

THANK YOU
SUBJECT CODE

TYPE THE SUBJECT NAME HERE

UNIT NO 1
INTRODUCTION TO PROGRAMMING AND
ALGORITHMS FOR PROBLEM SOLVING

1.5 Flowchart

I I

20ESCS101
Problem Solving and Programming in C
(Common to ALL Departments)
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
Flow Chart:

● A flowchart is a graphical or symbolic representation of a process. It is to visualize the logic of the


process, so that they can gain a better understanding of the process and find flaws.

● When designing a flowchart, each step in the process is depicted by a different symbol and is
associated with a short description.

● The symbols in the flowchart are linked together with arrows to show the flow of logic in the
process.

Flow chart symbols:

Basic symbols:
Start and end symbols are also known as the terminal symbols
and are represented as circles, ovals, or rounded rectangles. Terminal
Start Stop symbols are always the first and the last symbols in a flowchart.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART

Input/ Output Input/output symbols are represented using a parallelogram and are
used to get inputs from the users or display the results to them.

Generic processing step, also called as an activity, is represented using a


rectangle. Activities include instructions such as add a to b, save the result.
Process
Therefore, a processing symbol represents arithmetic and data movement
instructions.

Used to display the output of a program


20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART

● The decision block should be a True/False choice.A conditional or


decision symbol is represented using a diamond.

F ● It is basically used to depict a Yes/No question or a True/False test.

● The two arrows coming out of it, one from the bottom vertex and the
other from the right vertex, correspond to Yes or True, and No or False,
T respectively.

● The arrows should always be labelled. A decision symbol in a flowchart


can have more than two arrows, which indicate that a complex decision
is being taken.
Arrows

Arrows depict the flow of control of the program. They illustrate the
exact sequence in which the instructions are executed.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
Control structure in flow chart:

• Sequence structure – instructions are executed in linear order.

• Selection(branch) Structure – it asks a true/ false question and then selects the next
instructions based on the answer Eg: if condition
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART

• Loop (Iterative)structure – It repeats the execution of a block of instructions until the condition satisfies

Eg: while loop


20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART

Flowchart Advantages

• Flowcharts are easier to understand compare to Algorithms and Pseudo code.

• It helps us to understand Logic of given problem.

• Using only very few symbol, complex problem can be represented in flowchart.

• It helps us in debugging process.


20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART

Flowchart Disadvantages

• Complex Logic- flowchart becomes complex and clumsy

• Alterations and modifications – flowchart need to be redrawn


20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART

Flowchart of for Loop

for(initialization;test-exp;inc/dec)
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
Flowchart of while loop

while(test-exp)
{
body
}
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART

Flowchart of do...while loop

do
{
body
}while(test-exp);
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
switch Statement Flowchart

switch(exp)
{
case 1: body
case 2:body
.
.
default:body
}
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
Adding two numbers

start

Read num1,
num2

result= num1+num2

Store result

stop
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
Average of 3 numbers
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
Converting fahrenheit to celsius
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
To calculate simple interest
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
Finding leap year or not
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

To check Odd or Even Number


20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
To check armstrong no or not
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
To find factorial of a given number
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
To calculate area of a sphere

Yes
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
Adding integers from 1 to N
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

FLOWCHART
A simple calculator program
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Video Link

https://youtu.be/nG_2fCIjK8U
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

THANK YOU
SUBJECT CODE

TYPE THE SUBJECT NAME HERE

UNIT NO. 1

INTRODUCTION TO PROGRAMMING AND ALGORITHMS


FOR PROBLEM SOLVING

1.6 Programming Languages, Compilation, Linking and Loading,


Testing and Debugging , documentation
I I

20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C
(Common to CSE & IT)
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

PROGRAMMING LANGUAGES

● What is a programming language


● Why is it easy to use Programming languages
○ user friendly instructions
○ functions
○ operators
● Relative merits of programming languages over Machine language and
assembly language
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Basic components of a programming language

●Programming environment
●Syntax of the instructions/ Operations
●Set of recognizable characters
●Variables
●Constants
●Keywords
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Basic components of a programming language

● Operators
● Arrays
● Strings
● File handling
● Error and exception handling
● Built in and user defined functions
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Characteristics of a programming language

● A programming language must be simple, easy to learn and use, have


good readability and be human recognizable.
● Abstraction is a must-have Characteristics for a programming
language in which the ability to define the complex structure and then
its degree of usability comes.
● A portable programming language is always preferred.
● Programming language’s efficiency must be high so that it can be
easily converted into machine code and executed
● consumes little space in memory.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Characteristics of a programming language

●A programming language should be well structured and documented so that it


is suitable for application development.
●Necessary tools for development, debugging, testing, maintenance of a
program must be provided by a programming language.
●A programming language should provide a single environment known as
Integrated Development Environment(IDE).
●A programming language must be consistent in terms of syntax and
semantics.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Different Types of programming language

1.Machine and assembly languages Meaddowsb

2.Algorithmic Languages - FORTRAN, ALGOL, LISP, C


3.Business-oriented languages- COBOL, SQL
4.Education-oriented languages- BASIC, PASCAL, LOGO, HYPERTALK
5.Object-oriented languages- C++, ADA, JAVA,VISUAL BASIC, PYTHON,
6.Declarative languages- PROLOG, LISP, HASKELL, ML,..
7.Scripting languages- PERL, JAVASCRIPT, PHP, ASP.NET,
RUBY,NODE.JS
8.Document formatting languages- Tex, POSTSCRIPT,SGML
9.World Wide Web display languages- HTML, XML
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Programming Constructs

Any good programming language should have constructs for supporting the following
three ways of instruction execution, namely:
1.Sequence
2.Selection
3. Iteration
●Sequence is rather easy to implement where the instructions are executed one after the
other without any change in the order of execution and it’s order of arrangement.
●Selection is the mechanism by which only one course of instruction is selected and
executed, from among more than one set of instructions available. These instructions are
selected based on the outcome of a condition that evaluates to True or False.
Sometimes, there may be more than one choice available. Based on the choice of the
user, the programming construct may select one of the available options and execute the
same.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Programming Constructs

●Iteration is the process of selecting and executing a set of instructions over


and again either for a specified number of times or till a condition is satisfied.
These programming constructs evaluate a conditional expression and decide
whether the set of instructions are to be iterated over again or not. There are
two types of iteration statements, namely, Entry Control and Exit Control
looping structures.
In Entry control looping, the condition is evaluated and based on the output the
instructions in the body of the loop is executed.
In Exit control loop, the set of instructions in the body of the loop is executed
and then the condition is evaluated to decide for the next round of execution.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Compilation
The programming language is easier to be understood by the user, but it cannot be
executed by the computer in the present form. It needs to be presented in the form that
could be understood by the machine. A software (another program) would convert the
program into machine understandable format. This program is called as a compiler. The
compiler reads through the program one or more times (called as Phases of a compiler)
and then converts it into an object file.
A translation program that converts the high level language constructs into machine
readable format can be an Assembler, interpreter or compiler.
Assembler is used for converting mnemonics into machine language whereas an
interpreter and a compiler is used for converting high level languages into machine
language.
The difference between compiler and interpreter is that an interpreter reads the high level
language program line by line whereas the compiler reads the program in entirety and
then converts it into machine language
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Steps in Compilation
The compilation process in C language is made up of four steps
1.Preprocessing. A preprocessor is a text substitution tool or macro preprocessor for C,
that provides the ability for the inclusion of header files, macro expansions, conditional
compilation, and line control.The # symbol marks the statements that are to be
processed by the preprocessor.
2.The second stage is the compilation, where the preprocessed code is translated to
assembly instructions specific to the target processor architecture. These form an
intermediate human readable language.
3.The third stage is the assembling of the instructions into machine readable format or
object code .
4.The last stage is linking of the missing pieces of the code to get a complete executable
program.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Linking:
It is the process of combining separate pieces of code together to form a single
executable program. The use of linkers allows a single monolithic program to be split into
various modules and developed separately. These modules help in developing reusable
components, error free code, Modular programming, workload management and also
timely completion of very large projects. Individual modules built by various programmers
are individually compiled and then put together by a linker.

Two Types of linking


Static linking
Dynamic linking
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Types of linking:
There are two types of linking, namely static and dynamic linking. In static linking,
all the modules that need to be put together are decided first, then compiled and
then are linked together to form a single object file. The addresses are refined and
external variables are resolved. This is called a static linking.
In dynamic linking, the number of modules to be linked together is not decided
beforehand. The modules are decided during the runtime or execution of the
program. The choice of the modules may depend on the outcome of some
conditional expressions or choice of the user or errors / exceptions that may result
during the course of the program. The modules to be linked with the program are
selected at runtime and the instruction and the variable address resolution happen
at runtime. This is the most efficient way of managing the memory and also to keep
the size of the program a minimum.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Types of Linkers:
● Linkage Editor: It is a linker that generates the relocatable, executable module.
● Dynamic Linker: It defers/postpones the linkage of some external modules until
the load module/executable module is generated. Here, linking is done during
load time or run time.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Loading a Program:
● Once the program is compiled and linked, it is to be loaded into memory for
execution by the operating system. There are different types of loaders.
● Absolute loader: One in which the program is always loaded into the same address
● Relocatable loader: A loader which can relocate the program depending on the
availability of the memory
● Dynamic Run time loader: A loader which would load the module only when it is
called in and not before that.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Comparison of linkers and loaders

BASIS FOR COMPARISON LINKER LOADER

Basic It generates the executable It loads the executable


module of a source program. module to the main memory.

Input It takes as input, the object It takes an executable


code generated by an module generated by a
assembler. linker.

Function It combines all the object It allocates the addresses to


modules of a source code to an executable module in
generate an executable main memory for execution.
module.
Type/Approach Linkage Editor, Dynamic Absolute loading,
linker. Relocatable loading and
Dynamic Run-time loading.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Testing and Debugging:


Testing is defined as the process of finding errors in a program, whereas Debugging is
the process of fixing the errors found during the testing process.
Courtesy:https://www.tutorialspoint.com/difference-between-testing-and-debugging

Sr. No. Key Testing Debugging

1 Definition Technically Testing is a process to check if the On other hand Debugging


application is working the same as it was supposed to is the activity performed
do, and not working as it was not supposed to do. by developers to fix the
bug found in the system.

2 Objective Main objective of Testing is to find bugs and errors in an On other hand the main
application which get missed during the unit testing by objective of Debugging is
Testing Debugging the developer. to find the exact root
Process of verifying whether software meets the requirements and is free of defects or bugs.
Process of identifying, analyzing, and fixing defects or bugs in software after they have been found. cause at code level to fix
Aimed at preventing and catching errors early in the software development life cycle. Aimed at removing errors
after they have been found, often after the software has been released. the errors and bugs found
Typically performed by a dedicated team of testers who use a variety of techniques and tools to test the software.
Typically performed by developers who use specialized tools and techniques to analyze and fix bugs. during the testing.
ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Sr. Key Testing Debugging


No.

3 Perform As Testing is mainly to find out the errors and bugs is While on other hand Debugging is to find
mainly performed by the testers. Also if testing is at the missing or de-faulty code in an
developer end known as unit testing then it is application hence major performance by
performed by the Developer. the developers only.

4 Knowledge As Testing covers the functional and behavioural flow On other hand Debugging is to find the
Required of an application so only functional knowledge is error at code level so technical and code
required for the tester to perform the testing. level knowledge is required for the
developer to perform debugging.

5 Automation Testing can be manual or made automated with the On other hand Debugging can't be
help of different tools. automated, it is always manual.

6 Level Testing on the basis of level of performance is at a On other hand no such level of Debugging
different level i.e., unit testing, integration testing, is possible
system testing, etc.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Documentation
Documentation describes the code and its functionality. It may also have information about the
date of development, the development team, usage, system requirements and pitfalls of the
system.
There are two types of documentation, namely system documentation and User Documentation.
System documentation has information about the various components of the system, like
requirements documents, design decisions, architecture descriptions, program source code, and
FAQs. Process documentation involves description about the tasks carried out in the system, for
example standards, project documentation, such as project plans, test schedules, reports, meeting
notes, or even business correspondence.
User document will help the users understand the various ways in which he or she can interact
with the system, the various menus and reports available in the system and how to exploit them.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

References- Courtesy:

1.https://www.tutorialspoint.com/computer_programming/computer_progr
amming_basics.htm
2.https://www.geeksforgeeks.org/introduction-to-programming-languages/
3.https://www.britannica.com/technology/computer-programming-language
4.https://techdifferences.com/difference-between-linker-and-loader.html
5. https://dzone.com/articles/the-differences-between-testing-and-debugging
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to CSE & IT)

Video Links

Software Testing
https://www.youtube.com/watch?v=GOVEJTzwzFE
Types of Programming Language
https://www.youtube.com/watch?v=aYjGXzktatA
Programming Constructs
https://www.youtube.com/watch?v=eSYeHlwDCNA
Phases of compiler
https://www.youtube.com/watch?v=0jvKnJK0bnA
SUBJECT CODE

TYPE THE SUBJECT NAME HERE

UNIT NO 1
INTRODUCTION TO PROGRAMMING AND
ALGORITHMS FOR PROBLEM SOLVING

1.7 Control Structures - Algorithmic problem


solving - Problems based on sequential
I I

20ESCS101
Problem Solving and Programming in C
(Common to ALL Departments)
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

CONTROL STRUCTURES

Control structures form the basic entities of a “structured programming language“.


❖ Control structures are used to alter the flow of execution of the program.
❖ Control structures are used to make decisions and alter the direction of program flow in one or
the other paths available.
Types of control structures
There are three types of control structures available.
1. Sequence structure (straight line paths)
2. Selection structure (one or many branches)
3. Loop structure (repetition of a set of activities)
1. Sequence structure: A sequence structure is a set of program statements that are executed
sequentially. A simple program can be written using the sequence structure.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

SEQUENCE CONTROL STRUCTURES


20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

SELECTION CONTROL STRUCTURES

2. Selection structures are used to perform ‘decision making‘ and then branch the program flow
based on the outcome of decision making. It is also called as Decision Structures. Selection structures are
implemented with If, If Else and Switch statements. If and If Else statements are 2 way branching statements
where as Switch is a multi branching statement.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

LOOP CONTROL STRUCTURES

3. Loop structure is used to execute a certain set of actions for a predefined number of times or
until a particular condition is satisfied. It is also called as repetition or iteration structures. There are 3 control
statements available to implement loop structure. They are While, Do while and For statements.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

LOOP CONTROL STRUCTURES

3. Loop structure is used to execute a certain set of actions for a predefined number of times or
until a particular condition is satisfied. It is also called as repetition or iteration structures. There are 3 control
statements available to implement loop structure. They are While, Do while and For statements.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

ALGORITHMIC PROBLEM SOLVING

Algorithmic problem solving is solving problem that require the formulation of an algorithm for the
solution.
Understanding the Problem
❖ It is the process of finding the input of the problem that the algorithm solves.
❖ It is very important to specify exactly the set of inputs the algorithm needs to handle.
❖ A correct algorithm is not one that works most of the time, but one that works correctly for all
legitimate inputs.
Ascertaining the Capabilities of the Computational Device
❖ If the instructions are executed one after another, it is called sequential algorithm.
❖ If the instructions are executed concurrently, it is called parallel algorithm.
Choosing between Exact and Approximate Problem Solving
❖ The next principal decision is to choose between solving the problem exactly or solving it
approximately.
❖ Based on this, the algorithms are classified as exact algorithm and approximation algorithm.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

ALGORITHM DESIGN AND ANALYSIS PROCESS


20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Deciding a data structure:


❖ Data structure plays a vital role in designing and analysis the algorithms.
❖ Some of the algorithm design techniques also depend on the structuring data specifying a
problem’s instance
❖ Algorithm + Data structure=programs.
Algorithm Design Techniques
❖ An algorithm design technique (or “strategy” or “paradigm”) is a general approach to solving
problems algorithmically that is applicable to a variety of problems from different areas of
computing.
❖ Learning these techniques is of utmost importance for the following reasons.
❖ First, they provide guidance for designing algorithms for new problems,
❖ Second, algorithms are the cornerstone of computer science
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Methods of Specifying an Algorithm

❖ Pseudocode is a mixture of a natural language and programming language-like constructs.

Pseudocode is usually more precise than natural language, and its usage often yields more

succinct algorithm descriptions.

❖ In the earlier days of computing, the dominant vehicle for specifying algorithms was a flowchart,

a method of expressing an algorithm by a collection of connected geometric shapes containing

descriptions of the algorithm’s steps.

❖ Programming language can be fed into an electronic computer directly. Instead, it needs to be

converted into a computer program written in a particular computer language. We can look at

such a program as yet another way of specifying the algorithm, although it is preferable to

consider it as the algorithm implementation.


20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Proving an Algorithm’s Correctness


❖ Once an algorithm has been specified, you have to prove its correctness. That is, you have to
prove that the algorithm yields a required result for every legitimate input in a finite amount of
time.
❖ A common technique for proving correctness is to use mathematical induction because an
algorithm’s iterations provide a natural sequence of steps needed for such proofs.
❖ It might be worth mentioning that although tracing the algorithm’s performance for a few specific
inputs can be a very worthwhile activity, it cannot prove the algorithm’s correctness conclusively.
But in order to show that an algorithm is incorrect, you need just one instance of its input for
which the algorithm fails.
Analysing an Algorithm
1. Efficiency.
❖ Time efficiency, indicating how fast the algorithm runs,
❖ Space efficiency, indicating how much extra memory it uses.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

2. simplicity.
❖ An algorithm should be precisely defined and investigated with mathematical expressions.
❖ Simpler algorithms are easier to understand and easier to program.
❖ Simple algorithms usually contain fewer bugs.
Coding an Algorithm
❖ Most algorithms are destined to be ultimately implemented as computer programs.
Programming an algorithm presents both a peril and an opportunity.
❖ A working program provides an additional opportunity in allowing an empirical analysis of the
underlying algorithm. Such an analysis is based on timing the program on several inputs and
then analysing the results obtained.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

SEQUENCE CONTROL STRUCTURES

❖ It is one of the three basic logic structures in computer programming.

❖ In a sequence structure, an action, or event, leads to the next ordered action in a predetermined order.

❖ The sequence can contain any number of actions, but no actions can be skipped in the sequence.

❖ The program, when run, must perform each action in order with no possibility of skipping an action or

branching off to another action.

Advantage: There is no separate control statements are needed in order to execute the statements

one after the other.

Disadvantage is that there is no way to change the sequence. The solution for this is branching.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

PROBLEMS BASED ON SEQUENTIAL

1. TO FIND AREA OF RECTANGLE

Step 1: Start

Step 2: Get l,b values

Step 3: Calculate A=l*b

Step 4: Display A

Step 5: Stop
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

PROBLEMS BASED ON SEQUENTIAL


2. TO CALCULATE AREA AND CIRCUMFERENCE OF CIRCLE

Step 1: Start

Step 2: get r value

Step 3: Calculate A=3.14*r*r

Step 4: Calculate C=2*3.14*r

Step 5: Display A,C

Step 6: Stop
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

PROBLEMS BASED ON SEQUENTIAL


3. PROGRAM TO CALCULATE SIMPLE INTEREST

Step 1: Start

Step 2: get P, n, r value

Step 3: Calculate SI=(p*n*r)/100

Step 4: Display S

Step 5: Stop
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

PROBLEMS BASED ON SEQUENTIAL


4. TO CONVERT FAHRENHEIT TO CELSIUS

Step 1: Start.

Step 2: Read F.

Step 3: C=(5(F-32))/9.

Step 4: Print C.

Step 5: Stop.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

PROBLEMS BASED ON SEQUENTIAL


5. TO CALCULATE ENGINEERING CUT OFF

Step 1: Start

Step2: get P,C,M value

Step 3:calculate Cutoff= (P/4+C/4+M/2)

Step 4: Display Cutoff

Step 5: Stop
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

PROBLEMS BASED ON SEQUENTIAL


6. SWAPPING OF TWO NUMBERS WITH TEMPORARY VARIABLE

Step 1 : Start

Start 2 : READ num1, num2

Start 3 : temp = num1

Start 4 : num1 = num2

Start 5 : num2 = temp

Start 6 : PRINT num1, num2

Start 7 : Stop
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

PROBLEMS BASED ON SEQUENTIAL


7. SWAPPING OF TWO NUMBERS WITHOUT TEMPORARY VARIABLE

Step 1 : Start

Start 2 : READ num1, num2

Start 3 : num1 = num1 + num2

Start 4 : num2 = num1 - num2

Start 5 : num1 = num1 - num2

Start 6 : PRINT num1, num2

Start 7 : Stop
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

VIDEO LINK

1. https://www.youtube.com/watch?v=deb5ztpTjYY

1. https://www.youtube.com/watch?v=EcPY7Mg8bjo

1. https://www.youtube.com/watch?v=OoShU65HemA
SUBJECT CODE

TYPE THE SUBJECT NAME HERE

UNIT NO 1
INTRODUCTION TO PROGRAMMING AND
ALGORITHMS FOR PROBLEM SOLVING

1.8 Problems based on Decision Making and


Branching
I I

20ESCS101
Problem Solving and Programming in C
(Common to ALL Departments)
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Introduction
❖ A selection / Decision making statement causes the program control to be transferred to a specific part
of the program based upon the condition.
❖ If the conditional test is true, one part of the program will be executed, otherwise it will execute the other
part of the program.
❖ Decision Making and Branching can be said as Selection/ Conditional /Branching
statements/structures.
❖ They decide the flow of the statements which is based on the evaluation condition.
❖ Decision making is anticipation of conditions occurring while execution of the program and specifying
actions taken according to the conditions.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Introduction

Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.
You need to determine which action to take and which statements to execute if outcome is
TRUE or FALSE otherwise.

Two Major types in branching


1. Two way branching
o IF THEN
o IF…THEN..ELSE
2. Multiway branching
o NESTED IF…ELSE
o IF THEN ELSE LADDER
o SWITCH….CHOICE
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Binary or two-way branching:

• It allows the choice between two possible paths.


• If the condition is met then one path is taken, otherwise the second possible path is followed.
• In each of the given examples, the first case described requires a process to be completed only if the
condition is true.
• The process is ignored if the condition is false.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Two way branching IF THEN
Syntax:

IF condition THEN
sequence 1

If the condition is true, sequence 1 is performed.


Example:
IF mark > 50 THEN
Display pass message
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Two way branching IF…THEN..ELSE
Syntax
IF condition THEN
sequence 1
ELSE
sequence 2
ENDIF

The ELSE keyword and "sequence 2" are optional.

If the condition is true, sequence 1 is performed,


otherwise sequence 2 is performed.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Two way branching IF…THEN..ELSE
Example
IF HoursWorked > NormalMax THEN
Display overtime message
ELSE
Display regular time message
ENDIF

Example
IF THEN ELSE
IF age>= 18 THEN
DISPLAY message “Eligible to vote”
ELSE
DISPLAY message “Not eligible to vote”
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Multiway branching
• It allows for any number of possible choices, or cases.
• The path taken is determined by the selection of the choice which is true.
• Multi-way selection is often referred to as a case structure.
In pseudocode, multiple selection is expressed as:

CASEWHERE expression evaluates to


choice a : process a
choice b : process b . .
..
OTHERWISE : default process
ENDCASE

• As the flowchart version of the multi-way selection indicates, only one process on each pass is executed as
a result of the implementation of the multi-way selection.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Multiway branching`
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Multiway branching : NESTED IF…ELSE
It is used when a series of decisions are involved and have to use more than one if…else statement.
Syntax:

IF(condition 1) THEN
IF (condition 2) THEN
body of if
ELSE
Body of else
ELSE
Body of else
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Multiway branching
Example:
IF ( a>b) THEN
IF (a>c) THEN
DISPLAY message " a is greater"
ELSE
DISPLAY message “ c is greater”
ELSE
IF (b>c) THEN
DISPLAY message “b is greater”
ELSE
DISPLAY message “c is greater”
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Multiway branching : IF THEN ELSE LADDER
• The Structure that contains another structure of the same type is called as Nested Structure.
• In the Nested IF Structure, the statement that exist between IF and ELSE or between IF and END IF can
contain IF statement.
Syntax:
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Multiway branching
Flowchart: Example:
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Multiway branching : SWITCH…CHOICE/CASE
❖ The SWITCH control structure is the substitute for Nested IF structure of many levels of nesting.
❖ It is used to select one of several paths.
❖ It is especially useful when the selection is based on the value of a single variable or a simple expression
(called the case selector).
❖ The case selector may be an integer, character, or boolean variable or expression.
Syntax: Flowchart:
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


Multiway branching : SWITCH…CHOICE/CASE
Example:
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Problems based on Decision Making and Branching


VIDEO LINK:
https://youtu.be/IptxJPWbVu4
SUBJECT CODE

TYPE THE SUBJECT NAME HERE

UNIT NO 1
INTRODUCTION TO PROGRAMMING AND
ALGORITHMS FOR PROBLEM SOLVING

1.9 Problems based on Decision Making and


Iteration
I I

20ESCS101
Problem Solving and Programming in C
(Common to ALL Departments)
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

1.9 Problems based on Decision Making and Iteration


Iterations:

❖Iteration is the repetition part of an algorithm until a condition is met or might repeat for a specified
number of times.
❖The repetition structure is the construction of statement in such a way where statements can be
executed repeatedly until a condition evaluates to true or false.
❖Iteration is also known as looping.
❖For example, a very simple algorithm for eating breakfast cereal might consist of these steps:
1. Put cereal on bowl
2. Add milk to cereal
3. Use spoon to eat cereal and milk
4. Repeat step 3 until all cereal and milk in the bowl is eaten.
5. Rinse the bowl and spoon.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

❖ Iteration may take one of the following forms:


o Repeat actions until a desired condition is met.
o While some condition is met, repeat actions.
o Repeat actions for a fixed number of times.
❖ A very important feature of repetition is that every loop has termination condition to stop the repetition
or the loop will not stop executing, known as Infinite loop.
❖ The termination condition can be checked either at the beginning of the loop known as Pre-test loop
or at the end of the loop is called as post-test loop.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

1.9.1 Pre-tested Loop / Entry tested loop:

❖ This construct is often called a guarded loop.


❖ The body of the loop is executed repeatedly while the termination condition is true.
❖ In pseudocode pre-test repetition is expressed as:
WHILE condition is true

process(es)

ENDWHILE

❖ Flowchart of pre-tested loop is shown


20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

1.9.2 Post-tested Loop / Exit tested Loop:

❖ It executes the body of the loop before testing the termination condition.
❖ This construct is often referred to as an unguarded loop.
❖ The body of the loop is repeatedly executed until the termination condition is true.
❖ In pseudocode, post-test is expressed as:

REPEAT

process

UNTIL condition is true

❖ Flowchart of post-tested loop is shown

❖ An important difference between a pre-test and post-test loop is that the statements of a post-test
loop are executed at least once even if the condition is originally true, whereas the body of the pre-
test loop may never be executed if the termination condition is originally true.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

1.9.3 Types of Iteration / Looping Statements:


❖ There are 3 types of loop statements. They are,
● for
● while
● do-while
1. for Loop:
❖ A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.

Syntax

❖ The syntax of a for loop is −

for(initialization; condition; increment/decrement)

statement(s);

}
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Here is the flow of control in a 'for' loop −

❖ The init step is executed first, and only once. This step allows you to declare and initialize any loop
control variables. You are not required to put a statement here, as long as a semicolon appears.
❖ Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of
the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop.
❖ After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement.
This statement allows you to update any loop control variables. This statement can be left blank, as
long as a semicolon appears after the condition.
❖ The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false, the
'for' loop terminates.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Flow diagram:
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Example- Factorial of a number:

Algorithm: Flowchart:

Step 1: Start.

Step 2: Initialize variables.

Step 3: Check FOR condition.

Step 4: If the condition is true, then go to step 5

otherwise go to step 7.

Step 5: f = f * i.

Step 6: Go to step 3.

Step 7: Print value of factorial.

Step 8: Stop.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

2. while Loop:
❖ A while loop repeatedly executes a target statement as long as a given condition is true.

Syntax
❖ The syntax of a while loop is −

while ( condition)

statement(s);

❖ Here, statement(s) may be a single statement or a block of statements.


❖ The condition may be any expression, and true is any nonzero value.
❖ The loop iterates while the condition is true.
❖ When the condition becomes false, the program control passes to the line immediately following the
loop.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Flow diagram:

❖ Here, the key point to note is that


a while loop might not execute at
all. When the condition is tested
and the result is false, the loop
body will be skipped and the first
statement after the while loop will
be executed.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Example - Print all the integers from -5 to 0:

Algorithm: Flowchart:

Step1: Initialise variable j and assign j=-5

Step2: check while( j <=0 )

Step3: Print current value of j

Step4: increment value of j for next loop

Step5: stop when value of j=0


20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

3. do- while Loop:


❖ Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its
condition at the bottom of the loop.
❖ A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.

Syntax
❖ The syntax of a do...while loop is −

do

statement(s);

} while ( condition );

❖ Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
executes once before the condition is tested.If the condition is true, the flow of control jumps back up to do,
and the statement(s) in the loop executes again. This process repeats until the given condition becomes
false.
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Flow diagram:
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Example - Print all the integers from -5 to 0 :

Algorithm: Flowchart:

Step1: Initialise variable j and assign j=-5

Step2: Print current value of j

Step3: increment value of j for next loop

Step4: check while( j <=0 )

Step5: stop when value of j=0


20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

Nested Loops:
Syntax

The syntax for a nested for loop statement The syntax for a nested while loop statement is
as follows − as follows −

for ( init; condition; increment ) { while(condition) {

for ( init; condition; increment ) { while(condition) {

statement(s); statement(s);

} }

statement(s); statement(s);

} }
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

The syntax for a nested do...while loop statement is as follows −

do {

statement(s);

do {

statement(s);

}while( condition );

}while( condition );
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

More examples on Iteration


Example: find sum of first 100 integers

INITIALIZE SUM to zero

INITIALIZE I to zero

DO WHILE (I <100)

INCREMENT I

ADD I to SUM and store in SUM

END DO WHILE

PRINT SUM

STOP
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

More examples on Iteration


Example: Find Class Average

Set total to zero

Set grade counter to one

While grade counter is less than or equal to ten

Input the next grade

Add the grade into the total

endwhile

Set the class average to the total divided by ten

Print the class average.


20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

More examples on Iteration


Example: Print fibonacci series up to N

Set initial zero to F,F1, one to F2

WRITE F1,F2

F=F1+F2

READ N

WHILE (F<N)

F=F1+F2

F1=F2

F2=F

WRITE F

REPEAt WHILE UNTIL THE CONDITION FAIL

END WHILE
20ESCS101
PROBLEM SOLVING AND PROGRAMMING IN C (Common to All Departments )

video link
https://www.youtube.com/watch?v=nv52OwtCqIU
https://www.youtube.com/watch?v=vOEN65nm4YU

You might also like