0% found this document useful (0 votes)
32 views24 pages

ALGORITHM DESIGN - Clive

Uploaded by

eschosysbifmet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views24 pages

ALGORITHM DESIGN - Clive

Uploaded by

eschosysbifmet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

ALGORITHM DESIGN

1.1 Algorithm
a) Definition
An algorithm is a collection of well defined instructions, designed to solve a problem. Algorithms are only as
good as the instructions given, however, and the result will be incorrect if the algorithm is not properly defined or An
algorithm is a finite sequence of instructions, an explicit, step-by-step procedure for solving a problem.
A common example of an algorithm would be instructions for assembling a model airplane. Given the starting set of
a number of marked pieces, one can follow the instructions given to result in a predictable end-state: the completed
airplane. Misprints in the instructions, or a failure to properly follow a step will result in a faulty end product.

b) Characteristics of a good Algorithm


A good algorithm has five characteristics.
1. Input
A good algorithm must have an input. With out an input, an algorithm will be solving a problem with
nothing which is not possible.
2. Output
A good algorithm should produce some results based on its input. The output should be the solution of the
problem it was designed to solve.
3. Definiteness
The instructions should be precise and void of any ambiguities.
4. Effectiveness
The algorithm should be able to solve the problem for which it was designed without wasting system
resources such as processor time and memory.
5. Termination
The algorithm should eventually terminate so that output can collected and effectiveness measured. If the
algorithm is intentionally designed to run continually then it must have a way to permit output to be
collected

2.0 PRESENTATION OF ALGORITHMS


Algorithm can be written in so many ways ranging form ordinary English language to complex high level
language. Generally, algorithms are written using the following standard methods.

2.1 Structured English: The English language can be used to write algorithms. The good thing with this
approach is that, the algorithms are easily understood by humans but unfortunately, not understood by the computer.
Below is an example of algorithm to find the average of a set of numbers.

I. Get two numbers 2. Set count to zero


Find the sum of the numbers 3. Get number
Find the difference between the numbers 4. Set sum = sum + number
Display the sum 5. Set count = count +1
Display the difference. 6. If more numbers go back to step 3
otherwise go to step 7
II. 7. Average = sum/average
1. Set sum to zero 8. Print Average.
It is very difficult to write algorithms using English because the language is full of ambiguity.

Compiled by Sir Clive Ayumbi; [email protected] 675207337 1


2.2 Structured Diagram Or Flow Chart
An example of a structured diagram is a flow chart. The flow chart symbols can be used
to write algorithms. The above algorithm can be written using a flow chart as shown
below.

Flow Chart: A flowchart is a graphical representation of a sequence of steps in an algorithm. In flow charts, symbols are used to
represent activities while arrows are used to represent the direction of activity through the processes. Typical examples of these
symbol include:

2. Process
1. Terminator
Terminator: The oval shape marks the Process: The rectangle represents
start or end point of a system or task. It a single action or step in an
usually contains “start” or “end” algorithm

3. Decision 4. Input/Output
Decision: The diamond Input/Output: The parallelogram
represents a decision or represents the information entering
branching point (eg If – Else) or leaving the system, eg customer
order (Input) or product (Output)
Start

Sausage or Connector: The circle is


Sum =0 5. Sausage or Connector used to denote a process performed
Count = 0
on data such as calculation, sorting.

Merge: The triangle indicates a step


Get N where two or more sub-process
7. Merge
become one

Sum = Sum + N
Count = Count + 1

6. Flow Lines
Are they Yes
Flow Lines: The arrow indicates a sequence of
more N?
steps and the direction of floe

No
Average = Sum/Count End

2.3 Pseudo code

Compiled by Sir Clive Ayumbi; [email protected] 675207337 2


Pseudo code uses English like words. It is very close to a high level language. The algorithm below is the
equivalent of the one above.
Sum, Count , N: integer
Start
Sum = 0
Count = 0
Repeat
Read N
Sum = sum + N
count = count + 1
Until no more N
Average = sum /count
End
2.4 Basic Algorithmic Constructs
Three types of constructs can be used to design a good algorithm. These are Sequence, Selection (or Choice),
iteration recursion.
a) Sequence Construct or Sequential Construct
This is a group of instructions that can only be executed in the order in which they are specified without
skipping any.
ACTIVITY 1 ACTIVITY 2 ACTIVITY 3

