Thursday, December 30, 2010

Recursive function, add from 1-10

I struggled a lot with recursive function when I was first introduced to it

I mean, why can't you just do it in a loop, but meh, it has it advantages sometimes, but i like loops better, and will continue to use them. But you still gotta know how to do recursive, so here it is :)

I'm going to write a program in java that adds from like 1-x
say like 1-5, you can do it easily in a for-loop
but we're going to do it the recursive way

it's not short so hit jump for everything :)
here's a diagram of my attempt on explaining what is a recursive function






















when you call addSum(5), it calls addSum(4), which calls addSum(3) which calls addSum(2), which calls addSum(1)

so until the number becomes 1, it doesn't return.

so you go down the list of function calls, when you reach the bottom, it'll start returning back to the top
and when you get to the top, your function will return the appopriate value.

my program isn't that long, so try to read it and understand the concept, then move to a little more complicated stuff like fibonacci sequence


import java.util.Scanner;
import static java.lang.System.*;
public class Recursive
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(in);
        out.print("please enter a number>1: ");
        int num = scan.nextInt();
        add myAdd = new add();
        int result = myAdd.addSum(num);
        out.println("the sum of 1 to "+num+" is: "+result );
    }
}
class add
{
    int sum;
   
    int addSum(int num)
    {
        if (num == 1)
        {
            sum += 1;
        }
       
        else
        {
            sum += num;
            addSum(num - 1);
        }
        return sum;
    }
}

No comments:

Post a Comment