C Program to Generate a Digits Tower Pattern

This tutorial provides a C program that generates a unique 'digits tower' pattern. We'll walk you through the code and explain how it works.

The C Code

Here's the C program to print the digits tower pattern:

#include <stdio.h>

int main() {
    int height;
    printf('Enter the height of the digits tower: ');
    scanf('%d', &height);

    int numDigits = height * 2 - 1;

    for (int row = 1; row <= height; row++) {
        int numSpaces = height - row;
        int currentDigit = row;
        int digitCount = (row * 2) - 1;

        for (int space = 1; space <= numSpaces; space++) {
            printf(' ');
        }

        for (int digit = 1; digit <= digitCount; digit++) {
            printf('%d', currentDigit);
            currentDigit = (currentDigit + 1) % 10;
        }

        printf('
');
    }

    return 0;
}

How the Code Works

  1. User Input: The program starts by prompting the user to enter the desired height of the digits tower.
  2. Calculating Dimensions: It then calculates the total number of digits needed for each row based on the height.
  3. Outer Loop (Rows): The outer for loop iterates once for each row of the tower.
  4. Inner Loop 1 (Spaces): An inner for loop prints the leading spaces for each row, ensuring the tower is centered.
  5. Inner Loop 2 (Digits): The second inner for loop prints the digits for the current row. It uses the modulo operator (%) to cycle through the digits 0-9.
  6. Newline: After each row is printed, a newline character ( ) moves the output to the next line.

Running the Program

  1. Save: Save the code as a .c file (e.g., digits_tower.c).
  2. Compile: Compile the code using a C compiler (like GCC) from your terminal: gcc digits_tower.c -o digits_tower
  3. Run: Execute the compiled program: ./digits_tower

The program will ask for the height. After entering a number, you'll see the digits tower printed to your console.

This program demonstrates a creative way to manipulate loops and printing in C to produce interesting visual patterns. Experiment with different heights to see how the pattern changes!

C Program to Print Digits Tower - Source Code and Output

原文地址: https://www.cveoy.top/t/topic/RBs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录