Examples
Begin
Writeln(“ This is Cameroon”)
Writeln(“ I love very much”)
Writeln(“ What about you?”)
End.
b) Selection Construct or Conditional construct or Choice construct
This is a group of instructions designed in such a way as to permit the computer to make choice. The choice is
based on a condition. The computer is generally given two choices to make. One for a true, and the other for a
false condition. Examples include If-Then-Else, Case and GoTo statements.
If-Then-Else Statement
Activity 1

True Condition False


Activity 2 Activity 3

Begin
If x < 10 Then
Compiled by Sir Clive Ayumbi; [email protected] 675207337 3
Writeln(“ Passed”)
Else
Writeln(“Failed”)
End

c) Iteration and Recursion


Iteration: These constructs are to perform repetition of some instructions. Examples include: Repeat until, Do until,
Do While, For, and While statements. This is a program structures that allow the block of statements to be performed
again and again during program execution. This repeated execution of the same instructions is often called looping.

A loop: is a sequence of statements which is specified once but which may be carried out several times in succession. The
code "inside" the loop is obeyed a specified number of times, or once for each of a collection of items, or until some
condition is met. In a flowchart a back arrow hints the presence of a loop.

A loop is represented by the while, for, repeat constructs in most programming languages. A loop can be bounded or
unbounded.

Unbounded loops refer to those whose number of iterations depends on the eventuality that the termination condition is
satisfied.

Bounded loops refer to those whose number of iterations is known before-hand.

A trip around the loop is known as iteration.

You must ensure that the condition for the termination of the looping must be satisfied after some finite number of
iterations, otherwise it ends up as an infinite loop. They are used in the following: ways.

While (Condition) do Repeat Repeat For (condition) do

Statement1 Statements Statements Statements

Statement
We express 2
the above Until (Condition)
examples iteratively While (Condition)

1. The factorial function

Factorial(n)

Get the positive integer n.

factorial := 1; {initialize running product variable}

for i := 1 to n do

begin

factorial := factorial * n;

i = i+1

end;

Compiled by Sir Clive Ayumbi; [email protected] 675207337 4


display “factorial”

2. The sum function

Consider the following example for calculating the summation, which we will denote as sum(n), meaning n + n-1 + n-2 +
n-3 + ... + 2 + 1 + 0. Hence, sum(5) = 5+4+3+2+1+0 = 15. Now we will write psuedo-code to calculate the sum(n) using
Iteration.

sum(n) while i is not greater than n, end

begin begin return total;

i = 0; total = total + i; begin

total = 0; i = i + 1;
Recursion: In simple terms recursion is when a function calls itself. That is, in the course of the function definition
there is a call to that very same function.

When writing recursive function we make clear the following criteria

 Establish a base case which can be solved. (recursion ends here)


 Write down the general case which should make the problem smaller and approach the base case by looping.

Examples of recursive functions

1. The factorial function:

Function definition:

Function factorial(n)

Get the positive integer n

If n = 0 then the answer is 1

else evaluate n * factorial(n-1);

2. The sum function

The sum function which sums the integer from 1 to n, where n is to be given.

Compiled by Sir Clive Ayumbi; [email protected] 675207337 5


Now let sum(n) be the sum of all integers from 0 to n.

Function sum(n)

Get a positive integer.

if n is equal to 0, then return(0);

else, return (n + sum(n - 1));

3. The Fibonacci sequence


The Fibonacci function displays the elements in the sequence.

The sequence is 0, 1, 1, 2, 3, 5, 8, 13, …

We write it as F1, F2, F3, F4, F5, F6, F7, F8…

See that F1 = 0, F2=1 Base case

F3 = F2 +F1

F4 = F3 + F2

F5 = F4 + F3

Generally Fn = Fn-1 +Fn-2

Exercise: write a recursive function to generate the elements in the Fibonacci sequence.

