Upload
trinhnhu
View
218
Download
1
Embed Size (px)
Citation preview
Unit - 2
2.1 EXCHANGING THE VALUES OF TWO VARIABLES
Problem Statement:
Design an algorithm to exchange the values of two given variables a and b.
Algorithm Development:
Let us assume the initial values are a=20, b=10.
Initial Value
a b
This means that variable „a „contains the value 20, and variable „b‟ contains the value 10.
For exchanging the values we need to replace the content of a with 10, and the content of b
with 20.
Target value
a b
To change the value of variable we can use the assignment operator.
a=b;
b=a;
where “=” is the assignment operator. It is used to copy the value of variable in right side into
variable in left side. After execution of the statement a=b, the values in the a and b are
a b
Now a=10 and b=10. After execution of the statement b=a, the values in the a and b are
a b
20 10
10 20
10 10
10 10
This is not target value.While executing b=a , b takes the current value of a. but it needs the old
value of a. so it could not exchange the values not properly. The exact problem statement is
New value of a = old value of b;
New value of b = old value of b;
But in our proposed solution , New value of b = New value of a;
To solve this problem we need to store the old value of „a‟. For that we introduce a
temporary variable „t‟ and copy the original value of „a‟ into the „t‟ before executing a=b
statement.
t=a;
a=b;
after these two steps we have
a t b
Still we are having old value of “a” stored in “t”. we need to assign this value into “b”.
b=t;
After execution of this step we have:
a t b
This is the target value we needed. Now the value “a” and “b” is interchanged as required.
Algorithm Description:
Step 1: Start the process.
Step 2: Initialize a=20 and b=10.
Step 3: t=a;
a=b; Interchanging Process
b=t;
Step 4: Print the value of a and b.
Step 5: Stop the process.
10 20 10
10 20 20
Pseudo Code:
Procedure exchange
Input: a,b :integer
Output :a,b:integer
Var t:integer
begin
t = a;
a = b;
b = t;
end
Implementation:
Void main()
{
int a,b;
a=20;
b=10;
printf(“Before Swapping the value of a = %d and b =%d”, a,b);
t=a;
a=b;
b=t;
printf(“After Swapping the value of a = %d and b =%d”, a,b);
}
Notes on design:
Using Temporary variable the value of two variables are interchanged.
2.2 COUNTING
Problem Statement:
Design an algorithm to count number of student passed in their examination
among „n‟ number of students.
Algorithm Development:
Assumption: mark range is : 0 to 100
Condition: Pass mark is : 50 and above(>=50).
Consider given set of student marks are
75,60,90,30,85
Now, we have to make a count number of students get pass mark among 5 students. For that
initialize one counter variable called „count‟ (which is used to store counted value) with value
zero. Take first mark (i.e 75) and compare with the condition(>=50) i.e if 75>=50 or not..if it is
greater than 50 then so far one student get passed. So, increment counter variable („count‟) by
1. Continue this same process for remaining marks and for each pass mark counter
incremented by 1.
To achieve this counting for each pass mark value 1 will be added to the previous count value.
i.e new count value= old count value + 1
This means that always „new count value‟ is assigned to „old count value‟ in the next
forthcoming mark.
i.e.,
new count value = old count value + 1;
Old count value = new count value;
From this we can drive
new count value = new count value + 1;
So, count = count + 1
(new count value) (old count value)
For cumulative addition always left and right hand side of expression is same variable (eg.
count).
Initially, count=0
Marks condition(mark>=50) old count value new count value
75 yes count=0 count=1
60 yes count=1 count=2
90 yes count=2 count=3
30 no count=3 count=3
85 yes count=4 count=4
After examining all the marks the total number of students passed is : 4
Algorithm Description:
Step 1: Start the process.
Step 2: Read number of students (n).
Step 3: Initialize counter variable with value zero (count = 0).
Step 4: Repeat till to examine all the marks
(i) Read the mark value.
(ii) If it is pass (mark >= 50), then add value 1 to count (count=count+1).
Step 5: Print the value of count.
Step 6: Stop the process.
Pseudo Code:
Procedure count
Input : n, mark : integer
Output: count:integer
Var i:integer
begin
write(“enter a number of students”,n);
read(n);
count = 0;
i = 1;
while i<=n do
begin
i = i+1;
read(mark);
if mark > = 50 then count = count + 1;
end;
write(“Number of students passed is” , count);
end;
Notes on design:
Using Cumulative addition procedure counting is done.
Implementation:
Void main()
{
int i,n,count=0,mark;
printf(“enter the number of students”);
scanf(“%d”,&n);
for ( i=1;i<=n;i++)
{
printf(“enter the mark”);
scanf(“%d”,&mark);
if(mark>=50)
count=count+1;
}
printf(“number students passed”,count);
}
2.3 SUMMATION OF A SET OF NUMBERS
Problem Statement:
Design an algorithm to make a sum of a given set of „n‟ numbers and print the result.
Algorithm Development:
Assumption: set of numbers(„n‟ >=0)
Consider given set of numbers
125,65,87,43
Now, we have to add all the numbers and find sum value.
sum = 125 + 65 + 87 + 43
In above expression will add all the four numbers and added value will be store into variable
sum.
Then generally,
sum = number1 + number2 + number3 + …….+ numbern. (1)
Here n(set of numbers) is 4.
But in computer can add two numbers at a time. In this way first two numbers will be added first.
i.e., sum = number1 + number2 (2)
number1 = 125;
number2 = 65;
sum = 125 + 65;
Now current sum value is: sum = 190;
In the second step add the third number with the added value of the first two numbers (sum).
sum = sum + number3 (3)
sum = 190 + 87;
Now current sum value is: sum = 177;
Similarly,
sum = sum + number4 (4)
Now the current value of sum is : sum = 43;
In general,
sum = number1 + number2
sum = sum + number3 ≤
sum = sum + number4
. . .
. . .
. . .
sum = sum + numbern
In the ith step
sum = sum + number i+1
We need to develop an algorithm to sum a set of „n‟ numbers.(n>=0). If it is zero the sum value
is zero, then we can generate first sum directly by
sum = 0;
because of this we need to change expression (2)
sum = sum + number1
Algorithm Description:
Step 1: Start the process.
Step 2: Read set of numbers (n).
Step 3: Initialize sum variable with value zero (sum = 0).
Step 4: Repeat till „n‟ numbers
(i) Read number.
(ii) Calculate sum = sum + number.
Step 5: Print the value of sum.
Step 6: Stop the process.
Pseudo Code:
Procedure summation
Input: n,number : integer
Output: sum : integer
Var i:integer
begin
write(“enter total number of values”);
read(n);
i =1;
sum = 0.0;
while i<=n do
begin
i= i+1;
read (number)
sum = sum + number;
end;
write(“sum of numbers is”, sum);
end;
Notes on design:
Using the Cumulative addition procedure summation of „n‟ number is done.
Assignment problem:
Design an algorithm to find out multiplication of a set of numbers.
Implementation:
Void main()
{
int i,n;
int num,sum=0.0;
printf(“enter the no.of elements to be added”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
scanf(“%d”,&num);
sum=sum+num;
}
printf(“the sum value is%d”, sum);
}
2.4 FACTORIAL COMPUTATION
Problem Statement:
Design an algorithm to calculate factorial for given number.
Algorithm Development:
Assumption: given number „n‟ >=0
By definition n! = 1*2*3……n-1*n;
0! = 1;
1! = 1*0!;
2! = 2*1!;
3! = 3*2!;
…
…
…
In general n! = n * (n-1)!
For example, to calculate the value of 4!
4! = 4 *3! (Before that we need to find out 3!)
3! = 3*2! (Before that we need to find out 2!)
2!= 2*1! (Before that we need to find out 1!)
1! = 1*0! (Before that we need to find out 0!)
0! = 1
So, we have start with 0!. By definition 0! = 1;
We are taking „fact‟ variable to store factorial value of given number.
Intially, the value of fact is 0!. So, fact = 1.
fact = fact*1;
fact = fact*2;
fact = fact*3;
fact = fact*4;
Total number of multiplication(product) count is 4
Algorithm Description:
Step 1: Start the process.
Step 2: Read the number (n).
Step 3: Initialize fact variable with value one (fact = 1) and productcount = 1.
Step 4: Repeat till „n‟ number of products
(i) fact = fact * productcount;
(ii) Productcount = productcount + 1;
Step 5: Print the value of factorial.
Step 6: Stop the process.
Pseudo Code:
Procedure factorial
Input: n : integer
Output : fact :integer
Var i,productcount:integer
begin
write(“enter number to find out factorial”);
read(n);
fact=1;
productcount=1;
while productcount<=n do
begin
fact = fact * productcount;
productcount = productcount + 1;
end;
write(“Factorial of given numbers is”, fact);
end;
Notes on design:
Using the Cumulative multiplication procedure factorial of a given number is calculated.
Implementation:
Void main()
{
int i,n,fact=1;
printf(“enter the number to find factorial”);
scanf(“%d”,&n);
for(i=1;i<n;i++)
fact=fact*i;
printf(“the factorial value is %d”, fact);
}
2.5 SINE FUNCTION COMPUTATION
Problem Statement
Design an algorithm to evaluate the function sin(x), as defined by the expression
sin 𝑥 =𝑥
1!−
𝑥3
3!+
𝑥5
5!−
𝑥7
7!+ …
Algorithm Development
Looking at the sin expression we can see that the powers and the factorials form
the sequence 1,3,5,7,….This can be generated by a sequence starting with 1 and
incrementing by 2 every time.
Every single term can be represented in general by
𝑥𝑖
𝑖!=
𝑥
1 ×
𝑥
2 ×
𝑥
3 ×
𝑥
4 × … ×
𝑥
𝑖
These terms can be generated by using the value of previous term. For generating,
𝑥3
3! =
𝑥 × 𝑥 × 𝑥
3 × 2 × 1=
𝑥2
3 × 2 𝑥
1!
𝑥5
5! =
𝑥 × 𝑥 × 𝑥 × 𝑥 × 𝑥
5 × 4 × 3 × 2 × 1=
𝑥2
5 × 4 𝑥3
3!
𝑥7
7! =
𝑥 × 𝑥 × 𝑥 × 𝑥 × 𝑥 × 𝑥 × 𝑥
7 × 6 × 5 × 4 × 3 × 2 × 1=
𝑥2
7 × 6 𝑥5
5!
Each of these terms to be used to find the successive term can be generally specified
as,
𝑥2
𝑖(𝑖 − 1) 𝑓𝑜𝑟 𝑖 = 3,5,7, …
Therefore, to generate consecutive terms of the sine series,
i th term = 𝑥2
𝑖(𝑖−1) × 𝑝𝑟𝑒𝑣𝑖𝑜𝑢𝑠 𝑡𝑒𝑟𝑚
For alternate sign, (-) is multiplied with the term.
Initial conditions are set according to the value of first term as follows:
tsin = x
term = x
i=1
The ith term and summation can be generated iteratively using the following statements:
i = i+2
term = - term*x*x/(i*(i-1))
tsin = tsin + term
Considerations:
The input value x should be in the specified range, -1≤ 𝑥 ≤ 1
An error value is fixed as constant to terminate the iteration if the current term is
less than the error value.
Algorithm
1. Set up the initial conditions for the first term, as they cannot be calculated
iteratively.
2. While the absolute value of the current term is greater than the current term
do
a) Identify the i value
b) Generate i th term value
c) Add current term with the appropriate sine value to the accumulated
sum for sine function.
Pseudocode
procedure sine function
Input : x : real
Output : tsinx : real
const error =1.0 e -6
var x,term :real;
j,x2 : integer;
begin
term = x;
tsinx =x;
j =3;
x2 = x * x;
while abs(term) > error do
begin
j = j + 2;
term = - (term * x2 / j * (j-1))
tsin : = tsin + term;
end
sin = tsin;
end
2.6 GENERATION OF THE FIBONACCI SEQUENCE
Problem Statement
Generate and print the first n terms of the Fibonacci sequence, where n ≥ 1. The first
few terms are,
0,1,1,2,3,5,8,13,21,…
Each term after the first two terms are obtained from the sum of two immediate
predecessors.
Algorithm development
New term = preceding term + term before the preceding term
A general procedure:
Variables used:
a = Term before the previous term
b = Previous term
c= new term
Now,
a = 0; First Fibonacci number
b = 1; Second Fibonacci number
c = a + b ; Third Fibonacci number
to continue with next terms , we can reuse the variables a and b as follows:
a = 0; First Fibonacci number
b = 1; Second Fibonacci number
c = a + b ; Third Fibonacci number
a = b;
b = c;
As we have only two active terms, we can reduce three terms [a,b,c] to two terms [a and
b]. This can be done by generating two terms at a time. The first four steps would
become,
a = 0; First Fibonacci number
b = 1; Second Fibonacci number
a = a + b ; Third Fibonacci number
b = a + b; Fourth Fibonacci number
Initialize i = 2; In every iteration two terms are generated and printed with the final
condition for iteration as (i<n), to ensure we print only n terms in the series.
Algorithm
1. Read the number of terms to be generated, n.
2. Assign first two Fibonacci numbers to a as 0 and b as 1.
1. Initialize count =2.
2. While less than n terms generated,
a. Write two terms as a and b.
b. Generate next term by a = a + b.
c. Generated another term by b = a + b.
d. Update count by count + 2.
3. If n is even write the last two generated terms , else write only the last but one
term.
Pseudocode
Procedure Fibonacci
Var a {Fibonacci number variable},
b {Fibonacci number variable },
i{number of Fibonacci number generated },
n{ number of Fibonacci number to be generated }: integer;
begin {generate each Fibonacci number from the sum of its two predecessors}
a : =0;
b : =1;
i: = 2;
writeln („Enter n the number of Fibonacci numbers to be generated‟);
readln (n);
while i<n do
begin
writeln (a,b);
a :=a+b;
b:=a+b;
i :=i+2;
end
if i=n
then writeln (a,b)
else wrietln (a)
end.
2.7 REVERSING THE DIGITS OF AN INTEGER
Problem:
Design an algorithm that accepts a positive integer and reverses the digits in the integer.
Algorithm Development
Digit reversing is used in computing for fast information retrieval.
Let us take an example
Input: 576894
Output expected: 498675
Here 576894 can written as
5*10 5 +7*10 4 +6*10 3+8 *10 2 +9*10 1+4
Least Significant value (LSB) - 4
Most Significant value (MSB) – 5
To reverse it we have to extract the Least Significant value (LSB) from the number i.e., 4 first.
This is accomplished by modulo division.
576894 mod 10 4 (mod gives the remainder of division)
Followed by removing the next digit from the right hand side is 9.To extract 9 from the number,
we have to reduce the original number 576894 to 57689.This is done by integer division of the
number by 10.
576894 div 10 57689
These two steps have to be done repeatedly until the number is greater than zero.
r = n mod 10 (576894 mod 10 gives 4)
n= n div 10 (576894 div 10 gives 57689)
The reversed number can be obtained at this stage by shifting the LSB one time left by
multiplying with 10.
49 = 4*10+9
Then the reversed number can be computed by
reverse = previous value of reverse*10 + remainder
where reverse = 0 initially
step 1: r = n mod 10
step 2: reverse =reverse*10 +r
step 3: n= n div 10
These steps has to be repeated iteratively until n is equal to zero.
Number (n) remainder (r) reversed number (reverse) number (n)
576894 4 0*10+4 =4 57689
57689 9 4 *10+9 =49 5768
5768 8 49*10+8=498 576
576 6 498*10+6=4986 57
57 7 4986*10+7=49867 5
5 5 49867*10+5=498675 0
Algorithm Description
1. Get the number to be reversed, n;
2. Initialize the reversed number, reverse to be zero.
reverse = 0;
3. while number to be reversed is greater than zero
a. Extract the rightmost digit of the number, n and assign it to r.
b. Calculate reverse by increasing reverse by a factor of 10 and add r.
c. Remove the rightmost digit from n by using integer division by 10.
4. Display the reversed number, reverse.
PSEUDOCODE:
Procedure reverse
Input : n (Number to be reversed)
Output : reverse (reversed number)
var r; (remainder value)
var n; (Number to be reversed)
var reverse; (reversed number)
begin
reverse=0;
write ('enter the number to be reversed');
read (n);
while n>0 do
begin
r=n mod 10;
reverse = reverses *10 +r;
n = n/10;
end
Write („The reversed number is‟, reverse);
end
2.8 BASE CONVERSION
Problem:
Convert decimal integer to its corresponding octal or hexadecimal or binary
representation.
Algorithm Development
In computing it is necessary to convert a decimal number into octal or hexadecimal or
binary representation.The number system that we use in our day-to-day life is decimal number
system.
The Decimal number system has a base 10 as it uses 10 digits from 0 to 9. In Decimal number
system, the actual position of the each digit determines its value. For example, the number
275 consists of 5 units, 7 tens, 2 hundreds. It can written as
(275) 10=2*10 2 +7 * 10 1 + 5
The octal number system has a base 8 as it uses 8 digits from 0 to 7. The same number (275) 8
Consists of
5 units, 7 eights, 2 sixty-fours.It can be written as
(275) 8 = 2* 8 2 +7 *8 1 +5
Similarly, the Binary number system has a base 2 as it uses 2 digits (0,1).
101012 =1 x 24 + 0 x 23 + 1 x 22 + 0 x 21+ 1 x 20
The hexadecimal number system uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F.It
has a base 16 as it uses 16 letters. Letters represent numbers starting from 10. A = 10. B = 11,
C = 12, D = 13, E = 14, F = 15.For example, the hexadecimal number (19FDE) 16
19FDE16 = 1 x 164 + 9 x 163 + F x 162 + D x 161 + E x 160
Let us consider the decimal number be 93 that has to be converted into octal representation.
0 10 20 30 40 50 60 70 80 90
0 8 16 24 32 40 48 56 64 72 80 88 93
By dividing blocks of eight, we come to know that there are 11 blocks of eight (11*8=88) +5=93.
But 11 is not a valid octal digit. we know that sixty-fours can be used in the representation. So it
can be represented by 1 sixty-four, 3 eights and 5 units.
The base conversion mechanism for decimal to octal representation follows repeated division
by 8.
93
11
\
1
0
This apparently shows that two steps has to be followed iteratively.
step 1 : r= q mod 8 gives remainder
step 2 : q= q div 8 gives reduced quotient
The same has to be followed for any base conversion.
Algorithm Description
1. Get the number, n and its new base.
2. Initialize the quotient, q to the decimal number, n.
9 tens 3
units
1 sixty-four 3 eights
5 units
8
8
8
8
8
5
8
3
8
1
8
q=n
3. Set ndigit to zero.
4. Assign the ascii value of number zero to zero.
5. Repeat the following until q =0
a. Calculate the next MSB from q as r after division by newbase.
b. Increment ndigit by 1.
c. Get the ascii value of r by adding with zero.
ascii =zero+r
d. if ascii is greater than ascii value of 9
compute ascii =ascii +7
e. Store the character form of ascii value in newrep array indexed by ndigit.
6. Display the newrep array that has converted number in newbase representation in
reverse order.
PSEUDOCODE:
Procedure baseconversion
Input : n (Number to be converted)
newbase (base of the number system)
Output: newrep[] (Output array of character type)
Var n,newbase,i,ascii,ndigit,q,r,zero,newrep[50] ;
begin
Zero:=ord(„0‟);
q:=n;
ndigit:=0;
repeat
r=q mod newbase;
ndigit=ndigit+1;
ascii=zero+r;
if ascii > ascii („9‟)
ascii=ascii+7;
newrep[ndigit]=chr(ascii);
q=q div newbase;
until q=0;
for i=ndigit downto 1 do
write (newrep[i]);
end
2.9 CHARACTER TO NUMBER CONVERSION
Problem:
Given a character representation of an integer convert it to its conventional decimal
format.
Algorithm Development
Before going for conversion,we should know the character representation of integer and its
decimal number
Representation.Let us take an example number , 237.
Decimal notation =2 *10 2 +3* 10 1 +7
Binary notation=1 *2 7+1 *2 6+1 * 2 5+ 0* 2 4+1* 2 3+1 * 2 2+0*2 1+1
Decimal notation uses 3 digits, whereas binary notation uses 8 digits. To represent a very large
integer we require 32 bits in binary notation.
The character notation need 2 8 i.e., 8-bit to represent 256 character.It is ultimately to store a
single character in a 32-bit memory word of a computer. So we can pack 4 charcters in a 32-bit
memory word.
To pack the charcaters the widely used coding system is American Standard code for
Information Interchange(ASCII) or ascii code.
Let us take a string, 23 April 1984.From this string, we take four character sequence
1984.This charcter sequence has to be converted into decimal representation.The internal
representation of character sequence is
To convert it into integer format, we should extract the first character 1 and its corresponding
ascii value is 49 . Subtract the ascii value of zero from 49.We get the actual integer value 1.For
subsequent extraction and conversion, this 1 has to be shifted one time left for each
extraction.This accomplished by multiplying 10.Let the converted decimal be dec, which is
intialised to zero.
The steps involved are
For all characters from 1 to n do the following
1. Obtain the integer representation of the character.
ascii(Char) – asii(0)
2. To shift the decimal value ,dec.
dec=dec*10
To get the current decimal value dec=dec*10+ ascii(char) –acii(0)
The following table shows the ascii charcter codes and their decimal representation.
Character 8-bit code Decimal value
0 00110000 48
1 00110001 49
2 00110010 50
3 00110011 51
.
.
.
.
.
.
.
.
.
49 57 56 52
1 9 8 4
A 01000001 65
B 01000010 66
C 01000011 67
.
.
.
.
.
.
.
.
.
a 01100001
97
.
.
.
.
.
.
.
.
.
Algorithm Description
1. Get the character String, string.
2. Compute the length of the string and assign to n.
3. Initialize the decimal value to zero.
4. Assign ascii value of zero to base0.
5. Do the following till n characters are examined
a. Compute the decimal representation, dec.
b. Convert the next character to decimal digit by subtracting the base0 from the
ascii value of the character.
c. Shift the dec left one digit by multiplying with 10 and add with decimal digit
obtained in 5b.
6. Display the decimal representation,dec.
Procedure chartonum
Input : string[nelements] (string to be converted)
nelements (no of characters in string array)
Output: dec (converted number in decimal format)
var n,i,dec, base0,string[50]:integer;
begin
dec =0;
base0 = ascii(„0‟);
write („enter the string‟);
read (string);
nelements =Length(string);
for i=1 to n do
dec:=dec*10+ascii (string[i])-base0;
write (dec);
end
QUESTIONS FOR PRACTICE
1. Design an algorithm to exchange the values of three variables.
2. Design an algorithm to count number of even numbers in a given set of numbers.
3. Design an algorithm to find out ncr value.
4. Design an algorithm to find cos 𝑥 = 1 − 𝑥2
2!+
𝑥4
4!−
𝑥6
6!+ …
5. Calculate the value of function f when
𝑓 = 𝑥𝑛
𝑛! 2𝑛
∞
𝑛=1