Unit-3

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 50

CSE1021- Problem Solving

and Programming
Unit-3
Algorithms

An algorithm is a set of rules that specify the order and kind of


arithmetic operations that are used on a specified set of data.

An algorithm is an effective method expressed as a finite list of well-


defined instructions for calculating a function.

An algorithm is a finite, definite, effective procedure, with some


output

Systematic procedure that produces – in a finite number of steps –


the answer to a question or the solution of a problem.
Essential properties of an algorithm

an algorithm is finite (w.r.t.: set of instructions, use of resources, time of computation)

instructions are precise and computable

• instructions have a specified logical order, however, we can discriminate between

deterministic algorithms (every step has a well-defined successor)

non-deterministic algorithms (randomized algorithms, e.g.)


Basic Questions About Algorithms
For each algorithm, we should answer the following basic questions:

• does it terminate?
• is it correct?
• is the result of the algorithm
determined?
• how much resources will it use in
terms of
• memory? (and memory bandwidth?)
• operations?
• run-time
Swapping Two Numbers Using Variable

• In many case, programmers are required to swap values of two variables. Here, we
shall learn how to swap values of two integer variables, that may lead to swapping of
values of any type. Values between variables can be swapped in two ways −

With help of a third (temp) variable

Without using any temporary variable


Swapping Two Numbers Using Variable
With help of a third (temp) variable
Logic:
• Suppose we take two values in a and b, a=10, b=20 respectively.
• temp=a;
• a=b;
• b=temp;
• After the operation of this statement, the value of two variable
a and b will be interchanged.
• Output:
• A=20, B=10;
Algorithm:
• Using the temporary variable

Step 1: Start

Step 2: Take the value of variables a and b.

Step 3: Assign the value of variable a into the temp variable.

Step 4: Assign the value of variable b into a variable.

Step 5: Assign the value of variable temp into the b variable.

Step 6: Print the value of a and b.

Step 7: Stop
Pseudocode

• Using the temporary variable


Flow Chart
Python Program
Swapping Two Numbers without Using
Variable
• Here we will use arithmetic operator (+, -). We
use addition and subtraction operation on these
variables.
• a=a+b;
• b=a-b;
• a=a-b;
Algorithm:
• Without Using the temporary variable

Step 1: Start

Step 2: Take the value of variables a and b.

Step 3: Add the values of the a and b and assign it to the variable a.

Step 4: Subtract the values of a and b and assign it to the variable b. (Here the
value of a is changed due to the step 3).

Step 5: Subtract the values of a and b and assign it to the variable a.

Step 6: Print the value of a and b.

Step 7: Stop
Pseudocode

• Without Using the temporary variable


Flow Chart
Python Program
Without using third variable and without
using arithmetic operator
• Here we will use the Exclusive OR bit-wise
operator.
• Logic:
• a=a^b;
• b=a^b;
• a=a^b;
Algorithm:
• Without Using the temporary variable

Step 1: Start

Step 2: Take the value of variables a and b.

Step 3: Operate Exclusive OR operation on variable a and b and assign the


exclusive OR output in a variable. (Here value of a is changed)
Step 4: Operate Exclusive OR operation on variable a and b and assign the
exclusive OR output in b variable. (Here value of b is changed)
Step 5: Operate Exclusive OR operation on variable a and b and assign the
exclusive OR output in a variable. (Here value of a is again changed)

Step 6: Print the value of a and b.

Step 7: Stop
Python Program
Program to count digits in an integer
• The integer entered by the user is stored in variable n. Then the while
loop is iterated until the test expression n != 0 is evaluated to 0 (false).
• After first iteration, the value of n will be 345 and the count is
incremented to 1.
• After second iteration, the value of n will be 34 and the count is
incremented to 2.
• After third iteration, the value of n will be 3 and the count is
incremented to 3.
• At the start of fourth iteration, the value of n will be 0 and the loop is
terminated.
Program to count digits in an integer
• Method 1
Program to count digits in an integer
• Method 2
Program to count digits in an integer
• Method 3
Program to count digits in an integer
• Method 4
Algorithm: calculate the sum and average of first n
natural numbers
Python Program to calculate the Sum
Python Program to calculate average
Calculate the sum and average of first n natural
numbers using formula
Calculate the sum and average of first n natural
numbers using formula
Calculate the sum and average of multiple user-
entered numbers
Calculate the sum and average of multiple user-
entered numbers
Calculate the sum and average of multiple user-
entered numbers
Calculate sum using the built-in sum function in
Python
Sum of numbers in the list is required everywhere. Python provide an inbuilt function
sum() which sums up the numbers in the list
sum() function in Python
sum() function in Python
Practical Application: Problems where we require sum to
be calculated to do further operations such as finding out the
average of numbers.
Factorial Computation
Algorithm to calculate factorial value of a number