3.0 Some Standard Algorithms


3.1 Types of Algorithms
There is no universally accepted breakdown for the various types of algorithms however, there are common classes
that algorithms are frequently agreed to belong to. Among these are:
a) Dynamic Programming Algorithms:
This class remembers older results and attempts to use this to speed the process of finding new results.
b) Greedy Algorithms:
Greedy algorithms attempt not only to find a solution, but to find the ideal solution to any given problem.
c) Brute Force Algorithms:
The brute force approach starts at some random point and iterates through every possibility until it finds the
solution.
d) Randomized Algorithms:
This class includes any algorithm that uses a random number at any point during its process.
e) Branch and Bound Algorithms:
Branch and bound algorithms form a tree of sub-problems to the primary problem, following each branch
until it is either solved or lumped in with another branch.
f) Simple Recursive Algorithms:
This type of algorithm goes for a direct solution immediately, then backtracks to find a simpler solution.
g) Backtracking Algorithms:
Backtracking algorithms test for a solution, if one is found the algorithm has solved, if not it recurs once and
tests again, continuing until a solution is found.
h) Divide and Conquer Algorithms:
Compiled by Sir Clive Ayumbi; [email protected] 675207337 6
A divide-and-conquer algorithm is similar to a branch and bound algorithm, except it uses the backtracking
method of recurring and dividing a problem into sub problems.
3.2 Examples of standard algorithms
3.2.1) Sorting Algorithms
A sorting algorithm is an algorithm that puts elements of a list in a certain order. A sort algorithm as the
name goes, sorts an unsorted array of elements. Sorting is to rearrange a set of items such that their keys are
ordered according to some well defined ordering rule usually on numerical and alphabetical. If the file to be
sorted can fit in to the main memory, then the sorting method is known as internal. Sorting files that are sorted
in external storage is called external sorting.

Elementary sorting methods


A) Insertion Sort
If the first few objects are already sorted, an unsorted object can be inserted in the sorted set in proper
place. This is called insertion sort. The algorithm consider the elements one at a time, inserting each in its
suitable place among those already considered (keeping them sorted). In insertion sort, we consider the
elements one at a time inserting each into its proper place among those already considered (keeping them
sorted). We make space for the element being inserted by moving larger elements one place to the right.
Structure English version of an Insertion Sort Algorithm:
It works the way you might sort a hand of playing cards:
1. We start with an empty left hand [sorted array] and the cards face down on the table [unsorted array].
2. Then remove one card [key] at a time from the table [unsorted array], and insert it into the correct position
in the left hand [sorted array].
3. To find the correct position for the card, we compare it with each of the cards already in the hand, from
right to left.
Note:
At all times, the cards held in the left hand are sorted, and these cards were originally
the top cards of the pile on the table.

Pseudo code of an Insert Sort Algorithm


It uses a procedure that takes an array of length n as parameter. The array A is sorted in place. That is, the
numbers are rearranged within the array with at most a constant number outside the array at any time.

INSERTION_SORT (A)
Begin
For j ← 2 To length[A] Do
Key ← A[j]
Begin
Put A[j] into the sorted sequence A[1 . . j − 1]
End
i←j−1
While i > 0 and A[i] > key Do
A[i +1] ← A[i]
i←i−1
A[i + 1] ← key
End

Compiled by Sir Clive Ayumbi; [email protected] 675207337 7


Example 2:
How to sort the numbers below using Insertion sort algorithm. Array A = (5, 2, 4, 6,
1, 3)
Solution

The figure above shows the operation of INSERTION-SORT on the array A= (5, 2, 4, 6, 1, 3). Each
part shows what happens for a particular iteration with the value of j indicated. j indexes the "current
card" (or number) being inserted into the “hand”( or left side of the array). Elements to the left of A[j]
that are greater than A[j] move one position to the right, and A[j] moves into the evacuated position.

Example 2: Using insertion sort, sort the word ASORTINGEXAMPLE in ascending order.

