Number pyramind, with recursive method. Java Beginner - java

I am a new member here, and I am also a beginner in JAVA. The thing that seems the most abstract to me is recursion, and so I have some difficulties finishing a program that should have this output if we write 3 for example:
1
12
123
12
1
Or if we write 5 for example it should print out this:
1
12
123
1234
12345
1234
123
12
1
And I can do this program with for loop, but I have to use recursion, and here is what I have done so far:
public class Aufgabe3 {
private static void printSequenz(int n) {
if(n<1){
return;
}
printMany(n);
printSequenz(n-1);
}
private static void printMany(int n){
for(int i=1;i<=n;i++){
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}
}
I would be really happy if someone would help me :).

You need to implement two recursive functions:
void printLoToHi(int n)
{
if (n < 1)
return;
printLoToHi(n-1);
printMany(n);
}
void printHiToLo(int n)
{
if (n < 1)
return;
printMany(n);
printHiToLo(n-1);
}
Then, you need to call them sequentially:
printSequenz(int n)
{
printLoToHi(n);
printHiToLo(n-1); // -1 in order to avoid printing the highest twice
}
Or in a more "symmetrical manner":
printSequenz(int n)
{
printLoToHi(n-1); // print lowest to second highest
printMany(n); // print the highest
printHiToLo(n-1); // print second highest to lowest
}

You could do it like this:
private static void printSequenz(int n) {
printSequenz(1,n, true);
}
private static void printSequenz(int current, int total, boolean goingUp) {
if(!goingUp && current<1){
return;
}
printMany(current);
if(current+1>total){
goingUp=false;
}
if(goingUp){
printSequenz(current+1,total,goingUp);
} else {
printSequenz(current-1,total,goingUp);
}
}
private static void printMany(int n) {
for (int i = 1; i <= n; i++) {
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}

public class Test {
public static void main(String args[]) {
int seq = 6;
for(int i=1; i<=seq; i++) {
System.out.println("");
int low =seq-(seq-i);
printIncreasing(i,low);
}
for(int i=seq-1; i>=1; i--) {
System.out.println("");
int low = seq-i;
printDecreasing(i,low);
}
}
public static void printIncreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
public static void printDecreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
}

Related

How to print numbers from 1 to n using recrsion in java

public static void increase(int N){
int a = 1;
if(b <= N) {
System.out.print(a + " ");
a++;
} else {
increase(N);
}
}
I can see the problem with this approach that the int a gets initialized to 1 every time the code goes for a recursive call. Can anyone suggest the correct solution?
public static void main(String[] args) {
increase(10,1);
}
private static void increase(int N,int begin){
if(begin <= N){
System.out.print(begin+" ");
begin=begin+1;
increase(N,begin);
}
return;
}
You have to create one additional private method to count current value.
public static void increase(int N) {
increase(1, N);
}
private static void increase(int a, int N) {
if (a <= N) {
if (a > 1)
System.out.print(' ');
System.out.print(i);
increase(a + 1, N);
}
}
You can just put a outside the function:
// I don't know your class
private a = 1;
static void increase(int N){
int a = 1;
if(b <= N){
System.out.print(a+" ");
a=a+1;
}
else
{
increase(N);
}
}
static void increase(int N, int a){
if (a>N) return;
System.out.print(a+" ");
a=a+1;
increase(N,a);
}
//example call from static context print 1-100
increase(100,1);

Wrong amount of lines in printTriangle?

I've been doing a MOOC.fi Java course and it comes along quite well, except the Christmas Tree part. It works as intended in the output, but the system won't accept it and I don't know why.
I get this error:
when printTriangle(1) was called, wrong amount of lines was printed expected:<1> but was:<2>
Here's the code:
public class AdvancedAstrology {
public static void printStars(int number) {
for(int i = 0; i < number; i++){
System.out.print("*");
}
System.out.println();
}
public static void printSpaces(int number) {
while(number > 0){
System.out.print(' ');
number--;
}
}
public static void printTriangle(int size) {
int star = 0;
while(size > 0){
printSpaces(size--);
printStars(star++);
}
}
public static void christmasTree(int height) {
int h = height -1;
int stand = height - 2;
int s = 1;
while(height > 0){
printSpaces(h);
printStars(s);
s+=2;
h--;
height--;
}
printSpaces(stand);
printStars(3);
printSpaces(stand);
printStars(3);
}
public static void main(String[] args) {
// The tests are not checking the main, so you can modify it freely.
printTriangle(5);
System.out.println("---");
christmasTree(4);
System.out.println("---");
christmasTree(10);
}
}
You're doing post increment, that's why in star is being passed as 0 in first iteration.
public static void printTriangle(int size) {
int star = 0;
while(size > 0){
printSpaces(size--);
printStars(star++); //Here. change it to ++star
}
}

are there any fresh ideas for a recursive function printing square pattern?

i have a question where i need to do a recursive function getting int and doing star pattern of a square like if i insert 4 into the function it will give me:
****
****
****
****
so i made this recursion and i want to shrink my idea into one function what can you suggest to improve my design, thanks.
static int count = 0;
public static void rect(int num){
if(count<=0)
return;
if(count !=0 && num>0){
for(int i =0; i<num;i++){
System.out.print('*');
}
System.out.println();
count--;
rect(num);
}
}
public static void SetCount(int num){
count = num;
rect(num);
}
public static void main(String[] args) {
int i = 6;
SetCount(i);
}
You can eliminate the SetCount method and the second if check, something like this would work as well :
static int count = 0;
public static void rect(int num) {
if (count <= 0)
return;
for (int i = 0; i < num; i++) {
System.out.print('*');
}
System.out.println();
count--;
rect(num);
}
public static void main(String[] args) {
count = 4;
rect(count);
}
One argument, the size of the square. No external variables:
class Homework {
public static void square(int side) {
if (side > 0) {
for (int i = 0; i < side; i++) {
square(-side);
}
} else if (side < 0) {
System.out.print('*');
square(side + 1);
} else {
System.out.println();
}
}
public static void main(String[] args) {
square(5);
}
}
Your solution, and others offered so far, are all recursive on the rows of the square and iterative on the columns. This solution inverts that -- it's recursive on the columns and iterative on the rows.
OUTPUT
> java Homework
*****
*****
*****
*****
*****
>
import java.util.*;
import java.lang.*;
import java.io.*;
class Check{
static void rect(int num,int count){
if(count<=0)
return;
if(count !=0 && num>0){
for(int i =0; i<num;i++){
System.out.print('*');
}
System.out.println();
count--;
rect(num,count);
}
}
public static void main(String[] args) {
int i = 6;
rect(i,i);
}
}
Instead of using a class variable count and setting it again and again. Use two paramters for the recursive function. "num" to print stars num times in a single row and "count" to keep track of number of rows.

printStars method with recursion

Here are my instructions:
Write a recursive method called printStar(int n) which will print the following when n=4:
****
***
**
*
*
**
***
****
This is what I did so far:
public class Stars{
public static void main (String[] args){
printStars(4);
}
public static void printStars(int count){
if (count==0){
System.out.println("");
}
else{
System.out.print("*");
printStars(count-1);
}
}
}
My attempt only prints one line of the given number of stars. I don't know how to print multiple lines with only one call of the method. Any help is appreciated.
This one uses tail recursion, is split into helper function, and uses loop only to get the character as required.
public class JavaR {
public static void main(String[] args) {
System.out.println(star(4, new StringBuilder()));
}
public static StringBuilder star(int times, StringBuilder builder) {
return getStars(times, builder, times);
}
public static StringBuilder getStars(int currentIteration, StringBuilder builder, int times) {
if (currentIteration < -1 * times) return builder;
else if (currentIteration != 0) {
builder.append(getNTimes(Math.abs(currentIteration)));
return getStars(currentIteration - 1, builder, times);
} else {
return getStars(currentIteration - 1, builder, times);
}
}
public static String getNTimes(int count) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; i++) {
builder.append("*");
}
return builder.append("\n").toString();
}
}
Your program is incorrect, see the below program and analyze it -
public class Stars{
public static void main (String[] args){
printStars(4);
}
public static void printStars(int count){
if (count==0){
// System.out.println("");
}
else{
int tempCount = count;
while(tempCount>0){
System.out.print("*");
tempCount--;
}
System.out.println();
printStars(count-1);
while(tempCount<count){
System.out.print("*");
tempCount++;
}
System.out.println();
}
}
}
Explanation - I am using two while loops to print stars, first to print the start in asc order and second to print in reverse order. Using variable tempCount to get the current counter.
Try this
public static void printStars(int count){
if (count == 0){
return;
}
printStarNTimes(count);
printStars(count-1);
printStarNTimes(count);
}
private static void printStarNTimes(int n) {
for (int i = 0; i < n; i++) {
System.out.print("*");
}
System.out.println();
}
Logic is in printing star count times in the current call and when the recursive call returns.
The method needs information about the max number of *, as well as direction (is number of * increasing or decreasing)
Since the requested method signature includes only one argument, you have a few alternatives to define the additional needed information:
Use a partially recursive method like in this and this answers, or use a helper method:
public static void printStars(int count){
printStars(count, count, -1);
}
public static void printStars(int count , int max, int increment){
for(int i =0; i< count; i++) {
System.out.print("*");
}
count += increment;
if(count ==0 ) { //lower limit reached
increment = -increment;
}else {
System.out.println("");
}
if (count > max){ //upper limit reached
return;
}
printStars(count, max, increment);
}

