'What is wrong with my code? Should I be adopting the method I found online?
Objective: Ask user for input height, and print pyramid
Code I wrote:
for(i = 1; i <= height; i++)
{
for (j = height-1; j >= 1; j--)
{
printf ("#");
}
printf ("\n");
{
Code I found online:
for(i = height; i >= 1; i++)
{
for (j = 1; j <=i; j++)
{
printf ("#");
}
printf ("\n");
{
It should look something like this:
###
##
#
Solution 1:[1]
Kinda like this?
#include <stdio.h>
#include <string.h>
int main(void) {
int height = 7;
char blocks[2*height];
((char*)memset(blocks, '#', 2*height-1))[2*height-1] = '\0';
for(int i=0; i<height; ++i)
{
printf("%*.*s\n", height+i, 2*i+1, blocks);
}
return 0;
}
Result:
Success #stdin #stdout 0s 5472KB
#
###
#####
#######
#########
###########
#############
Solution 2:[2]
Based on the sample output you provided:
#include <stdio.h>
#include <string.h>
int main(void) {
int height = 7;
char blocks[height+1];
((char*)memset(blocks, '#', height))[height] = '\0';
for(int i=0; i<height; ++i)
{
printf("%.*s\n", height-i, blocks);
}
return 0;
}
Result:
Success #stdin #stdout 0s 5520KB
#######
######
#####
####
###
##
#
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | abelenky |
Solution 2 | abelenky |