Part 4: Java Scope and Recursion use with Example.

Part 4: Java Scope and Recursion use with Example.

Java Scope and Recursion use

Java Scope

In Java, variables are only accessible inside the region they are created. This is called scope.In Method Scope Variables declared directly inside a method.

Example

public class Tree{
public static void main(String[] args) {

// Code here CANNOT use numTree

int numTree = 100;

// Code here can use numTree
System.out.println(numTree );
}
}

output

100

Besides, Block Scope means a block of code refers to all of the code between curly braces {}. Variables declared inside blocks of code are only accessible by the code between the curly braces.

Example

public class Tree{
public static void main(String[] args) {

// Code here CANNOT use numTree

{ // This is a block

// Code here CANNOT use numTree

int numTree = 100;

// Code here CAN use numTree
System.out.println(numTree );

} // The block ends here

// Code here CANNOT use numTree

}
}
output

100

Java Recursion

In, java programming the technique of making a function call itself is Recursion. This technique provides a way to break complicated problems down into simple problems which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.

Recursion Example

Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the following example, recursion is used to add a range of numbers together by breaking it down into the simple task of adding two numbers:

Example

//Use recursion to add all of the numbers up to 10.

public class Tree {
public static void main(String[] args) {
int result = sum(5);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
}

output

15

Example Explained

When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns the result. When k becomes 0, the function just returns 0. When running, the program follows these steps:

5 + sum(4)
5 + ( 4 + sum(3) )
5 + ( 4 + ( 3 + sum(2) ) )

5 + 4 + 3 + 2 + 1 + sum(0)
5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns the result.

Halting Condition

In java, like loops can run into the problem of infinite looping, recursive functions can run into the problem of infinite recursion. Infinite recursion is when the function never stops calling itself. Every recursive function should have a halting condition, which is the condition where the function stops calling itself. In the previous example, the halting condition is when the parameter k becomes 0.

It is helpful to see a variety of different examples to better understand the concept. In this example, the function adds a range of numbers between a start and an end. The halting condition for this recursive function is when end is not greater than start:

Example
Use recursion to add all of the numbers between 5 to 10.

public class Tree {
public static void main(String[] args) {
int result = sumTree(5, 10);
System.out.println(result);
}
public static int sumTree(int start, int end) {
if (end > start)
{
return end + sumTree(start, end - 1);
}
else
{
return end;
}
}
}

output

45

 Factorial of a Number Using Recursion

#Factorial of a Number Using Recursion in java
public class Factorial {

    public static void main(String[] args) {
        int num = 6;
        long factorial = multiplyNumbers(num);
        System.out.println("Factorial of " + num + " = " + factorial);
    }
    public static long multiplyNumbers(int num)
    {
        if (num >= 1)
            return num * multiplyNumbers(num - 1);
        else
            return 1;
    }
}

Output

Factorial of 6 = 720

Initially, the multiplyNumbers() is called from the main() function with 6 passed as an argument.

Since 6 is greater than or equal to 1, 6 is multiplied to the result of multiplyNumbers() where 5 (num -1) is passed. Since, it is called from the same function, it is a recursive call.

In each recursive call, the value of argument num is decreased by 1 until num reaches less than 1.

When the value of num is less than 1, there is no recursive call.

And each recursive calls returns giving us:

6 * 5 * 4 * 3 * 2 * 1 * 1 (for 0) = 720.

Draftsbook is a learning base blog. The blog share Article series based on Subject. For example:

