A slightly condensed version that operates on the same principal could be:
#include <stdio.h>
int main (void) {
int n, /* your number 10, 28, etc... */
suffix = 0; /* number after a(), b(), c(), ... */
fputs ("enter n: ", stdout); /* prompt for n */
/* read/validate positive int value */
if (scanf ("%d", &n) != 1 || n <= 0) {
fputs ("error: invalid, zero or negative integer input.\n", stderr);
return 1;
}
fputs ("output : ", stdout); /* prefix for output */
while (n > 0) { /* while n greater than 0 */
/* loop i from 0 to n or 26 (whichever is less) */
for (int i = 0; i < (n > 26 ? 26 : n); i++) {
/* if i not 0 or suffix not 0, add ", " before next output */
printf (i || suffix ? ", %c%d" : "%c%d", 'a' + i, suffix + 1);
}
n -= 26; /* subtract 26 fron n */
suffix += 1; /* add 1 to suffix */
}
putchar ('\n'); /* tidy up with final newline */
}
(Note: both i
and suffix
loop from 0
instead of 1
which allows a test of whether suffix
or i
have been used, e.g. 0 == false
, 1 == true
. That way you can control whether the ','
is output by checking whether i
or suffix
have been set yet)
Example Use/Output
$ ./bin/alphabetloop
enter n: 10
output : a1, b1, c1, d1, e1, f1, g1, h1, i1, j1
or
$ ./bin/alphabetloop
enter n: 28
output : a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1, m1, n1, o1, p1, q1, r1, s1, t1, u1, v1, w1, x1, y1, z1, a2, b2