A S O R T I N G E X A M P L E
A S O R T I N G E X A M P L E
A O S R T I N G E X A M P L E
A O R S T I N G E X A M P L E
A O R S T I N G E X A M P L E
A I O R S T N G E X A M P L E
A I N O R S T G E X A M P L E
A G I N O R S T E X A M P L E
A E G I N O R S T X A M P L E
A E G I N O R S T X A M P L E
A A E G I N O R S T X M P L E
A A E G I M N O R S T X P L E
A A E G I M N O P R S T X L E
A A E G I L M N O P R S T X E

Compiled by Sir Clive Ayumbi; [email protected] 675207337


8
A A E E G I L M N O P R S T X
A A E E G I L M N O P R S T X

B) Bubble Sort
Bubble Sort is an elementary sorting algorithm. It works by repeatedly exchanging adjacent
elements, if necessary. When no exchanges are required, the file (or array) is sorted. In bubble sort,
we keep passing through the file, exchanging adjacent elements that are out of order, continuing until
the file is sorted. Bubble sort is slower than insertion sort and selection sort. When the minimum
element is encountered during the first pass, we exchange it with each of the elements to its left,
eventually putting it at the leftmost position.
Pseudocode for a Bubble Sort Algorithm
Begin
For i ← 1 to length [A] Do
For j ← length [A] down to i +1 Do
If A[A] < A[j-1] Then
Exchange A[j] ↔ A[j-1]
End

Compiled by Sir Clive Ayumbi; [email protected] 675207337


9
Example 1:
Sort the Array A= (5, 2, 4, 6, 1, 3) given above using the Bubble Sort Algorithm.
Solution

5 2 4 6 1 3 2 5 4 6 1 3

2 4 5 6 1 3 2 4 5 1 6 3

2 4 1 5 6 3 2 1 4 5 6 3

1 2 4 5 6 3 1 2 4 5 3 6

1 2 4 3 5 6 1 2 3 4 5 6

From the figure notice how the elements are interchange as one moves from left to
right and top to down.

Example 2: Using bubble sort, sort the word ASORTINGEXAMPLE in ascending order.

A S O R T I N G E X A M P L E
A O S R T I N G E X A M P L E

A O R S T I N G E X A M P L E
A O R S T I N G E X A M P L E

A O R S I T N G E X A M P L E

A O R I S T N G E X A M P L E
A O I R S T N G E X A M P L E
A I O R S T N G E X A M P L E
A I O R S N T G E X A M P L E
A I O R N S T G E X A M P L E
A I O N R S T G E X A M P L E
A I N O R S T G E X A M P L E
A I N O R S G T E X A M P L E
A I N O R G S T E X A M P L E
A I N O G R S T E X A M P L E

Compiled by Sir Clive Ayumbi; [email protected] 675207337


10
A I N G O R S T E X A M P L E
A I G N O R S T E X A M P L E
A G I N O R S T E X A M P L E
A G I N O R S E T X A M P L E
A G I N O R E S T X A M P L E
A G I N O E R S T X A M P L E
A G I N E O R S T X A M P L E
A G I E N O R S T X A M P L E
A G E I N O R S T X A M P L E
A E G I N O R S T X A M P L E
A E G I N O R S T A X M P L E
A E G I N O R S A T X M P L E
A E G I N O R A S T X M P L E
A E G I N O A R S T X M P L E
A E G I N A O R S T X M P L E
A E G I A N O R S T X M P L E
A E G A I N O R S T X M P L E
A E A G I N O R S T X M P L E
A A E G I N O R S T X M P L E
A A E G I N O R S T M X P L E
A A E G I N O R S M T X P L E
A A E G I N O R M S T X P L E
A A E G I N O M R S T X P L E
A A E G I N M O R S T X P L E
A A E G I N M O R S T P X L E
A A E G I N M O R S P T X L E
A A E G I N M O R P S T X L E
A A E G I N M O P R S T X L E
A A E G I N M O P R S T L X E
A A E G I N M O P R S L T X E
A A E G I N M O P R L S T X E
A A E G I N M O P L R S T X E
A A E G I N M O L P R S T X E
A A E G I N M L O P R S T X E
A A E G I N L M O P R S T X E

Compiled by Sir Clive Ayumbi; [email protected] 675207337


11
A A E G I L N M O P R S T X E
A A E G I L N M O P R S T E X
A A E G I L N M O P R S T E X
A A E G I L N M O P R S E T X
A A E G I L N M O P R E S T X
A A E G I L N M O P E R S T X
A A E G I L N M O E P R S T X
A A E G I L N M E O P R S T X
A A E G I L N E M O P R S T X
C) Selection sort: In
A A E G I L E N M O P R S T X
selection sort we find the smallest
element in the A A E G I E L N M O P R S T X list and exchange
it with the first A A E G E I L N M O P R S T X element, then
find the second A A E E G I L N M O P R S T X
smallest element
and exchange it with the second
element and the process continuous. This is an elementary sort method of choice for files with huge items and
small keys, because for such applications, the cost of moving data dominates the cost of making comparisons,
and selection sort involves substantially less data movement than other algorithms.

Example 1 : Using selection sort, sort the word ASORTINGEXAMPLE in ascending order.

A S O R T I N G E X A M P L E

A S O R T I N G E X A M P L E
A A O R T I N G E X S M P L E

A A E R T I N G O X S M P L E
A A E E T I N G O X S M P L R
A A E E G I N T O X S M P L R
A A E E G I N T O X S M P L R

A A E E G I L T O X S M P N R
A A E E G I L M O X S T P N R

A A E E G I L M N X S T P O R
A A E E G I L M N O S T P X R
A A E E G I L M N O P T S X R
A A E E G I L M N O P R S X T
A A E E G I L M N O P R S X T
A A E E G I L M N O P R S T X
A A E E G I L M N O P R S T X

Compiled by Sir Clive Ayumbi; [email protected] 675207337


12
3.2.2 Searching Algorithms
These are algorithms used in search for the present of some specific data in a file. An example is the
sequential search algorithm wherein the target data is search sequentially, that is, line by line through
entries of the array without skipping. When the data is found, the algorithm returns True otherwise it
returns False.
Pseudocode: Sequential Search
SEARCH(x, [A])
SEARCH ←False
For i ← 1 to length [A] Do
If A[i] = x Then
SEARCH ← True
Else
SEARCH ← False
Sequential search algorithm: To over the limitation to wasted memory for large key values, an
alternative approach is to store the items in an array contiguously. This approach presents two alternatives as
to how items are added to the array. The first is to ensure that we insert new items in their correct positions
and then shift all larger items one position backwards so that the array is always sorted. The second approach
is to add all new items to the end of the array.
Binary search algorithm: Binary search algorithm is a very efficient and widely used search
algorithm that is applied to a sorted list. The algorithm uses the divide and conquer approach, that is the
algorithm begins by dividing the list into two parts and a determination is made if the key if present would be
on the first or the second half. The section of the list that can not contain the key is then discarded, and the
section that the algorithm concentrates on the part that may contain the key.
An algorithm for binary search is given as:
Get the lower and upper bounds of a sorted list that is first and last
While last > first
Compute middle of list (mid)
If mid < searched item that is search item may only be on right of list then
First = mid + 1 ( new lower bound)
Else search item may only be on left of list
Last = mid – 1
If last point to search item, search is successful otherwise, it is not.
Hashing: A process of identifying the address of a record in a character string. When the number of keys
actually stored is small relative to the total number of possible keys, hash tables become an effective
alternative to directly addressing an array, since hash tables typically use an array size proportional to the
number of distinct keys actually stored. Search algorithms that use hashing consist of two separate parts. The
first part computes a hash function that transforms the search key into a table address. If h is the hash
function we say that an element with key k hashes to slot h(k); we also say that h(k) is the hash value of key
k.
Hash function: This is a simple arithmetic operation that transforms keys into table addresses. If an
array has a size m, the hash function transforms key into integers in the range
4.0 Algorithms Development Techniques

Compiled by Sir Clive Ayumbi; [email protected] 675207337


13
The following techniques are used in developing good algorithms.
4.1 Divide and Conquer Technique.
In this technique, the bigger problem is divided into smaller sub problems of the same type,
which are easier to solve and solve these sub problems recursively. At the end, combine the
solutions to the sub problems into a solution to the original problem.

