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:
new char[10]creates an array of10characters, each initialized to'\0'(null character)new String(new char[10])converts this array to a string of10null charactersreplace("\0", "a")replaces each null character with 'a'
It is important to write
"\0"and not“0”
Challenge
EasyEach 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
nfrom user - 1 <=
n< 1000
Tips
- Try starting from the small triangles
- Check the hint if you are stuck ;)
nrepresents 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:
new char[10]creates an array of 10 characters, each initialized to'\0'(null character)new String(new char[10])converts this array to a string of 10 null charactersreplace("\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();
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else