Uploaded by Mohammed ALMadhoun

Programming I Lab 10 - HackMD

advertisement
Programming I Lab 10
Recursion
The Islamic University of Gaza
Engineering Faculty
Department of Computer Engineering
Author: Mohammed Nafiz ALMadhoun
2021/12/03
In this lab, we will talk about a new idea that will help us with a lot of problems, the concept of
recursion is pretty simple, but applying it without understanding it is pretty hard!
Lab Objectives
Understand the concept of recursion.
Be able to write recursive methods.
Recursion
The idea of recursion is pretty simple, imagine you have a method and inside this method, you call
the same method.
So you will have a method that calls itself, this will lead to making the code easier to understand
and write in some complex problems that require itself!
Fibonacci Number Example
The Fibonacci sequence is a sequence starts like this:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . .
Each number in the sequence is just the sum of the previous two numbers, and the first and
second number is our base, so they are just 0 and 1 , to write this in equations we can write:
F0 = 0
F1 = 1
Fn = Fn−2 + Fn−1
Thinking about the code
The idea here is that you will select the base cases (Which will prevent the method from calling
itself forever), then you will write the regular case.
1
2
3
4
5
6
7
8
public static int fib (int index) {
if (index == 0)
return 0;
if (index == 1)
return 1;
return fib(index - 2) + fib(index - 1);
}
Notice that if the index is 0 or 1 , it will return a certain value, but if it’s not 0 or 1 , it will return
the summation of the two previous elements, which in the end will lead to getting the base values.
Calling Example
If we want to get the fib(5) , this will lead to calling the method fib multiple times like this:
fib(5)
fib(1)
fib(3)
fib(4)
fib(2)
fib(1)
fib(3)
fib(2)
fib(0)
fib(2)
fib(1)
fib(1)
fib(1)
fib(0)
fib(0)
Lab Tasks
Task 1: Print the tree of Folders!
In this task, you will use File class, which will allow you to get all the files and folders in a certain
folder using listFiles method, and you can check if this is a file or folder using the methods
isFile , or isDirectory , for example:
1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args){
File dir = new File("D:\\TA\\Programming");
File[] list = dir.listFiles();
for(File child : list){
System.out.print(child.getName());
if (child.isFile())
System.out.println (" - File");
else
System.out.println (" - Folder");
}
}
This code will print all the files and folders names in D:\TA\Programming\ folder:
Files and Folders in the Folder
Code Output
Now, your task is to create a program that prints the tree of files in a certain folder, this will run
recursivly because we don’t know the depth of our tree.
tags: Programming
Java
IUG
End Of Lab 10
Download