Mike Drek
Mike Drek

Reputation: 33

C: Hashes pyramid pattern

I need a program which prints the pattern below. Program must read the number of lines from user.

Example 1:

Input: 3

Output:

#
##
####

Example 2:

**Input: ** 5

Output

#
##
####
#######
###########

The code I have so far:

#include <stdio.h>

int main(int argc, char const *argv[])
{
   int n;
   scanf("%d", &n);
   int step = n;
   for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j+=step) {
         printf("#");
      }
      step--;
      puts("");
   }
   return 0;
}

Upvotes: 0

Views: 151

Answers (2)

Watachiaieto
Watachiaieto

Reputation: 422

You are doing great ;)

you actually have three issues:

The first issue is that you do not want to increment j by step.
The second issue is that you are not incrementing step in the right place.
The third is that the max value of j is NOT i

Upvotes: 2

4386427
4386427

Reputation: 44274

As far as I can see from your examples the pattern is:

Line 0: 1 #

Line 1: 2 # (i.e. 1 + 1 or "The number of # in previous line + this line number")

Line 2: 4 # (i.e. 2 + 2 or "The number of # in previous line + this line number")

Line 3: 7 # (i.e. 4 + 3 or "The number of # in previous line + this line number")

So you can use "The number of # in previous line + this line number" as the pattern in your code to find the number of # needed in the current line. Something like:

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int n;
    scanf("%d", &n);
    int limit = 1;                      // Limit for line 0
    for (int i = 0; i < n; i++) {
        limit += i;                     // Calculate limit for this line
        for (int j = 0; j < limit; ++j) {
            printf("#");
        }
        puts("");
    }
    return 0;
}

Output for n=7:

#
##
####
#######
###########
################
######################

Upvotes: 3

Related Questions