• step 1. Start
step 2. Read the number n
step 3. [Initialize]
i=1, fact=1
step 4. Repeat step 4 through 6 until i=n
step 5. fact=fact*i
step 6. i=i+1
step 7. Print fact
step 8. Stop
Fibonacci Sequence
Algorithm to print Fibonacci series up to given
number N

Step 1: Start
• Step 2: Declare variables N, N1, N2, N3, i.
• Step 3: Read value of N from user.
• Step 4: if N < 2, display message “Enter number > 2” and go to step 9.
• Step 5: Initialize variables N1 = 0, N2 = 1, i = 0
• Step 6: Display N1, N2
• Step 7: Compute N3 = N1 + N2
• Step 8: Repeat following statements until i < N - 2
Display N3
N1 = N2
N2 = N3
N3 = N1 + N2
i =i+1
• Step 9: Stop
Reverse a Number
Algorithm to Reverse a Number
• Step 1:Start
• Step 2:Intilize reverse=0
• Step 3:Read digit
• Step 4:check whether digit>0 then go to step 5 else go to step 9
• Step 5:reverse=reverse*10
• Step 6:reverse=reverse+digit%10
• Step 7:digit=digit/10
• Step 8: Go to step 4
• Step 9:Print reverse
• Step 10: Stop
Base Conversion
• Decimal to Any Base
• Decimal to Octal
• Decimal to Binary
• Decimal to Hexadecimal
• Binary to Any Base
• Octal to any base
• Hexadecimal to any base
The Basic Idea
• The basic algorithm for this conversion is to repeatedly divide
(integer division) the given decimal number by the target
base value until the decimal number becomes 0.
• The remainder in each case forms the digits of the number in
the new base system, however, in the reverse order.
An Upper Limit
• The algorithm, in general, will work for any base, but we need
digits/characters to represent that many numbers of a base system.
• For simplicity, we limit ourselves to base 36 i.e 10 numbers + 26
alphabets.
• (We can differentiate lower and upper case, but we intend to focus on the
algorithm here!).
• It will be clear after the implementation that the method has to work
for any base.
Decimal to Basex
1.Divide the decimal number by the radix of the target
base
2.The remainder from step 1 becomes the value for the
current column.
3.Use the quotient (answer) from step 1 as the decimal
value to calculate the next column.
4.Return to step 1 and repeat until the quotient is zero.
Let's return to the number 237 and convert it to a binary number:

Example – Decimal to Binary


decimal: 237
radix: 2
Decimal Radix Quotient Remainder
237 / 2 118 1 (20)
118 / 2 59 0 (21)
59 / 2 29 1 (22)
29 / 2 14 1 (23)
14 / 2 7 0 (24)
7 / 2 3 1 (25)
3 / 2 1 1 (26)
1 / 2 0 1 (27)
binary: 11101101
Example – Decimal to Hexadecimal
decimal: 3,134,243,038
radix: 16
Decimal Radix Quotient Remainder

3,134,243,038 / 16 195,890,189 E (14) (160)

195,890,189 / 16 12,243,136 D (13) (161)


12,243,136 / 16 765,196 0 ( 0) (162)
765,196 / 16 47,824 C (12) (163)
47,824 / 16 2,989 0 ( 0) (164)
2,989 / 16 186 D (13) (165)
186 / 16 11 A (10) (166)
11 / 16 0 B (11) (167)
hexadecimal: xBAD0C0DE
Decimal to Any Base – Python
Implementation
def dec_to_base(num,base): #Maximum base - 36
base_num = ""
while num>0:
dig = int(num%base)
if dig<10:
base_num += str(dig)
else:
base_num += chr(ord('A')+dig-10) #Using uppercase letters
num //= base
base_num = base_num[::-1] #To reverse the string
return base_num
Basex to Decimal
• Actually, I have already demonstrated how to convert a number from
a base different than ten, into decimal. Once again, here is the
complete formula, where cx represents the coefficients at each place-
column.
cn·bn + ... + c2·b2 + c1·b1 + c0·b0
As an example, let's convert the binary answer back into decimal:

1·27 + 1·26 + 1·25 + 0·24 + 1·23 + 1·22 + 0·21 + 1·20


1·128 + 1·64 + 1·32 + 0·16 + 1·8 + 1·4 + 0·2 + 1·1
128 + 64 + 32 + 8 + 4 + 1
237
Basex to Basey
• Is it possible to convert a number from Basex directly to
Basey without converting to decimal (base-10) first?
• Yes, however, you will need to perform all of your math
operations in either Basex or Basey. The algorithms that
I have presented are performed with base-10 since that
is the number system most people are familiar with.

You might also like