Yogeshwar Singh
Yogeshwar Singh

Reputation: 1425

Drawing a triangle with one loop (Revised)

The triangle should look like this

1
11
111
1111
11111
111111

the number of rows is entered by the user and then transforms to the function Note: Without arrays, must be with one loop(while or for) and not nested loops

the closest I got is a code with 2 loop (but can`t think about how to do it with less loops)

int i,k;
    for(i=1;i<=x;i++)
    {
        for(k=1;k<=i;k++)
        {
            printf("1");
        }
        printf("\n");
    }

The above question was asked by someone but it was marked as off topic I don't know why..? I came up with this solution tell me if it's correct or not?

int i=1,k=1;
    while (i<=x)
    {
        if(k<=i)
        {
            printf("1");
     k++;
     continue;
        }
   i++;
  k=1;
        printf("\n");
    }

thanks

Upvotes: 0

Views: 1364

Answers (2)

Weather Vane
Weather Vane

Reputation: 34585

Recursive solution, one loop, no arrays.

#include <stdio.h>

void liner(int line, int limit) {
    int i;
    if (line > limit)
        return;
    for(i=1; i<=line; i++)
        printf("1");
    printf("\n");
    liner (line + 1, limit);
}

int main() {
    int limit;
    printf ("Enter number of lines ");
    scanf ("%d", &limit);
    liner (1, limit);
    return 0;
}

Upvotes: 1

D3Hunter
D3Hunter

Reputation: 1349

You can replace loops(iteration) with recursion, try this(with one loop):

#include <stdio.h>

void draw(int depth)
{
    int i;
    if(depth <= 0) return;
    draw(depth-1);
    for(i = 0; i < depth; i++)
        printf("1");
    printf("\n");
}

int main()
{
    draw(5);
    return 0;
}

You can do it even without loop

#include <stdio.h>

void draw_num_char(int num)
{
    if(num <= 0) return;
    printf("1");
    draw_num_char(num-1);
}
void draw(int depth)
{
    int i;
    if(depth <= 0) return;
    draw(depth-1);
    draw_num_char(depth);
    printf("\n");
}

int main()
{
    draw(5);
    return 0;
}

Upvotes: 1

Related Questions