Home > Back-end >  What is wrong with my code? Should I be adopting the method I found online?
What is wrong with my code? Should I be adopting the method I found online?

Time:04-29

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:

###
##
#

CodePudding user response:

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
      #
     ###
    #####
   #######
  #########
 ###########
#############

CodePudding user response:

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
#######
######
#####
####
###
##
#
  •  Tags:  
  • c
  • Related