C Program to Print Digits Tower - Source Code and Output
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
- User Input: The program starts by prompting the user to enter the desired height of the digits tower.
- Calculating Dimensions: It then calculates the total number of digits needed for each row based on the height.
- Outer Loop (Rows): The outer
forloop iterates once for each row of the tower. - Inner Loop 1 (Spaces): An inner
forloop prints the leading spaces for each row, ensuring the tower is centered. - Inner Loop 2 (Digits): The second inner
forloop prints the digits for the current row. It uses the modulo operator (%) to cycle through the digits 0-9. - Newline: After each row is printed, a newline character (
) moves the output to the next line.
Running the Program
- Save: Save the code as a
.cfile (e.g.,digits_tower.c). - Compile: Compile the code using a C compiler (like GCC) from your terminal:
gcc digits_tower.c -o digits_tower - 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!
原文地址: https://www.cveoy.top/t/topic/RBs 著作权归作者所有。请勿转载和采集!