    1. JAVA : JAVA  is a object-oriented programming(OOP) language. This language classes and objects are the two main aspects of OOP. The blog content discuss below principles of OOP:
      1. Encapsulation
      2. Inheritance
      3. Abstraction
      4. Polymorphism
  1. Data Structure: Data structure refers a several way of organizing data in a computer system.
  2. Android : Android software development  apps can be written using Kotlin, Java, and C++ languages” using the Android software development kit (SDK). This blog contains  android feature Navigation drawer implementation and its usage are mention.
  3. IELTS : IELTS  Four module with strategies are written hereby

5.Problem Solving : Problem solution on various online platform tips and solution are given here following platform.

IELTS formal informal word uses.

IELTS formal informal word uses.

IELTS formal informal word

Vocabulary is important for practicing English. IELTS Formal and informal word Knowing and using  is essential for higher scores. In Speaking and Writing, for both General and Academic students. Speaking part, talking to a office is different from talking with family’s members. Besides in writing, writing an academic essay is different from writing a letter to a close friend.

 

Using the correct form of language is essential for getting a high score in the writing section. Let’s take a look at the FREQUENT situations and several main differences of formal and informal WORD writing in the IELTS.

Informal Formal
Sorry Apologize
Tell Inform
Need Require
Ask Request
Check Verify
Get Receive
So Therefore
Choose Select
Look for Seek/Search
Maybe Perhaps
Say no Reject
Buy purchase
Start Commence
Check Verify
Help Assist
Use Consume
Kids Children
Call off Cancel
I think In my opinion
To sum up In conclusion
But however
Point out indicate
Think about consider
Empty Vacant
Worse Inferior
Hurt Damage
Want Desire
Build Construct
Seem Appear
mad Insane
Go up increase
tough difficult
book reserve
In the end finally
What’s up? How do you do?
Nice to meet you It is a pleasure to meet you?
As soon as you can At your earliest convenience
Worried about you Concerned about you
To start with/ For a start Firstly
Say hello to Give my regards to
Heard from her lately Have you heard from her lately
Seen her? Have you seen her?
She’s right I agree with her,that..
Don’t forget I would like to remind you that…
Thanks a lot! I appreciate your assistance!
Because In light of the fact that
I think.. In my opinion that…
I need to.. It is necessary for me
You don’t hafta It is not necessary for yo to..
We recommend It is recommended
Sorry… Please accept our apologies for…
Another good thing is Secondly..
What’s more Besides
Not only that Furthermore
And one of the best things is…/The most important thing is../And best of all.. Lastly,
She can She has the ability
They put the plan into action The plan was implemented/carried out
The place where you want to go Our destination
I’m sorry to tell you that.. I regret to inform you of..
Could you? I was hoping that you could
It wasn’t be a problem anymore It will cease to be a problem
When you get here, Your arrival
I’m getting tired of this junk. One grows waery in these matters.
This seemed to fix the problem This appeared to rectify the problem
Can I help you? Please State your business
Please get back to me ASAP I would be grateful if you could reply early
Could you..? I’d really appreciate it if you could..
We want to We would like to
Shall I? Would you like me to.?
To think about To consider
This shows that.. This demonstrates.
To tell the difference To distinguish
We’ve received We are in receipt of
You should revise Revision should be done
It will do you good This will be of great benefit to you
What’s going on? How are you doing?
Just a note to say.. I am writing to inform you..
As we discussed this morning As per our telephone conversation on today’s date
It would be great if you could attend this event We would be honored if you would attend this event
Your kid is making trouble I am afraid your child is experiencing difficulty
See you next week I look forward to meeting you next week.
People use a huge amount of People consume a tremendous amount of
 

 See more articles about IELTS study and strategy:

  1. IELTS writing different sentence in Similar meaning.
  2. IELTS reading module vocabulary list
  3. IELTS reading module vocabulary list
  4. IELTS Speaking band scores scheme and how they are calculated
A program sorts an array of integer. Write down the code that tests the sorting algorithm of written in a program.

A program sorts an array of integer. Write down the code that tests the sorting algorithm of written in a program.

Combined Bank(HBFC and KB)

Assistant Programmer-2018

Description: given array of size number, write a program to check if it is sorted in Ascending order or not.

Description: given array of size number, write a program to check if it is sorted in Ascending order or not.

Input: 10, 11,12,13,14

Output: True

Input: 20, 21,22,23,24

Output: True

Input: 20, 11.19,13,12

Output: False

Source code

#include <bits/stdc++. h>

#include <iostream>

using namespace std;

int sortTest (int arraList[], int nunber)

{

    int i;

        if(nunber==1 || nunber==0)

        return true;

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

        if(arraList[i-1]>arraList[i])

        return false;

    return true;

}

int main()

{

    int arraList[5] = {1,2,4,6,7};

    int number=5;

    if(sortTest(arraList,number))

    cout<<“True”;

    else

    cout<<“True”;

}