Menu
Coddy logo textTech

Number Pattern

Part of the Fundamentals section of Coddy's Java journey — lesson 71 of 73.

When creating patterns like pyramids, we often need to create strings with repeated characters. Here's a useful technique to create such strings:

String str = new String(new char[10]).replace("\0", "a");

str will hold "aaaaaaaaaa"

Let's break down how this works: 

  1. new char[10] creates an array of 10 characters, each initialized to '\0' (null character)
  2. new String(new char[10]) converts this array to a string of 10 null characters
  3. replace("\0", "a") replaces each null character with 'a' 

It is important to write "\0" and not “0”

challenge icon

Challenge

Easy

Each test case has one input - an odd whole number.
Your task is to print n - pyramid using *, here are some examples:

1 - pyramid

*

5 - pyramid

*
***
*****

7 - pyramid

*
***
*****
*******

Input

  • odd integer n from user
  • 1 <= n < 1000

Tips

  • Try starting from the small triangles
  • Check the hint if you are stuck ;)

n represents the number of  * in the bottom row

Cheat sheet

To create strings with repeated characters in Java:

String str = new String(new char[10]).replace("\0", "a");

This creates a string with 10 'a' characters: "aaaaaaaaaa"

How it works:

  1. new char[10] creates an array of 10 characters, each initialized to '\0' (null character)
  2. new String(new char[10]) converts this array to a string of 10 null characters
  3. replace("\0", "a") replaces each null character with 'a'

Important: Use "\0" (null character) and not "0" (zero character)

Try it yourself

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals