Increasing list in c

Asked

Viewed 82 times

-2

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int total = 10;
    char letra = '*';

    char *retorno;
    retorno = (char *) malloc(total + 1);

    for (int i=0; i<total; i++) {
      retorno[i] = letra;
      retorno[i+1] = '\0';

      printf("%s\n", retorno);
    }

    return 0;
}
  • 2

    Do you have the code snippet you made? Try to explain your question better

  • it is necessary to do two loop repetition. If the question is not answered, when I get home I send the answer

  • 1

    @Andrelacomski doesn’t need two ties to do this

1 answer

5

It is possible to solve this issue with only one loop, although it requires more variables.
Follows a possible solution:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int total = 10;
    char letra = '*';

    char *retorno;
    retorno = (char *) malloc(total + 1);

    for (int i=0; i<total; i++) {
      retorno[i] = letra;
      retorno[i+1] = '\0';

      printf("%s\n", retorno);
    }

    return 0;
}

Already with two ties, maybe it’s easier to understand:

#include <stdio.h>

int main()
{
    int total = 10;
    char letra = '*';

    for (int i=0; i<total; i++) {
      for (int j=0; j<=i; j++){
        printf("%c", letra);
      }
      printf("\n");
    }

    return 0;
}

I apologize if I blew the question (since I myself voted to close it because it is not very clear), but the comments do not me allowed to pass..

  • 2

    Good! You can really do only with 1 loop. I hadn’t even thought of this creative solution, of concatenating only one char in the same string.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.