Print star pattern count

Print star pattern count

Easy Java Control Flow 23 views
Explanation Complexity

Problem Statement

Task: return total stars printed in a triangle of height n (1+2+...+n).

Input Format

An integer n (height of the triangle).

Output Format

An integer: total number of stars printed.

Example

4
10

Constraints

• n ≥ 1

Concept Explanation

A triangle of height n prints:
1 + 2 + 3 + ... + n stars.
This is the sum of first n natural numbers.

Step-by-Step Explanation

1.Read integer n.

2.Initialize total = 0.

3.Loop i from 1 to n.

4.Add i to total.

5.After loop ends, return total.

Concept Explanation

A triangle of height n prints:
1 + 2 + 3 + ... + n stars.
This is the sum of first n natural numbers.

Step-by-Step Explanation

1.Read integer n.

2.Initialize total = 0.

3.Loop i from 1 to n.

4.Add i to total.

5.After loop ends, return total.

Input / Output Format

Input Format
An integer n (height of the triangle).
Output Format
An integer: total number of stars printed.
Constraints
• n ≥ 1

Examples

Input:
4
Output:
10

Example Solution (Public)

Java
static long totalStars(int n){return 1L*n*(n+1)/2;}

Official Solution Code

static long totalStars(int n){return 1L*n*(n+1)/2;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.