-2

Based on user input(number of rows) to print fibonacci series in diamond pattern. The user will enter the number of rows and the output should contain those many rows printing the Fibonacci series

import java.util.*;

public class HelloWorld {
    public static void main(String []args) {
        Scanner sc = new Scanner(System.in);

        //Taking noOfRows value from the user
        System.out.println("Enter no of rows:");
        int noOfRows = sc.nextInt();

        //Initializing rowCount with 1
        int rowCount = 1;

        //Implementing the logic
        int previous = 0, prevtoprev;
        for (int i = noOfRows; i > 0; i--) {

            //Printing i*2 spaces at the beginning of each row
            for (int j = 1; j <= i*2; j++) {
                System.out.print(" ");
            }

            //Printing j value where j value will be from 1 to rowCount
            for (int j = 1; j <= rowCount; j++) {
                if (j%2 == 0) {
                    System.out.print("+");
                } else {
                    System.out.print(j);
                }
            }

            //Printing j value where j value will be from rowCount-1 to 1
            for (int j = rowCount-1; j >= 1; j--) {
                if (j%2 == 0) {
                    System.out.print("+");
                } else {
                    System.out.print(rowCount);
                }
            }

            System.out.println();

            //Incrementing the rowCount
            previous = rowCount;
            rowCount++;
        }
    }
}

Getting output as

enter image description here

Expected output:

Here “34” was split to place “4” into the next row to form a diamond and “144” is split to place “1” in the last row and remaining digit ‘44’ is discarded.

enter image description here

Girish
  • 2,196
  • 2
  • 18
  • 24
  • why few people giving negative check – Girish Nov 16 '16 at 08:27
  • What is the expected output? – Bijay Gurung Nov 16 '16 at 08:31
  • 1
    Please [edit] the question. Format your code properly by selecting it and clicking on the `{}` button. Explain what "diamond format" is and what your expected output is, and then *ask a question*. – RealSkeptic Nov 16 '16 at 08:31
  • How will a Fibonacci series formed a diamond pattern? It will form a triangle as the series grows. – TungstenX Nov 16 '16 at 08:35
  • @RealSkeptic added the expected output – Girish Nov 16 '16 at 09:08
  • But you removed your actual output and still didn't ask a question. It should probably be "I get this output instead. How can I print the correct numbers" or "How can I split the numbers in the middle" or something like that. – RealSkeptic Nov 16 '16 at 09:17
  • @Girish please have a look at [ask] and [mcve]. Your question isn't specific enough. Just keep the part of code which is necessary, explain the algorithm you want to implement and different outputs for different inputs. Then tell us what's the problem. – xenteros Nov 16 '16 at 09:19
  • @xenteros Based on "number of rows" that user enters need to print fibonacci series in diamond pattern – Girish Nov 16 '16 at 09:27
  • @RealSkeptic How to maintain fibonacci series in diamond pattern – Girish Nov 16 '16 at 09:28
  • @Girish [edit] your question and provide all the information there. Just check some good questions and then try to write a good question on yourself: [Question 1](http://stackoverflow.com/q/38716703/4723795), [Question 2](http://stackoverflow.com/q/39328351/4723795) – xenteros Nov 16 '16 at 09:29
  • About the problem itself - you should break it into several steps. (1) You are not producing the Fibonacci sequence at all. Start by a program that outputs the correct fibonacci sequence in one line. (2) Think about how to format it into a diamond, and what's the connection between the length of the sequence and the height of the diamond. (3) Combine the two steps. – RealSkeptic Nov 16 '16 at 09:53

2 Answers2

2

Here is some code for you. Try to understand it and modify it if necessary. It works only if the row number is odd and the row number is not larger than 23. Try to improve it by yourself.

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class NewClass {

    public static void main(String []args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of rows:");
        int noOfRows = sc.nextInt();
        while(noOfRows%2==0){
           System.out.println("Only an odd number can be inserted. Enter number of rows:");
           noOfRows = sc.nextInt(); 
        }
        String str = concatFibSeries(noOfRows*3);
        List<String> list = chopp(str,noOfRows);
        printDimondPattern(list);
    }
    // Formula for the n-th Fibonacci number
    static int nthFib(int n){
        return (int)( ( 1/Math.sqrt(5) )* ( (Math.pow( ( ( 1+Math.sqrt(5) )/2),n ) ) - (Math.pow( ( ( 1-Math.sqrt(5) )/2),n ) ) ) );    
    }
    // returns a string of all Fibonacci numbers upto the nth Fibonacci number concatenated with "+"
    static String concatFibSeries(int n){
        StringBuilder sb = new StringBuilder();
        for(int i= 1; i<=n; i++){
            sb.append(nthFib(i)).append("+");
        }
        return sb.toString();
    }
    // cuts the string returned by the method concatFibSeries(int n) into small chunks
    // returns a list of strings with list.size equal to given rows
    // the length of the strings beginns by one and increases by two on each step till the middle row is reached
    // and decreases by two till the end of rows is reached
    static List<String> chopp(String concatenatedString,int rows){
        List<String> list = new ArrayList<>();
        for(int i = 1, j = 1; i <= rows; i++, j=(i<= Math.ceil(rows/2.))? j+2 : j-2){
           list.add(concatenatedString.substring(0,j));
           concatenatedString = concatenatedString.substring(j);
           if (concatenatedString.startsWith("+")){
               concatenatedString = concatenatedString.substring(1);
           }
        }
        return list;    
    }
    // adds the required space before and after each string and prints the string
    static void printDimondPattern(List<String> list){
        for(int i = 0; i< list.size();i++){
            String str ="";
            for (int j = 0; j<(Math.abs(list.size()-Math.ceil(list.size()/2.)-i));j++){
                str +=" ";
            }
            System.out.println(str+list.get(i)+str);
        }
    }        
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28
0

I am able to print the fibonacci series based on number of rows But still that's not the correct one, I need to arrange in diamond pattern with "+" sign and also discard the extra digits if it doesn't fit.

    import java.util.*;
    public class HelloWorld{

     public static void main(String []args){
         meth();
     }
     public static int meth(){
         int row, column, first_no = 1, second_no = 1, sum = 1;

        Scanner sc = new Scanner(System.in);
        //Taking noOfRows value from the user
        System.out.println("Enter no of rows:");
        row = sc.nextInt();

        for (int i = 1; i <= row; i++) {
            for (column = 1; column <= i; column++) {
                if (i == 1 && column == 1) {
                System.out.printf("%"+(row)+"d\t",second_no);
                continue;
         }
         System.out.printf(" %d ", sum);

         //Computes the series
         sum = first_no + second_no;
         first_no = second_no;
         second_no = sum;
      }
      System.out.println("");
   }
   return 0;
}
}

Input:4

Getting output as:

enter image description here

Girish
  • 2,196
  • 2
  • 18
  • 24