Jump to content

how will the RECURSION code be like

- - - - -

  • Please log in to reply
1 reply to this topic

#1
atoivan

atoivan

    Learning Programmer

  • Members
  • PipPipPip
  • 61 posts
can any one help me rewirte dis code and make it recursive .

import java.util.Scanner;

public class Main {

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String[] args) {
        int total = 0, num = 0;
        int i = 0;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number");
        num = in.nextInt();
        for (; i <= num; i++) {
            total += num % 10;
            num /= 10;
        }
        System.out.println(total);
    }

}

Edited by Alexander, 23 November 2010 - 02:47 PM.
[code][/code] tags


#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Fairly simple, the condition of the current loop will go into a normal if

if(i<=num){

  //continue

} else {

  //done

} 


The done-path must return a simple value, and the continue-path must calculated the value with the given paramters and call itself again AND return whatever it gives as reply.

private int recurse(){

  if(i<=num){

    return thevalueIcalculatedHere_with_num + recurse(); 

  } else {

    return ?

  } 

}


The simple value it must return is the vallue that gets added in the end, when i>num. In this case we don't want to add anything else so we'll take 0 here.
Now determine the variables and give them as paramter to the function. When calling yourself again, the variables gets updated!
The end result looks like:

private int recurse(int i, int num){

  if(i<=num){

    return num % 10 + recurse(i+1,  num/10);

  } else {

    return 0;

  } 

}






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users