4.2 Incremental Technique.


Using this technique, a complicated algorithm of n instructions by first building the n-1
instructions and then making the necessary changes to fix things in adding the last
instruction.

5.0 Algorithms for parallel tasks


A parallel algorithm is a set of Algorithms that are able to work cooperatively to solve a
common problem. For these algorithms to effectively solve the problem they must work
conflicting with each other.

5.1 Concepts associated with parallel Algorithms


a) Concurrency
If two or more algorithms run simultaneously and solve a common problem without a
destructive interference from each then they said to be in concurrency.

b) Deadlock
When two algorithms are in a deadlock, if they cannot continue their execution. This
happens when the resource needed by one to complete execution, is needed also by another
with the same priority.

c) Lovelock
Lovelock is a situation in which two algorithms enter an infinite loop because they keep on
exchanging resources. This usually happens when the output of algorithm A serves as input
for algorithm B and vice visa.
6.0 Testing, Evaluation and Analysis of algorithms
After an algorithm is written or designed it must be tested to ensure correctness.
6.1 Testing
Testing an algorithm is done by first performing a dry run. That is running the mentally. If it
runs mentally without any error, then it can now be tested with some sample data in a real
system. An algorithm that runs successfully to the end does not mean it is correct. It can run
without errors yet solving a different problem.

6.2 Evaluation

Compiled by Sir Clive Ayumbi; [email protected] 675207337


14
This entails checking an algorithm to ensure that it actually solves the problem for which it was
designed.

6.3 Analysis
After testing and evaluating an algorithm we might discover that, though it solves the problem
for which it was designed, it might be doing so at the expense of system resources such as
memory space and processor time. If this is the case, the algorithm is said to be working but not
effective. Analysis an algorithm entails checking to ensure correctness, reasonableness and
effectiveness.

ALGORITHM C Code

1) sum(n) #include <stdio.h>

begin int main()