Java recursion to find prime factors doesn't work

I am trying to get all prime factors of a number. The for loop should work until it finds the match and it should break and jump to the next if statement which checks if number is not equal to zero.
public class Factor {
public static ArrayList <Integer> HoldNum = new ArrayList();
public static void main(String[]args){
Factor object = new Factor();
object.Factor(104);
System.out.println(HoldNum.get(0));
}
public static int Factor(int number){
int new_numb = 0;
int n=0;
for( n = 1; n < 9; n++) {
if (number % n == 0) {
HoldNum.add(n);
new_numb = number/n;
break;
}
}
System.out.println(new_numb);
if(new_numb < 0) {
HoldNum.add(new_numb);
return 1;
} else {
return Factor(new_numb);
}
}
}
There are at least three errors :
As okiharaherbst wrote, your counter is not incremented.
you start your loop at 1, so yourval % 1 always equals to 0 and new_numb is always equals to your input val, so you'll loop endlessly on 104.
new_numb will never be lesser than 0.
You asked for a recursive solution. Here you go:
public class Example {
public static void main(String[] args) {
System.out.println(factors(104));
}
public static List<Integer> factors(int number) {
return factors(number, new ArrayList<Integer>());
}
private static List<Integer> factors(int number, List<Integer> primes) {
for (int prim = 2; prim <= number; prim++) {
if (number % prim == 0) {
primes.add(prim);
return factors(number / prim, primes);
}
}
return primes;
}
}
The code is not bullet-proof, it is only a quick-and-dirty example.
Java implementation...
public class PrimeFactor {
public int divisor=2;
void printPrimeFactors(int num)
{
if(num == 1)
return;
if(num%divisor!=0)
{
while(num%divisor!=0)
++divisor;
}
if(num%divisor==0){
System.out.println(divisor);
printPrimeFactors(num/divisor);
}
}
public static void main(String[] args)
{
PrimeFactor obj = new PrimeFactor();
obj.printPrimeFactors(90);
}
}

Categories