Download Algorithms and Recursion

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
KING FAHD UNIVERSITY OF PETROLEUM & MINERALS
Information and Computer Science Department
ICS-201 Introduction to Computing II
Lab 11: Algorithms and Recursion
Objectives: In this lab, the following topics will be covered
1. Algorithms and pseudo-code.
2. Recursion
1. Algorithms and Pseudo-code:
An algorithm is a logical sequence of steps to solve a problem.
A Pseudo-code is an informal description of an algorithm that does not use any programming
language syntax.
Algorithm




A logical sequence of steps for solving a problem, …
Unambiguous (precise) set of steps for solving a problem (or sub-problem) in a finite
amount of time using a finite amount of data.
The algorithm must be general, that is, it should solve the problem for all possible input
sets to the problem.
If there is a particular output for an input, we say that the algorithm can be applied to this
input and process it to give the corresponding output.
Pseudo-code




Pseudo-code (Pseudo = not real; false, Code = Program fragment) is a generic way of
describing an algorithm using the conventions of programming languages, without using
language-specific syntax.
It is a mix of natural language (e.g. English) and programming language conventions.
There is no systematic standard form, although any particular writer will generally
borrow the appearance of a particular language.
Details not relevant to the algorithm (names of variables, which type of a loop, etc.) are
usually omitted.
Example (to be done by the lab instructor)
1. Develop an algorithm to find the average of a list of student scores.
Solution:
 The problem statement doesn’t specify the number of students, so we assume that a
sentinel value of -1 for score indicates the end-of-input. The algorithm is straightforward:
1.
2.
3.
4.
5.
6.
7.
8.
Initialize score, total, count and average to zero.
Input student score
If score = -1 then go to step 7.
Add score to total
Increment count by 1.
Go to step 2.
If count ≠ 0 average = total/count.
Output average.
Here is the Java implementation of the algorithm:
import java.util.Scanner;
public class Sentinel
{
public static void main(String[] args)
{
Scanner stdin = new Scanner(System.in);
double sum = 0, avg = 0;
int score = 0, count = 0;
System.out.print("Enter the score (or -1 to Quit): ");
score = stdin.nextInt();
while (score != -1)
{
sum += score;
count += 1;
System.out.print("Enter the next grade (or -1 to Quit): ");
score = stdin.nextInt();
}
if (count != 0) avg = sum/count;
System.out.println("Average Grade = "+avg);
}
}
Exercise 1:
1. n children are given a jar of cookies. The first child takes away half of the cookies and gives
the jar to second one. The second child also takes half of the cookies from the remaining and
gives the jar to the third child. This process goes on until the last child removes half of the
cookies from the jar, leaving k cookies in the jar. Develop an algorithm to find how many
cookies were in the jar to begin with?
Algorithm:
1.
2.
3.
4.
5.
6.
Display “Enter the number of children:”
Read <number of children>
Display “Enter the number of cookies remaining:”
Read <cookies remaining>
<original cookies> = <cookies remaining>
While (<number of children> > 0)
a. <original cookies> = <original cookies> * 2
b. <number of children> = <number of children> - 1
7. End_While
8. Display “Original number of cookies =” <original cookies>
Convert the above pseudo-code to Java code.
Exercise 2
Here we give an algorithm to display all prime numbers from 2 to 100. Convert your pseudocode into a Java program.
Given an integer n, for all positive integers k less than or equal to n do the following:
1. If k is prime, i.e. isPrime(k) is true, print k.
Algorithm isPrime(int x)
1.
2.
3.
4.
For a given integer x do the following.
Assume that x is prime.
For all positive integers j less than x do the following
Divide x by j. If the remainder after division is equal to zero
for any division, x is not prime.
5. Return the status of primality of x.
Exercise 3
Develop an algorithm to find the maximum and minimum value from a list of integers. Convert
your pseudo-code into a Java program.
2. Recursion
Recursion is a powerful concept that helps to simplify the solution of complex problems.
Recursion means defining something in terms of itself.
•
•
•
A recursive method is a method that calls itself directly or indirectly.
A recursive method has two major steps:
– Recursive step in which the method calls itself
– Base step which specifies a case with a known solution
The method should select one of two steps based on a criteria
•
Any recursive algorithm can be replaced by an iterative one (which uses loops).
Example
An example of a recursive function is factorial
factorial(0) = 1
factorial(n) = n * factorial (n - 1)
(Base Case)
(Recursive Step)
public static int factorial(int n)
{
if (n==0)
return 1;
else
return n * factorial(n-1);
}
Removing Recursion
•
•
Recursion can be removed by replacing the selection structure with a loop
If some data need to be stored for processing after the end of the recursive step, a data
structure is needed in addition to the loop.
Quick Exercise: Write a non-recursive (iterative version of the factorial method above).
Example
Here we write a recursive method to convert a String representing a decimal number to its binary
equivalent. The algorithm is as follows:
1.
2.
3.
4.
5.
If the integer is 0 or 1, its binary equivalent is 0 or 1.
If the integer is greater than or equal to 2 do the following:
Divide the integer by 2.
Separate the result into a quotient and remainder.
Divide the quotient again and repeat the process until the
quotient is zero.
6. Write down all remainders in reverse order as a string.
7. This string is the binary equivalent of the given integer.
// Recursive decimal to binary method
public static String dec2binRecursive(int n)
{
if ( n < 2 )
return n+“”;
else // n>=2
return dec2binRecursive(n/2) + n%2;
}
// Iterative decimal to binary method
public static String dec2binIterative(int n)
{
String binary ="";
while ( n >= 1 )
{
binary = n%2 + binary;
n /= 2;
}
return binary;
}
//=======The Complete Program=============================================
import java.util.Scanner;
public class Dec2Bin
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer: ");
int n = in.nextInt();
String x = dec2bin(n);
System.out.println("The binary equivalent of " + n + " is " + x);
}
public static String dec2bin(int n)
{
if (n < 2)
return n + "";
else
return (dec2bin(n/2) + n%2);
}
}
Exercise 4
Write a java method that computes a b recursively. Both a and b are integers and are not both
zero at the same time.
1
Hint: a b = a * a b – 1 when b > 0, a b = a * a b + 1 when b < 0, and a b = 1 when b = 0.
Exercise 5
Write a recursive method that reverses a String. For example reverse(“Apple”) should return
back elppA.
Exercise 6
Write a recursive method that finds the number of occurrences of a specified character in a string
using the following method header:
public static int count(String str, char a)
For example, count("Welcome", 'e') returns 2.
Exercise 7
Write a recursive method that bin2dec(String s) that converts the binary representation of a string
S into its decimal form. (Hint: This is the converse of the Example given on the previous page).