Follow on Facebook

Like and Share on Facebook

Wednesday, December 17, 2014

Program for printing pattern 1 31 531 7531 97531 in Java Using Scanner

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++) {
            int currentNum = 2 * i - 1;
            for (int j = 1; j <= i; j++) {
                System.out.print(currentNum + " ");
                currentNum = currentNum - 2;
            }
            System.out.println();
        }
    }

}

Here is a sample output.
Enter n: 5 

1
 3 1
 5 3 1
 7 5 3 1
 9 7 5 3 1

No comments:

Post a Comment