I want to display every number leading up to the variable 'number'.
Example, if the number is 5, I would want the result to be 1 2 3 4 5. I have an error for returning a value, I'm not sure why. How do I return the results using recursion?
public class SumOfNumbers {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number?");
int number = keyboard.nextInt();
System.out.println(recursion(number));
}
public static int recursion(int number)
{
for (int i=0;i>number;i++)
{
return recursion(i);
}
else {
return number ;
}
}
}
You are mixing recursion and iteration. The for loop is unnecessary in your recursive solution.
Think of your recursive solution as if it already exists: what would you do if a program "print numbers up to n-1" was given to you, and you were asked to write a program that prints numbers up to n? The solution would be pretty clear - you would write it like this:
void myRecursiveProgram(int n) {
if (n == 0) {
return; // do nothing
}
printNumbersUpToN(n-1); // Go up to n-1 using the "magic solution"
System.out.println(n); // Complete the task by printing the last number
}
Now observe that myRecursiveProgram is your printNumbersUpToN program, so all you need to do is renaming it:
void printNumbersUpToN(int n) {
if (n == 0) {
return; // do nothing
}
printNumbersUpToN(n-1);
System.out.println(n);
}
Note the if (n == 0) step: it's very important, because it prevents your recursion from going non-stop into negative territory. This is called the base case of recursion - i.e. the case when you do a fixed amount of work, or no work at all.
Your code doesn't compile, you have an else without if.
What you are trying to do is something like:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number?");
int number = keyboard.nextInt();
recursion(number);
}
public static void recursion(int number)
{
if (number>1)
{
recursion(number-1);
System.out.print(number);
}
else {
System.out.print(number);
}
}
}
This short code will also print the numbers right.
public void recursion(int number){
if (number>1)
recursion(number-1);
System.out.println(number);
}
Related
I'm trying to write a recursive method in Java to find the base 2 log for multiples of 2.
I've successfully computed the log using this recursive method.
import java.util.*;
class temp
{
static int log(int number)
{
if(number==1)
return 0;
return log(number/2)+1;
}
public static void main(String s[])
{
Scanner input=new Scanner(System.in);
System.out.println("Enter Multiple of 2:");
System.out.println("Log is:"+log(input.nextInt())); //calling log with return value of nextInt()
}
}
Where I've run aground is trying to implement the same program using a different method , a method where i start multiplying from 2 in recursive calls until it becomes equal to the given number. Here's what i've tried:
class logarithmrecursion
{
static int step=1;
static int log(int number)
{
final int temp=number;
if(number>=temp && step!=1)
return 0;
step++;
return log(number*2)+1;
}
}
During the first call, number is equal to temp so i use a step variable to prevent the execution of the termination condition.If i don't use "number" variable in the recursive call, i don't have a way to accumulate the previous product but number variable is already equal to temp and will trigger the termination condition in the next recursive call , thus always giving output 1.
What can i do to make this program work?
The first, reducing, version has a fixed termination value of 1.
But the second version's termination depends on the number, so you have to pass that into the recursive call. So, your main function calls a private recursive version:
static int log(int number) {
return log(number, 1);
}
private static int log(int number, int current) {
return current < number ? log(number, current * 2) + 1 : 0;
}
Note: Your algorithm rounds the value up. To give the (more expected) rounded down result, which agrees with (int)(Math.log(i) / Math.log(2)), use this variation:
private static int log(int number, int current) {
return current <= number / 2 ? log(number, current * 2) + 1 : 0;
}
This kind of pattern - using a wrapper function - is common where initial state of the recursion needs to setup once, but we don't want to burden the caller with having to know about what is an implementation choice.
Your first method may also be coded as one line:
static int log(int number) {
return number == 1 ? 0 log(number/2) + 1;
}
try this:
import java.util.Scanner;
public class LogTest
{
static int calLog(final int number)
{
if(number < 2) {
return 0;
}
return log(number, 2, 1);
}
static int log(final int number, final int accumulated, final int step)
{
if(accumulated >= number) {
return step;
}
return log(number, accumulated * 2, step+1);
}
public static void main(String s[])
{
Scanner input=new Scanner(System.in);
System.out.println("Enter Multiple of 2:");
System.out.println("Log is:"+calLog(input.nextInt())); //calling log with return value of nextInt()
}
}
I'm using recursion to print numbers until 2(number), and I'm passing zero(0) as input and recursively calling it until the number reaches 2.
I have tried this code, and it shows the correct output.
class Test{
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num<=2){
rec(++num);
}
System.out.println(num);
}
}
but I want to do this with the following way.
class Test{
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num==2){
return;
}
rec(++num);
System.out.println(num);
}
}
Expected output:
2,1,0
but it shows:
2,1
Why does it happen?
++num increments num, which (as here) makes the code harder to understand.
Try calling rec(num + 1); instead.
You may find your terminating condition needs to be modified to:
if (num > 2)
Terminating conditions are usually the “do nothing” case, which is the case here.
When you are calling rec(++num);, you are incrementing num before printing it out. So when you use 0 as input, by the time it prints num will have changed to 1. When num = 2 at the start of rec(), the print does not execute.
rec(0) prints rec(1),1
rec(1) prints rec(2),2
rec(2) prints nothing
Total output: 2,1
It happens because ++num doesn't just return num + 1 it also modifies num like num = num + 1.
Your if statement is also backwards.
public class Test {
public static void main(String[] args) {
rec(0);
}
private static void rec(int num) {
if (num < 2) {
rec(num + 1);
}
System.out.println(num);
}
class Test {
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num <= 2){
rec(num + 1);
} else return;
System.out.println(num);
}
}
++num - prefixes increment, it means that it's incremented before System.out.println(num); was called. So, first, you check the case of recursion call. If it condition is false - get out of recursion. And when printing value.
When you are working with recursion, try to spread out nested blocks of code, when you will understand simpler.
I'm trying to create a recursive method that returns a value, and prints the value in my main method. I'm confused on how to return and print in main() a row of X asterisks (**..)
X being a integer on the commandline.
For example the commandline argument is 5.
It should output to: *****
My code so far:
public static void main(String[] commandlineArguments){
if(commandlineArguments.length == 0){
System.out.println("Please enter a least one commandline!");
}
else{
Integer number = new Integer(0); //initialize number
try{
Integer x = Integer.parseInt(commandlineArguments[0]);
}
catch(NumberFormatException exception){ //NumberFormatException
System.out.println(exception+" is not a integer!");
System.exit(1); //end program
}
Integer num1 = recursiveMethods.asterisks(number); //A (return address)
System.out.println(num1);
}
}
public static Integer asterisks(Integer number){
String asterisks1 = "*";
for(int i = 0; i < number; i++){
return i;
}
return number;
}
}
A recursive method have two characteristics:
It calls to itself to provide the solution
It has a base case that contains where the recursive call must stop.
Your asterisks method does not fulfill any of these. Since this looks like homework, I would only provide an explanation about how this method should be, the implementation will be yours:
Since your method needs to return asterisks, it would be better returning a String instead of an Integer. This String will contain all the *s needed.
Define a base case. This can be where number have a value of 1.
If number is greater than 1, then you should return an asterisk and the result of calling to asterisks method using the rest of asterisks the whole result needs.
The problem is here:
for(int i = 0; i < number; i++){
return i;
}
This loop will only run one time, and it will immediately return i = 0. You don't want that. Make it append a * to your asterisks1 variable each iteration, then after the loop is finished, return asterisks1 to the caller and print it.
Also, just FYI, this method is not recursive. A recursive method by definition calls itself at some point.
You probably want to call the asterisk function recursively, and return the built up String of asterisks, something like this:
public static void main(String[] commandlineArguments) {
if (commandlineArguments.length == 0) {
System.out.println("Please enter a least one commandline!");
} else {
Integer number = new Integer(0); // initialize number
try {
number = Integer.parseInt(commandlineArguments[0]);
} catch (NumberFormatException exception) { // NumberFormatException
System.out.println(exception + " is not a integer!");
System.exit(1); // end program
}
String asterisk = asterisks(number); // A (return address)
System.out.println(asterisk);
}
}
public static String asterisks(Integer number) {
if (number == 0) {
return "";
} else {
return "*" + asterisks(number - 1);
}
}
to do it recursively you must call itself in itself. for example :
public static void main(String[] commandlineArguments){
if(commandlineArguments.length == 0){
System.out.println("Please enter a least one commandline!");
}
else{
Integer number = new Integer(0); //initialize number
try{
Integer x = Integer.parseInt(commandlineArguments[0]);
}
catch(NumberFormatException exception){ //NumberFormatException
System.out.println(exception+" is not a integer!");
System.exit(1); //end program
}
recursiveMethods.asterisks(number); //A (return address)
}
}
public static void asterisks(Integer number) {
if(number == 0)
return;
else {
System.out.print("*");
asterisks(number - 1);
}
}
}
Can be done as,
public static String asterisks(int n){
return (n==1)?"*":asterisks(n-1)+"*";
}
Note : return Type is String
EDIT: For n <= 0 it prints nothing
public static String asterisks(int n){
return (n<=0)?"":asterisks(n-1)+"*";
}
Here I am working on the following problem where we are given n types of coin denominations of values v(1) > v(2) > ... > v(n) (all integers) The following code tries to find the minimum number of coins that are required to make a sum-C. Here the C is 100(see main function).When I run the code, error--"java.lang.StackOverflowError" comes. Please help.
import java.util.ArrayList;
public class Problem2 {
public static int count=4;
public static int []v={25,10,5,1}; //Array storing denominations
private static int findminimum(ArrayList<Integer> v2) {
int count=v2.get(0);
for(int i=0;i<v2.size();i++)
{
if(count>v2.get(i))
{
count=v2.get(i);
}
}
return count;
}
public static int countmincoins(int n)
{
int t;
if(n<0)
{
t=Integer.MAX_VALUE-100 ;
}
if(n==0)
{
t= 0;
}
else
{
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=0;i<v.length;i++)
{
int temp=0;
temp=countmincoins(n-v[i])+1; //Stackoverflow error
a.add(temp);
}
t=findminimum(a);
}
return t;
}
public static void main(String args[])
{
System.out.println(countmincoins(100));
}
}
If you use recursion then you need to reach a condition to terminate the recursion. But in your code I do not seen any termination logic. Thats why, it get to infinite loop and StackOverflowException. In your code you use following code to terminate.
if(n==0)
{
t= 0;
}
But here n may not be zero. Becuase countmincoins(n-v[i]) do not ensure you to n will be 0.
Your code is infinite cause t will never be <0 or ==0 given that the values in the array and the condition (n - v[i] )+1, v[i] will always return the same value in every call to the method, therefore infinite recursion.
If your not restricted to using recursion the following would be much simpler:
public static int[] denominations = {25,10,5,1};
public static int minimumCoins(int amount){
int total = 0;
for(int denomination: denominations){
while(amount - denomination >= 0){
amount -= denomination;
total++;
}
}
return total;
}
public static void main(String args[])
{
System.out.println(minimumCoins(98));
}
I have written the code but it displays Stackoverflowerror message.
class Sum
{
int ans=0,temp,temp2;
int getsum(int no)
{
if(no>0)
{
temp=no % 10;
ans=ans + temp;
getsum(no/10);
}
else
{
return ans;
}
}
}
class recsum
{
public static void main(String args[])
{
Sum s=new Sum();
int no,len;
len=args.length;
if(len==0)
{
System.out.println("No argruments are given ! ");
}
else
{
no=Integer.valueOf(args[0]).intValue();
System.out.println("Sum of digits= " + s.getsum(no));
}
}
}
You are over-complicating things a lot in your code. Here is a simpler working example:
public static int getSum(final String[] args, final int index) {
if (index < args.length) {
return Integer.valueOf(args[index]) + getSum(args, index + 1);
} else {
return 0;
}
}
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("You need to provide numbers as arguments.");
}
final int sum = getSum(args, 0);
System.out.println("Sum: " + sum);
}
You are supposed to be recursive, this is in the getSum function, because it is calling itself with differing parameters.
In recursive functions, you always need to have an exit branch that causes the calling to stop.
As sums won't change if you add 0 this can be exploited for a very clean exit.
The Stack overflow is normally because you never bottom out of the recursion.
Change class Sum to this:
class Sum {
int ans = 0, temp = 0;
int getsum(int no) {
if((no/10)-.5 >= 1)
ans += getsum(no/10);
else
return ans;
}
}
I'm not completely sure if this will work, and I can't compile it right now. I think this is one way to do it, but again, I'm not completely sure.
Program: Write a program to use Command Line Arguments.
class Sumnum1
{
int i,t,num,sum=0;
void getData(String s)
{
num=Integer.parseInt(s);
}
int digitSum()
{
for(i=num;i>=1;i=i/10)
{
t=i%10;
sum=sum+t;
}
return sum;
}
public static void main(String arg[])
{
int ds=0;
Sumnum1 obj=new Sumnum1();
obj.getData(arg[0]);
ds=obj.digitSum();
System.out.println("sum of digit="+ds);
}
}
BY :ANKIT AGRAWAL (A.A.)