123456
12345
1234
123
12
1
public class PatternExample{
public static void main(String[] args){
for(int i=6;i>=1;i--){
for(int j=1;j<i+1;j++){
System.out.print(j);
}
System.out.println();
}
}
}
source :
http://www.roseindia.net/answers/viewqa/Java-Beginners/16020-java-Question.html
or (int i = 5; i >=0; i--) {
for (int j = i; j > 0; j--) {
System.out.print(j);
}
System.out.println();
}
This is your code.
You have 2 variables, i and j.
Try placing yourself in place of compiler. Write i and j on register.
Now its written , int i=5. That means "i" is an integer with value 5 assigned to it and if you know the syntax of "FOR" loop, second condition limits the value and third conditions proceeds the loop.
So, coming in the nested loop, where j is equal to 5.
So, next line is printing j.
So we write the value of j on the register which is equal to 5 and just before that we check the condition(j>0 ?? yes? ok, proceed)
So your register has
5 written on it.
now, j-- . so j is 4. check again, is j>0? yes? ok, proceed,
54
now, j=3. check again..
543
now j =2, check again, ..
5432..
now, j=1, check agian..
54321
now j=0 , check, no? come out of the loop.
println() means taking the cursor to next line.
now i--.
so i=4.
and j =i therefore j=4.
and again start with printing j and checking..
so it will be
54321
4
then 54321
43... and so on. this is how program will work in very lay man's terms.
/**
* Prints the pattern in the post above.
*
* @author Gaurav
* @version 1.0
*/
public class pattern
{
public static void main(String[] args) {
for(int i = 1; i <= 5; i++){
for(int j = 1; j <=5; j++){
if(j < i){
System.out.print(i);
}
else{
System.out.print(j);
}
}
System.out.println();
}
}
}
/**
* Prints the above mentioned pattern
*
* @author Gaurav <Gaurav@wjunction.com>
* @version 1.0
*/
public class PatternwJ
{
public void display() {
int n = 5;
while(n >= 1){
int k = n;
while(k >= 1){
System.out.print(k);
k--;
}
System.out.println();
n--;
}
}
}
public class oddeven {
public static void main(String[] args){
System.out.println("Even numbers: ");
for(int a=1;a<=50;a++){
if(a%2 == 0){
System.out.println(a);
}
}
System.out.println("Odd numbers: ");
for(int a=51;a<=100;a++){
if(a%2 == 1){
System.out.println(a);
}
}
}
}
if a<50:
if a%2 == 0:
print a
else:
if a%2 == 1:
print a
/**
* Prints the above mentioned pattern
*
* @author Gaurav <Gaurav@wjunction.com>
* @version 1.0
*/
public class oddeven
{
public static void main(String[] args){
for(int i = 1; i <= 100; i++) {
if(i <= 50 && i % 2 == 0) {
System.out.println(i);
}
else if(i > 50 && i % 2 == 1){
System.out.println(i);
}
}
}
}