Home > Enterprise >  Problem with logic of this pattern problem
Problem with logic of this pattern problem

Time:10-10

Here is the question. I have to print this pattern eg For n = 5

For n = 5 
****1
***232
**34543
*4567654
567898765

I have written logic for this problem but I am not able to solve it. I can't make the last pattern print i.e. the decrease one 2 4,3 5,4

Here's my pattern For n = 5
****1
***232
**34544
*4567666
567898888    

Can anyone help me out and tell what's wrong with my logic. How to fix it

My code down below

import java.util.Scanner;
import java.lang.*;
public class Main {
    public static void main(String[] args) {

        solve();
    }





    public static void solve(){
        int n;
        Scanner obj = new Scanner(System.in);
        n = obj.nextInt();

        for(int row =1;row<=n;row  ){
            int  ans1 =  row;
            int spaces =1;
            
            for( spaces = 1;spaces<=n-row;spaces  ){
                System.out.print("*");

            }
            for (int pattern01 = 1; pattern01<=row;pattern01  ){
                System.out.print(ans1);
                ans1 = ans1  1;
            }

            for ( int pattern2 = 1 ; pattern2<=row-1; pattern2  ){
                ans1= 2*row-2;
                System.out.print(ans1);
                ans1--;


            }

        System.out.println();

        }

    }

}

CodePudding user response:

The issue you are having is that you are not decrementing 'ans1' correctly. If you are not sure how to use the debugger then observe your output through the console with print-out statements. Specifically the 3rd loop when 'ans1' is supposed to count backwards. Also, keep in mind the value of 'ans1' after you exit the second for-loop.

This is your second loop when you start to count up from row number variable. You increment 'ans1' by 1 each iteration.

for (int pattern01 = 1; pattern01 <= row;pattern01  )   {
   System.out.print(ans1);
   ans1 = ans1   1;
}

One thing to consider is that you are incrementing 'ans1' and what is the value of it before you enter your third loop to decrement? You need to do something here before you enter the loop and start printing.

Also, in your third loop you are not decrementing correctly. You should be counting backwards, or rather just decrementing by 1.

for(int pattern2 = 1;pattern2 <= row-1; pattern2  ){
   ans1= 2*row-2; // Your focus should be here, does this look right? Do you need it?
   System.out.print(ans1); // You should decrement first and then print
   ans1--; // this is correct, but in the wrong spot
}

I know you can pull it off :) You got this.

  • Related