2.Fundamental Algorithms
2.Fundamental Algorithms
Chapter 2
2.1: Exchanging the Values of Two Variables
● Problem: Given two variables a and b, exchange the values assigned to them.
● Algorithm:
1. Save the original value of a in t.
2. Assign to a the original value of b.
3. Assign to b the original value of a that is stored in t.
● Applications: Sorting algorithms.
● Solve: Given two variables a and b, exchange their values without using a third
temporary variable.
2.2: Counting
● Problem: Given a set of students’ examination marks (in the range 0 to 100) make a
count of the number of students that passed the examination. A pass is awarded for
all marks of 50 and above.
● setofmarks = [35,60,55,45,79,37,68]
totalstds = len(setofmarks)
passmarks = 50
passcount = 0
● for i in setofmarks:
if i >= passmarks:
passcount = passcount+1
print("the number of students passed are : ",passcount)
2.2: Counting
● Algorithm:
● 1. Read the number of marks to be processed.
● 2. Initialize count to zero.
● 3. While there are still marks to be processed repeatedly do
○ (a) read next mark
○ (b) if it is a pass (i.e. ≥ 50) then add one to count.
● 4. Write out the total number of passes.
● Applications: All forms of counting.
● Solve: Design an algorithm that reads a list of numbers and makes a count of the
number of negatives and the number of non-negatives in the set.
2.3: Summation of a Set of Numbers
● Problem: Given a set of n numbers design an algorithm that adds these numbers and
returns the resultant sum. Assume n is greater than or equal to zero.
● numlist[] = array of numbers to be summed
n = length of numlist
sum = 0 (the total sum of numbers in numlist)
● for i from 0 to n-1:
sum = sum + numlist[i]
● print sum
2.3: Summation of a Set of Numbers
● Algorithm:
● 1. Read in the number of numbers to be summed.
● 2. Initialize sum for zero numbers.
● 3. While less than n numbers have been summed repeatedly do
○ (a) read in next number
○ (b) compute current sum by adding the number read to the most recent sum.
● 4. Write out sum of n numbers.
● Applications: Average, variance calculations.
● Solve: Design an algorithm to compute the average of n numbers.
2.4: Factorial Computation
● Problem: Given a number n, compute n! where n ≥ 0
● n! = 1*2*3* … * (n-1) * n for n ≥1
● By definition 0! = 1
● fact = 1
● for i=0 or i=1 fact = 1
● for i in range(2,n+1)
● fact = fact * i
● print(fact)
2.4: Factorial Computation
● Algorithm
● 1. Establish n ≥ 0, the factorial required.
● 2. Set product p for 0! Also set product count to 0.
● 3. While less than n products have been calculated repeatedly do
○ Increment product count
○ Compute ith product p by multiplying i by the most recent product.
● 4. Return the result n!
● Applications: Probability and statistical computations.
2.5: Sine Function Computation
● Problem: Design an algorithm to evaluate the function sin(x) as defined by the
infinite series expansion
● Step1: Evaluate
● Step2: Do the respective additions and subtractions
● Step3: determine the terminating condition
● The ith term and summation which can be generated iteratively from their
predecessors are
● Problem: Generate and print the first n terms of the Fibonacci sequence where n ≥1.
● Fibonacci sequence: 0,1,1,2,3,5,8,13,…
● new term = preceding term + term before preceding term
● Initialization : a = 0, b = 1
● while i < n:
i=i+1
c= a+b
a=b
b=c
● Can this be improved?
2.6 Generation of the Fibonacci Sequence
● Initialization : a = 0, b = 1, i = 2
● while i < n:
a = a+b
b = a+b
i=i+2
● See complete algorithm in the book.
● To generate n Fibonacci numbers n steps are required.
● An algorithm that generates n Fibonacci numbers more efficiently will be studied
later.
2.7 Reversing the Digits of an Integer
● Problem: Design an algorithm that accepts a positive integer and reverses the order of its
digits.
● Example – input:12345, output:54321
● Extract the right most digit by applying mod 10.
○ r = n % 10 = 12345 % 10 = 5
● Reduce the number by doing integer division by 10.
○ n = n div 10 = 1234.
● How to make ‘4’ follow ‘5’ after extraction.
○ rev = 5 * 10 + 4 = 54 (2 digits have been reversed)
○ rev is initialized to 0 initially
● Digit extraction and reversal can be done iteratively.
● When to stop?
○ When the outcome of the integer division is 0
2.7 Reversing the Digits of an Integer
● Input : n, output: revn
● Set revn = 0
● While (n>0)
● x = n % 10
● revn = revn*10 + x
● n = int(n/10)
2.8 Base Conversion
● Problem: Convert a decimal integer to its corresponding octal representation.
● Input: n = decimal integer, output: q = octal representation of n, ndigit = digit count,
nbase = new base to be converted to.
● Divide n by nbase, save the remainder in q
● Update n as the new quotient after the integer division.
● Convert r to appropriate ascii value.
● Increment ndigit and repeat the steps until the quotient is 0.
2.9 Character to Number Conversion
● Problem: Given the character representation of an integer convert it to its
conventional decimal format.
● Textual information is usually represented using upper and lower case characters, the
ten digits, punctuation and control characters.
● Totaling about 100 different characters.
● Thus we may need 7 or 8 bits to store all different characters.
● The fundamental unit or computer word size for storing numbers is usually:
16,32,36,60,64 bits.
● In a 32-bit computer, four 8-bit characters are usually stored in a computer word.
2.9 Character to Number Conversion
● ASCII (American Standard Code for Information Interchange)
● Each character is assigned a fixed 8-bit ASCII code.
● Consider the date : 23 April 1945
● We cannot do the arithmetic operations directly on the character code representations
because the corresponding binary representation does not conform to the standard
binary positional notation used to represent numbers in the computer.
● Convert the number from its character representation to its conventional number
internal representation.
2.9 Character to Number Conversion
● 1 -> 49, 9 -> 57, 4 -> 52, 5 -> 53
● Functions like ord() in pascal, ascii() in Python: accept 8-bit character as argument
and return the ascii value.
● Example: ord(‘9’) = 57
● How to get the decimal digit 9?
● Input: s - character representation of the integer, Output: n - the integer
● Initialise base0 = ord(‘0’)
● for i in (1,n)
n = n * 10 + ord(s[i]) – base0