Iterative and Recursive Demo

ALT-F4 0 Tallied Votes 178 Views Share

This small program simply allows the user to call two different methods passing along an interger value to each. One method will output numbers from zero utnil that integer value using iteration. The other method outputs numbers from zero to that integer using recursion.

public class Main {
    

    public Main() {
        iterativeMethod(10);
        recursionMethod(10);
    }
    public static void main(String[] args) {
        Main demo = new Main();
    }
    public void iterativeMethod(int x){
        for(int i=0; i<=x; i++){
            System.out.println("The iterative number is "+i);
        }
    }
    public int recursionMethod(int x){
        int call;    
        if(x!=-1){
            call = recursionMethod(x-1)+1;
            System.out.println("The recursive number is "+call);
        }
        return x;
    }
}
Dani 4,329 The Queen of DaniWeb Administrator Featured Poster Premium Member

I'm new to Java. This has actually been the first time I've seen a constructor method for main. Looks good, and it's a good way to explain recursion.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.