Follow on Facebook

Like and Share on Facebook

Showing posts with label java pattern. Show all posts
Showing posts with label java pattern. Show all posts

Thursday, December 18, 2014

Java Programs to print pattern 12345 22345 33345 44445 55555




import java.util.Scanner;


public class Pattern {


    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter n: ");

        int n = scanner.nextInt();

        for (int i = 1; i <= n; i++) {

            for (int j = 1; j <= n; j++) {

                if (j <= i) {

                    System.out.print(i + " ");

                } else {

                    System.out.print(j + " ");

                }

            }

            System.out.println();

        }

    }

Output:

12345
22345
33345
44445
55555

Java Programs to print pattern 1 10 101 1010 10101





Java Programs to print pattern 1 10 101 1010 10101


The outer loop counter i ranges from 1 to n. i is used to keep track of line number. Line i contains i numbers. So, the inner loop counter j ranges from 1 to i. If j is odd, we print 1, else we print 0.

import java.util.Scanner;

public class Pattern {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = scanner.nextInt();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                if (j % 2 == 1) {
                    System.out.print("1 ");
                } else {
                    System.out.print("0 ");
                }
            }
            System.out.println();
        }
    }

}

Enter n: 5
1
1 0
1 0 1
1 0 1 0
1 0 1 0 1