My assignment is to print out a triangular number's digits leading up to the final value in pyramid shape, but I can't for the life of me get it evenly spaced and centered, and I can't just use %6i
or something because it has to work for any number we put in. I've tried justification, using a separate variable to calculate spacing based on the user defined number, but none of it worked.
Our result should look like this image, using 15 as an example.
It's due by midnight, and we've been at it for days. My code is sort of long:
//Include the usual libraries
#include <stdio.h>
//Declare the main function
int main (void)
{
//Declare variables
int space, n, triNum, ast, num, triDisplay = 0, number = 1;
//Welcome the user to your program
printf("Welcome to Phase 1!\nThis program will display a triangular number of your choosing in 'graphical' format.\n");
//Prompt the user for the triangular number
printf("Enter the triangular number: ");
scanf("%i", &triNum);
//This loop keeps track of how many times the nested loops have run.
n = 1;
while(n<=triNum)
{
//This loop prints the spaces before the asterisks, and decreases the amount printed after each line.
space=n;
while(space>0, space<triNum)
{
printf(" ");
space++;
}//End of second loop
//This loop prints the asterisks and increases the amount printed by one for each line.
ast=n;
while(ast>0)
{
printf("* ");
ast--;
}//End of third loop
printf("\n") ;
n++;
}//End of first loop
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//This loop is identical to the first loop, but is used to display a different set of loops
n = 1;
while(n<=triNum)
{
space=n;
while(space>0, space<triNum)
{
printf(" ");
space++;
}
//This loop prints the number associated with each asterisk in triangle format
num = 1;
while(num>0, num<=n)
{
printf("%i ",number);
number++;
num++;
}
n++;
printf("\n");
}
//This loop calculates the actual value of the triangular number
n=1;
while(n<=triNum)
{
triDisplay += n;
n++;
}
printf("\nThe triangular number of %i is %i.\n", triNum, triDisplay);
//Thank the user for using your program
printf("Thank you for using this program! Have a nice day.\n");
//End function
return 0;
}
This is what ours currently looks like.