Java For Loop into Recursive function - java

public class For {
public static void main(String[] args){
for(int i=2; i<=1024; i *= 2){
System.out.println("Count is: " + i);
}
}
public class While {
public static void main(String[] args){
int i = 1;
while (i < 1024) {
i *= 2;
System.out.println("Count is: " + i);
}
}
public class DoWhile {
public static void main(String[] args){
int i = 1;
if (i < 1024) {
do { i*=2;
System.out.println("Count is: " + i);
} while (i < 1024);
}
}
How would one convert the for loop/while loop so it does the same thing, but using a recursive function?

Like so:
public class Recursive {
public void r(int i) {
if (i < 1024) {
i *= 2;
System.out.println("Count is: " + i);
r(i);
}
}
public static void main(String[] args) {
Recursive r = new Recursive();
r.r(1);
}
}

Take the loop of main and put it in its own function with an argument int i. In that function, rewrite the loop to
If the loop condition is false (i >= 1024), then return
Else, recursive call with argument i*2.
Call the function with argument 1 or 2, depending on which of your programs you're rewriting (they don't entirely match).

Recurrent loop can look like this:
class Main
{
public static void main(String[] args){
RecWhile(1);
}
public static void RecWhile(int i) {
if (i < 1024) {
i = i*2;
System.out.println("Count is: " + i);
RecWhile(i);
}
}
}

public class Test1 {
public static void main(String[] args) {
Test1 mainFunc = new Test1();
int[] arr = {1,2,4,3,5,6};
int start=0;
int end=arr.length;
mainFunc.callRecursiveFun(start, end, arr);
}
public int callRecursiveFun(int start, int end, int[] arr) {
int arrLen = end;
if(arrLen == 0) {
return 0;
} else {
System.out.println("Loop Index at "+start +": "+arr[start]);
}
return callRecursiveFun(start+1, end-1, arr);
}
}

Related

Connecting a variable in the main method with another method Java

The method should return true if the argument is even, or
false otherwise. The program’s main method should use a loop to generate 100 random integers. It should use the isEven method to determine whether each random number is even, or odd. All this is done!!!
This is the part where I can't figure it out!
When the loop is finished, the program should display the number of even numbers that were generated, and the number of odd numbers.
This is my code:
import java.util.Random;
public class EvenOdd
{
public static void main(String[] args)
{
Random random = new Random();
int randomInteger = 0;
for(int i = 0; i < 100; i++){
randomInteger = random.nextInt();
System.out.println("Random Integer: " + randomInteger);
EvenOdd(randomInteger);
}
}
public static void EvenOdd(int x)
{
int oddNumbers = 0;
int evenNumbers = 0;
if ((x % 2) == 0)
{
System.out.println("Even");
evenNumbers++;
}
else
{
System.out.println("Odd");
oddNumbers++;
}
}
}
Try with this:
public static void main(String[] args)
{
Random random = new Random();
int randomInteger = 0;
int oddNumbers = 0;
int evenNumbers = 0;
for(int i = 0; i < 100; i++){
randomInteger = random.nextInt();
System.out.println("Random Integer: " + randomInteger);
if(evenOdd(randomInteger)) evenNumbers++;
else oddNumbers++;
}
System.out.printf("Even numbers: %d - Odd numbers: %d", evenNumbers, oddNumbers);
}
public static boolean evenOdd(int x)
{
if ((x % 2) == 0)
{
System.out.println("Even");
return true;
}
else
{
System.out.println("Odd");
return false;
}
}
Your original approach doesn't work because you initialize to 0 the oddNumbers and evenNumbers variables everytime you call the method.
Define oddNumbers, evenNumbers variables as static class variables and after the loop you can print these 2 value.
Java is not JavaScript. Also, it does not have the ability of C++ as "Static variables in functions".
Variables declared inside a method are local. Variables initialization occurs every time your code reaches a variable definition inside the method and destroyed after exiting from the method.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
So you have such variants:
1) Count numbers inside your main method and return indicator from the utility method.
1.1) boolean
public static boolean isEven(int x){
return (x % 2) == 0;
};
1.2) enum
private enum NumberType {
EVEN,
ODD
}
public static NumberType getNumberType (int x) {
if ((x % 2) == 0) {
return NumberType.EVEN;
} else {
return NumberType.ODD;
}
};
2) Make your variables static:
public class EvenOdd {
private static int evenNumbersCount = 0;
private static int oddNumbersCount = 0;
public static void main(String[] args) {
// your code
}
public static void countNumberType (int x) {
if ((x % 2) == 0) {
++evenNumbersCount;
} else {
++oddNumbersCount;
}
}
}
3) In some sophisticated situations you will need to pass container to your method:
public class EvenOdd {
private static final String EVEN = "even";
private static final String ODD = "odd";
public static void main(String[] args) {
// initialize container
Map<String, Integer> evenOddCounts = new HashMap<>(2, 1);
evenOddCounts.put(EVEN, 0);
evenOddCounts.put(ODD, 0);
Random random = new Random();
int randomInteger = 0;
for (int i = 0; i < 100; i++) {
randomInteger = random.nextInt();
countNumberType(evenOddCounts, randomInteger);
}
System.out.println(evenOddCounts.toString());
}
public static void countNumberType(Map<String, Integer> counts, int x) {
if ((x % 2) == 0) {
counts.compute(EVEN, (numberType, count) -> ++count);
} else {
counts.compute(ODD, (numberType, count) -> ++count);
}
}
}

How to find the largest integer (n), such that n^3 < 12,000, using a while loop

