0

After searching stack overflow and going through several tutorials I still can't find out how to print a variable multiple time with one printf statement.

This is what I want to get as a result:

1111111111

2222222222

3333333333

by using something like this:

for(int i=1; i<4; i++)

{
    printf("%d", i);   //it would be great to add something here
}

But without another for loop!

Or it can be easily asked like this, I want printf to print variable int i=1; multiple times in a row without loops. So output would be 1111111111

Starl1ght
  • 4,422
  • 1
  • 21
  • 49
mikagrubinen
  • 51
  • 1
  • 1
  • 8

3 Answers3

1

You have to use a second loop, like this :

int i, j, number = 1;
for (i = 0; i < 4; i++){
    for (j = 0; j < 3; j++){
        printf("%d", number);
    }
    printf("\n");
    number++;
}

where 4 is the number of different numbers you want to print and 3 is the number of times you want to print a number. In your case, this will print :

111

222

333

444

Otherwise, you have to specify manually the number of arguments in printf :

int i = 1;
printf("%d%d%d\n", i, i, i);
Community
  • 1
  • 1
Marievi
  • 4,951
  • 1
  • 16
  • 33
1

So the answer is...it is not possible to do what I wanted on the way I wanted. The best way is to use another for loop inside existing one.

Thank you all for your answers.

mikagrubinen
  • 51
  • 1
  • 1
  • 8
-1

it is impossible to print it without loops(for, while, do while). you can also use goto statement but it is not recommended.

        int counter = 1;
label1: printf("1");
        counter ++;
        if (counter <= 10)
           goto label1;

as I said, using goto is bad. so i recommend loops.

Fatemeh Karimi
  • 914
  • 2
  • 16
  • 23