GESP C++ Level 2 Exercise luogu-T259140: Triangle

GESP Level 2 exercise, multi-layer loop practice, difficulty ★✮☆☆☆.

luogu-T259140 Triangle

Problem Requirements

Problem Description

Given , please output a right-angled triangle with the length of the right angle being . All numbers are composed of digits, and if there are not enough digits, leading should be added.

Tip: Use <span>printf("%02d",x);</span> to automatically add leading zeros for single-digit numbers.

Input Format

Input a positive integer .

Output Format

Output the numeric right-angled triangle as required by the problem.

Sample Input #1

5

Sample Output #1

0102030405
06070809
101112
1314
15

Data Range

The data guarantees that .

Problem Analysis

This is a simple mathematical problem, and we can use two nested loops to print the numeric right-angled triangle. The outer loop controls the number of rows, while the inner loop controls the number of digits in each row. We use a variable b to represent the current number, and after printing a number, b is incremented by 1. When b is a single-digit number, we use the printf function to print it, keeping two decimal places. When b is a two-digit number, we print it directly.

Example Code

#include <cstdio>
#include <iostream>
using namespace std;
int main() {
    int a; // Define variable a
    cin >> a; // Input a
    int b = 1; // Define variable b and initialize to 1
    for (int i = a; i > 0; i--) { // Outer loop, controls the number of rows
        for (int j = 1; j <= i; j++) { // Inner loop, controls the number of digits in each row
            if (b / 10 == 0) { // If b is a single-digit number
                printf("%.02d", b); // Output b, keeping two decimal places
            } else { // If b is a two-digit number
                printf("%d", b); // Output b directly
            }
            b++; // Increment b
        }
        cout << endl; // New line
    }
    return 0; // Return 0, indicating normal program termination
}

For GESP level outlines, real exam explanations, knowledge expansion, and practice lists, see:

[Top][GESP] C++ Certification Learning Resource Summary

luogu-” series problems can be evaluated online at Luogu Problem Bank.

bcqm-” series problems can be evaluated online at Programming Enlightenment Problem Bank.

Leave a Comment