This is what I have so far. The idea is it's supposed to increase n until n^3 is less than 12000, and print out n at the highest integer below 12k.
public static void main(String[] args) {
int n = 0;
int nCubed = (int) (Math.pow(n, 3));
while (nCubed < 12000) {
n++;
}
System.out.println("The highest integer below 12000 is " +n);
}
}
You need to set the nCubed value each time in the loop:
public static void main(String[] args) {
int n = 0;
int nCubed = (int) (Math.pow(n, 3));
while (nCubed < 12000) {
n++;
nCubed = (int) (Math.pow(n, 3));
}
System.out.println("The highest integer below 12000 is " +(n-1));
}
public class newClass{
public static void main(String[] args) {
int largestValue=0;
int n=0;
while(Math.pow(n,3)<12000) {
if(n>largestValue)
largestValue=n;
n++;
}
System.out.println(largestValue);
}
}
public class Loops_13
{
public static void main(String[] args)
{
int n = 0;
while (Math.pow(n,3) < 12000)
{
if (Math.pow(n + 1,3) >= 12000)
break;
n++;
}
System.out.println("The largest integer n such that n^3 is less than 12,000 is " + n);
}
}
//Find the largest n
public class Pb5 {
public static void main(String[] args) {
int n=0;
while(true) {
if(n*n*n<12000) {
n++;
}
else
break;
}
System.out.println("The largest integer n less than 12000 is:: "+(n-1));
}
}

Need help in java search

Ok so I have to make a java program to search through an array using a binary search to find 45.3 but I am getting numerous class, interface, or enum expected errors starting after public static void main(String[] args) on line 23 can you guys help. thanks.
public class BinSearch
{
public static final int NOT_FOUND = -1;
public static int binarySearch(double[] arr, double x)
{
int low = 0;
int high = arr.length - 1;
int mid;
while (low <= high)
{
mid = (low + high) / 2;
if (arr[mid] > x)
{
high = mid - 1;
}
else if (arr[mid] < x)
{
low = mid + 1;
}
else
{
return mid+1;
}
}
return NOT_FOUND;
}
public static void main(String[] args)
{
int j,x;
double y,temp;
double[] arg= {-3.0, 10.0, 5.0, 24.0, 45.3, 10.5};
int i=0;
for (j = 1; j<arg.length;j++)
{
if(arg[i]>arg[j])
{
temp = arg[i];
arg[i] = arg[j];
arg[j] = temp;
}
i++;
System.out.print(arg[j-1]+",");
}
x = binarySearch(arg, 45.3);
System.out.print("45.3 found at ");
System.out.print(x);
}
}
It looks like you tried to use public class BinSearch as your main class. However, your parentheses enclose code before your main args.
public class MyClass {
//}// no bracket here
public static void main(String[] args) {
}
}
If you want to use a class to create Objects that use methods such as your public static final int , create a new class before.
class NewClass {
}
public class MyClass {
public static void main(String[] args) {
}
}

printing fibonacci number series without using loops

Is there a hack to print the first n fibonacci numbers without calling a loop
for(int i=1; i<n; i++)
System.out.println(computeF(n));
from the main program?
public static int computeF(int n)
{
if(n==0)
{
return 0;
}
else if(n==1)
{
return 1;
}
else
{
return computeF(n-1)+computeF(n-2);
}
}
There might be a way to print the intermediate values in recursion which will print the fibonacci numbers.
You could use tail recursion.
public class Fid
{
static int n1=0;
static int n2=1;
static int nex=0;
public static void fb(int n)
{
if(n<10)
{
if(n==0)
{
System.out.print(" "+n);
n++;
fb(n);
}
else
if(n==1)
{
System.out.print(" "+n);
n++;
fb(n);
}
else{
nex=n1+n2;
System.out.print(" "+nex);
n1=n2;
n2=nex;
n++;
fb(n);
}
}
}
public static void main(String[] args)
{
fb(0);
}
}
using recursion:-
class FibonacciRecursion
{
private static int index = 0;
private static int stoppingPoint = 9;
public static void main (String[] args)
{
int n1 = 0;
int n2 = 1;
fibonacciSequence(n1, n2);
}
public static void fibonacciSequence(int n1, int n2)
{
System.out.println("index: " + index + " -> " + n1);
// make sure we have set an ending point so this Java recursion
// doesn't go on forever.
if (index == stoppingPoint)
return;
// make sure we increment our index so we make progress
// toward the end.
index++;
fibonacciSequence(n2, n1+n2);
}
}
//Java program to print Fibonacci Series up to n terms given by user without using loop
import java.util.* ;
public class Fibonacci
{
public static void main(String[] arguments)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the no of terms :");
int no_of_terms= s.nextInt(),a=1,b=0,c=0,count=1;
System.out.print("0 ");//printing the first term
fib(no_of_terms,a,b,c,count);}
public static void fib(int no_of_terms,int a,int b,int c,int count)
{
//when value of count will be equal to the no of terms given by user the program will terminate
if (count==no_of_terms)
System.exit(0);
else
{
count++;
System.out.print(a+" ");
c=b;
b=a;
a=b+c;//calculating the next term
fib(no_of_terms,a,b,c,count);//calling the function again with updated value
}
}
}
import java.util.*;
public class Fibonacci{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a no.");
int n= sc.nextInt(),a=1,b=0,c=0;
num(n,a,b,c);
}
public static void num(int n,int a,int b,int c){
if(a<=n){
System.out.println(a);
c=b;
b=a;
a=b+c;
num(n,a,b,c);
}
}
}

Write a program to accept number from command line and display sum of digits in a number by using recursive funcion

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.)

Categories

Resources