-3

Trying to output a string that has been assigned to an array, with different characters on each new line, eventually creating a right triangle. But I'm completely stuck. I believe some for loops should be involved to iterate over each character but I don't know how to increase the array index on each new line to output one character more than the line before.

This is a sketch that allowed me to visualize this:

string[0]
string[1] + string[2]
string[3] + string[4] + string[5]
string[6] + string[7] + string[8] + string[9]

For example, let's take into account this line of code: char string[50] = "Assignment";

The output desired would look like this:

A
s s
i g n 
m e n t

Any guidance would be appreciated.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Chris
  • 23
  • 2
  • Think of the pattern you want to produce. It starts with **one** character, then go to the next line and print the next **two** characters; next line and print **three** characters...1, 2, 3. How can you produce the numbers 1, 2, 3, etc, and for each number print that many characters from the string? Start with that, and build on top of it – smac89 Sep 08 '21 at 17:16
  • First create a program which prints just `*` to make the pyramid. Then create a *new* program, which prints the string one character per line. Then create a final program, which does what your assignment asks for. – hyde Sep 08 '21 at 18:24

2 Answers2

1

You can do it using only one while loop.

Here is a demonstrative program

#include <stdio.h>

void triangle_output( const char *s )
{
    size_t n = 1;
    size_t i = n;
    
    while ( *s )
    {
        if ( i-- == 0 )
        {
            putchar( '\n' );
            i = n++;
        }
        putchar( *s++ );
        putchar( ' ' );
    }
    
    if ( i != n - 1 ) putchar( '\n' );
}

int main(void) 
{
    char *s = "Assignment";
    
    triangle_output( s );
    
    return 0;
}

The program output is

A 
s s 
i g n 
m e n t 

Or the function can be rewritten the following way

void triangle_output( const char *s )
{
    size_t n = 1;
    size_t i = 0;
    
    while ( *s )
    {
        putchar( *s++ );
        putchar( ' ' );

        if ( ++i == n )
        {
            putchar( '\n' );
            i = 0;
            ++n;
        }
    }
    
    if ( i != 0 ) putchar( '\n' );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

This function will print the triangle. If the string have enough chars to print the whole last line it will print -.

void printTriangle(const char *s)
{
    size_t length = strlen(s), pos = 0;
    for(size_t line = 1; line < -1; line++)
    {
        for(size_t ch = 1; ch <= line; ch++)
        {
            if(pos < length) printf("%c", *s++);
            else printf("-");
            pos++;
        }
        printf("\n");
        if(pos >= length) break;
    }
}


int main(void)
{
    printTriangle("Assignment123");
}

https://godbolt.org/z/xxM1eEY6a

0___________
  • 60,014
  • 4
  • 34
  • 74