i = 1; {

total = 0; int i = 1, sum = 0, N; // initialization of I and sum

while i is not greater than n, printf(“Enter the last number you want to sum to \n”);

begin scanf(“%d”, &N);

total = total + i; while (i <= N)

i = i + 1; {

end sum = sum + i;

return total; ++i;

printf(“The sum of the first %d is %d”, N, Sum);

return 0;

Algorithm to calculate the average of n # include <stdio.h>


numbers
int main()
Start
{
Get N1, N2, N3, N4, N5
int a ;
Sum = N1 + N2 + N3 + N4 + N5
float num1, num2 , num3 ,num4,num5 ,sum;
Average = sum/n.
a=3;
We can also define an array of numbers
printf("Enter three numbers\n");

Compiled by Sir Clive Ayumbi; [email protected] 675207337


15
printf("Enter num1");

scanf("%f",&num1);

printf("Enter num2");

scanf("%f",&num2);

printf("Enter num3");

scanf("%f",&num3);

printf("Enter num4");

scanf("%f",&num4);

printf("Enter num5");

scanf("%f",&num5);

sum= num1+num2+num3+num4+num5;

printf("\nThe average of %f, %f, and %f is %f ", num1, num2,


num3,num4,num5, sum /a);

return 0;

Algorithm to calculate the average of n /*program assigns numbers into a five-element float array, and
numbers computes the sum and average*/

Using arrays #include <stdio.h>

#define N 5

int main(void) {

float a[N], sum = 0, average;

int i;

/*assign numbers in the array*/

a[0] = 56.5; a[1] = 67.5; a[2] = 45; a[3] = 89; a[4] = 78;

/*compute the sum*/

for (i = 0; i < N; i++)

sum += a[i];

average = sum/N;

/*display required output*/

printf("\nThe %d numbers are: ", N);

for (i = 0; i < N; i++)

Compiled by Sir Clive Ayumbi; [email protected] 675207337


16
printf("%.2f ",a[i]); /*print all the numbers on one line*/

printf("\n\nThe sum of the numbers is %.2f", sum);

printf("\n\nThe average of the numbers is %.2f\n", average);

2. The Fibonacci sequence // Program to generate the first N Fibonacci numbers


The Fibonacci function displays the elements
in the sequence. #include <stdio.h>

The sequence is 0, 1, 1, 2, 3, 5, 8, 13, int main (void)



{
We write it as F1, F2, F3, F4, F5, F6, F7,
F8… int Fibonacci[N], i;

See that F1 = 0, F2=1 Base case Fibonacci[0] = 0; // by definition

F3 = F2 +F1 Fibonacci[1] = 1; // ditto

F4 = F3 + F2 Printf(“Enter the maximum number whose series you want to generate.


\n”);
F5 = F4 + F3
scanf(%d, &N);
Generally Fn = Fn-1 +Fn-2
for ( i = 2; i < N; ++i )

{Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];

for ( i = 0; i < N; ++i )

printf ("%i\n", Fibonacci[i]);

return 0;

3. Algorithm to calculate the area of a circle #include <stdio.h>

Analysis: #define PI 3.1415926535897932385E0

Input: radius (r) or diameter (d)

Constant: Π= 3.14

Processing: Area= Π*r*r or area =Π*d/2 main()

Output: Area {

double radius, area;

Start /* define variables */

Take Π=3.14

Compiled by Sir Clive Ayumbi; [email protected] 675207337


17
Give the radius, r

Calculate the area using Area= Π*r*r printf("Enter the radius of a circle \n");

Print out Area /* ask for radius */

Stop scanf("%lf", &radius);

/* read in radius */

area = radius * radius * PI;

/* area formula */

printf("radius=%f, area=%f\n", radius, area);

/* print results */

Algorithm to implement a loop and condition #include<stdio.h>


depending on age.
int main()
Start
{
Get age
int a, n, i ;
Get the number whose addition or multiplication
table you want to build. /*variables for age,number ,and loop counter*/

If age is less than 6 printf("enter age:\t");

Produce the addition table for n scanf("%d",&a);

Else printf("Enter integer:\t ");

Produce a multiplication table for n scanf("%d",&n);

stop if (a < 6)

for (i=1; i<=10; i++)

printf("%d + %d = %d\n",n,i,n+i);

else

for (i=1; i<=10; i++)

Compiled by Sir Clive Ayumbi; [email protected] 675207337


18
printf("%d*%d=%d\n",n,i,n*i);

Algorithm to calculate the area of a rectangle #include<stdio.h>

Analysis int main()

Input: length(L), width(W) {

Processing: Area= L*W int L, W, Area ;

Output: Area printf(“Enter the value for the Length of the rectangle\n”);

scanf(“%d”, &L);

Start printf(“Enter the value for the Width of the rectangle\n”);

Give the length, l scanf(“%d”, &W);

Give the width, w Area = L * W;

Calculate the area using Area=l*w printf(“Then Area %d = %d x %d”, Area, L, W);

Print out Area return 0;

Stop }

Algorithm to calculate the area of a triangle #include<stdio.h>

Analysis int main()

Input: base (b), height (h) {

Processing: Area=b*h/2 int B, H, Area ;

Output: Area printf(“Enter the value for the Base of the Triangle\n”);

scanf(“%d”, &B);

Start printf(“Enter the value for the Height of the Triangle\n”);

Give the base, b scanf(“%d”, &H);

Give the height, h Area = B * H/2;

Calculate the area using Area=b*h/2 printf(“Then Area %d = %d x %d”, Area, B, H);

Output Area return 0;

Stop. }

. Calculate the value of the function


f ( x)  2 x 2  2 x  3 where x is any integer

Compiled by Sir Clive Ayumbi; [email protected] 675207337


19
Analysis

Input: an integer, x

Processing: f=2*x*x – 2*x-3

Output f

Start

Give an integer, x

Calculate f from the formula f=2*x*x – 2*x – 3

Output the value of f

Stop

Calculate and print the different values of y=f(x)


where f ( x)  2 x 2  2 x  3 for 1  x  5 .

Analysis

Give an integer, x.

For x=1 up to x=5 do what is in this box

f ( x)  2 x 2  2 x  3

Output: f (x )

Start

Give an integer, x

For x=1 to 5 do

Begin

f ( x)  2 x 2  2 x  3

Output: f (x )

End

Compiled by Sir Clive Ayumbi; [email protected] 675207337


20
Stop.

Algorithm to evaluate the value of the factorial of #include <stdio.h>


an integer.
int main()

{
Analysis
int c, n, fact = 1;
Input: integer n
printf("Enter a number to calculate it's factorial\n");
Processing: if n<2 then n!=1

Else n!=n*(n-1)!
scanf("%d", &n);
Output: n!
for (c = 1; c <= n; c++)

fact = fact * c;
Start
printf("Factorial of %d = %d\n", n, fact);
Give an integer n
return 0;
Set fac to 1
}
For i=n down to 1 do

Set fac to fac*i

Print fac

Stop.

Algorithm for calculating the value of x in the #include<stdio.h>


equation ax  bx  c  0 with a<>0.
2

//#include<conio.h>
Analysis
#include<math.h>
Input: a, b, c with a<>0

Process: D  b  4 * a * c
2
//#include<process.h>

If D<0 then no solution

Else roots are X1 = (-b+D)/2*a or void main()

X2 = (-b-D)/2

Output: X1, X2 {

double a,b,c,d,root1,root2,t;

Start

Give 3 integers a, b, c

Compiled by Sir Clive Ayumbi; [email protected] 675207337


21
If a=0 then output “Not a quadratic equation” printf("\n- A quadratic equation is in the forrm a * x * x + b * x + c = 0");

Else

Calculate D from D  b  4 * a * c printf("\n\n- To solve the equation ,please provide the value of a, b & c -");
2

If D<0 then output “Roots are not real” prinf(“ Note The value of a is never zero\n”);

Else printf("\n\n a = ");

Calculate roots using x1=(- scanf("%lf", &a);


b+D)/2*a or x2=(-b-D)/2*a
printf("\n b = ");
Display x1, x2.
scanf("%lf", &b);
Stop
printf("\n c = ");

scanf("%lf", &c);

d=(b*b-4*a*c);

t = pow(d,0.5);

if(d<0)

printf("\n Cannot claculate roots, as these would be complex numbers.\n");

root1=(-b+t)/(2.0*a);

root2=(-b-t)/(2.0*a);

printf("\n The roots of the quadratic equation are %lf & %lf", root1,root2);

return 0;

Compiled by Sir Clive Ayumbi; [email protected] 675207337


22
}

Infix, Postfix, & Prefix notation


 We usually write algebraic expressions like this:

a+b

 This is called infix notation, because the operator (“+”) is inside the expression

 A problem is that we need parentheses or precedence rules to handle more complicated expressions:

For Example :

a+b*c = (a + b) * c ?

= a + (b * c) ?

 There is no reason we can’t place the operator somewhere else.

 How ?

 Infix notation : a + b

 Prefix notation : + a b

 Postfix notation: a b +

Prefix notation was introduced by the Polish logician Lukasiewicz, and is sometimes called “Polish notation”.

Postfix notation is sometimes called “reverse Polish notation” or RPN.

 Question: Why would anyone ever want to use anything so “unnatural,” when infix seems to work just fine?

 Answer: With postfix and prefix notations, parentheses are no longer needed!

infix postfix prefix

(a + b) * c ab+c* *+abc

a + (b * c) abc*+ +a*bc

Infix form : <identifier> <operator> <identifier>

Postfix form : <identifier> <identifier> <operator>

Prefix form : <operator> <identifier> <identifier>

Convert from Infix to Prefix and Postfix (Practice)

Compiled by Sir Clive Ayumbi; [email protected] 675207337


23
 x

 x+y

 (x + y) - z

 w * ((x + y) - z)

 (2 * a) / ((a + b) * (a - c))

Convert from Postfix to Infix (Practice)

 3r-

 13r-+

 st*13r-++

 vwxyz*-+*

Compiled by Sir Clive Ayumbi; [email protected] 675207337


24

You might also like