# Thread: Printing a certain number of variables.

1. ## Printing a certain number of variables.

Is there an easier way to do this? The quantity is decided in the program. I don't know how it is done with a loop if it's possible. If there's more than one way, can you please briefly describe all of them? Thank you.
Code:
```void printSorted( int quantity, int n1, int n2, int n3, int n4, int n5, int n6 )
{
switch( quantity )
{
case 1:
printf( "%d", n1 );
break;
case 2:
printf( "%d, %d", n1, n2 );
break;
case 3:
printf( "%d, %d, %d", n1, n2, n3 );
break;
case 4:
printf( "%d, %d, %d, %d", n1, n2, n3, n4 );
break;
case 5:
printf( "%d, %d, %d, %d, %d", n1, n2, n3, n4, n5 );
break;
case 6:
printf( "%d, %d, %d, %d, %d, %d", n1, n2, n3, n4, n5, n6 );
break;
}
}```

2. Arrays are designed for situations like this.

Arrays in C and C++ - Cprogramming.com

3. Can it be done without using an array?

4. Using an array IS the easiest and neatest way.

If you wanted to do different without using an array, you could do something like this:
Code:
```void printSorted( int quantity, int n1, int n2, int n3, int n4, int n5, int n6 )
{
if (quantity < 1) return;

printf( "%d", n1 );

if (quantity < 2)  return;

printf( ", %d", n2 );

if (quantity < 3)  return;

printf( ", %d", n3 );

if (quantity < 4)  return;

printf( ", %d", n4 );

if (quantity < 5)  return;

printf( ", %d", n5 );

if (quantity < 6)  return;

printf( ", %d", n6 );

}```
However, it is not as good as using an array and a loop.

5. Or use function with a variable number of arguments (I still prefer the array solution)

Code:
```#include <stdarg.h>
#include <stdio.h>

void printSorted(int quantity, ...) {
va_list ap;
int k;
va_start(ap, quantity);
printf("%d", va_arg(ap, int));
for (k = 1; k < quantity; k++) {
printf(" %d", va_arg(ap, int));
}
va_end(ap);
puts("");
}

int main(void) {
printSorted(2, 42, 42);
printSorted(15, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3);
return 0;
}```

6. Originally Posted by HaydeezPluto
Can it be done without using an array?
That's like asking if you can run a marathon by hopping all the way on one leg. In theory maybe, but in practice that would be idiotic.