function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ritik DwivediRitik Dwivedi 

How can we write the Apex code of following pattern ?

1
12
123
1234
12345
123456
Best Answer chosen by Ritik Dwivedi
Vanisha_GuptaVanisha_Gupta
Hi Ritik,

My bad, i thought u want numbers like 1, 1,2, 1,2,3
In that case you can do like this :
public class Pattern {
 	Integer i,j;
    String pattern='';
    public void pattern_12(){
        for(i=1;i<5;++i){
           for (j = 1; j <= i; ++j) {
               pattern+=j; 
       	    }
     	pattern+='\n';       
     	}
        System.debug('Pattern \n'+pattern);
}
}

User-added image

I hope it works well for you. 

Thanks!

All Answers

Vanisha_GuptaVanisha_Gupta
Hi, 

I am able to pattern in this way: Debugs you can check, with following code: 
public class Pattern {
     Integer i,j;
    public void pattern_12(){
        for(i=1;i<5;++i){
                  for (j = 1; j <= i; ++j) {
                System.debug(' '+j);
        }
            System.debug('\n');
    }
}
}

User-added image

Thanks!
Ritik DwivediRitik Dwivedi
Hi vanisha 
but i want write code this pattern
my code should display outputin this pattern .

1
12
123
1234
12345
Vanisha_GuptaVanisha_Gupta
Hi Ritik,

My bad, i thought u want numbers like 1, 1,2, 1,2,3
In that case you can do like this :
public class Pattern {
 	Integer i,j;
    String pattern='';
    public void pattern_12(){
        for(i=1;i<5;++i){
           for (j = 1; j <= i; ++j) {
               pattern+=j; 
       	    }
     	pattern+='\n';       
     	}
        System.debug('Pattern \n'+pattern);
}
}

User-added image

I hope it works well for you. 

Thanks!
This was selected as the best answer
Ritik DwivediRitik Dwivedi
Thank you so much Vanisha 

one last thing i want to  ask 
what is this '\n' ?

and last thing 

i want display number pattern in this following way 

    1
   12
  123
 1234
12345

like pyramid format 
how can i write apex code ?
 
Vanisha_GuptaVanisha_Gupta
\n means next line.

this is an escape sequence (Refer this : https://www.javatpoint.com/escape-sequence-in-c)

For Pyramid:
refer these URL for different patterns -  https://www.programiz.com/java-programming/examples/pyramid-pattern understand the logic and convert it to apex code.

Logic is same in all OOP languages be it Apex or Java. Let me knw if help needed in this.