C program

How to write a c program to print 1,21,321,4321,54321 order
Last edited on
You can use two (nested) for loops
or may be one ;)
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
 *  reverse.c
 *  
 *
 *  Created by Matthew Dunson on 11/15/09.
 *  Copyright 2009 The Ohio State University. All rights reserved.
 *
 */

#include <stdio.h>

int main ()
{
	int i = 1, j = 1, j_counter = j;
	while ( i < 6)
	{
		while ( j > 0)
		{
			printf ("%d", j);
			j--;
		}
		if ( i != 5)
		{
			printf(",");
		}
		j_counter++;
		j = j_counter;
		i++;
	}
	return 0;
}

Last edited on
ha ha:
1
2
3
4
5
#include <stdio.h>
int main() {
	print("1,21,321,4321,54321");
	return(0);
}


you can also use math to shift the decimal point then add the digits.

these are all equal:

4321 = 4000 + 300 + 20 + 1
4321 = (4 * 1000) + (3 * 100) + (2 * 10) + (1 * 1)
4321 = (4 * pow(10, 3)) + (3 * pow(10, 2)) + (2 * pow(10, 1)) + (1 * pow(10, 0))


in a progressive form:

result = shifted digit   + oldresult
1      = (1 * pow(10, 0) + 0
21     = (2 * pow(10, 1) + 1
321    = (3 * pow(10, 2) + 21
4321   = (4 * pow(10, 3) + 321


now, all you have to do is write a loop. is this your first loop program?
Topic archived. No new replies allowed.