a program should accept one 5 digit number eg 42139, seperate the number into individual digits seperated from one another by three spaces eg. 4 2 1 3 9
a program should accept one 5 digit number eg 42139, seperate the number into individual digits seperated from one another by three spaces eg. 4 2 1 3 9
The Full num: 42139
The first num: (42139 / 10000)
The second num: (42139 % 10000) / 1000
The third num: (42139 % 1000) / 100
The fourth num: (42139 % 100) / 10
The fifth num: (42139 % 10)
Now this just tell's you how to separate the numbers, after you know this, it's not difficul to do what you want.
Last edited by Vber; 01-16-2003 at 03:01 PM.
You can do it the hard way
Or the easy wayCode:#include <stdio.h> int five_digs(int num) { int cnt = 0; while (num != 0) { cnt++; num /= 10; } return cnt == 5; } void print_dig(int num) { if (num / 10 != 0) { print_dig(num / 10); } printf("%d ", num % 10); fflush(stdout); } int main(void) { int num; printf("Enter a 5 digit number: "); fflush(stdout); if (scanf("%d", &num) != 1) { return 1; } if (five_digs(num)) { print_dig(num); printf("\n"); } return 0; }
Code:#include <stdio.h> #include <string.h> int main(void) { int num, len; char snum[10]; printf("Enter a 5 digit number: "); fflush(stdout); if (scanf("%d", &num) != 1) { return 1; } sprintf(snum, "%d", num); if ((len = strlen(snum)) == 5) { int i; for (i = 0; i < len; i++) { printf("%c ", snum[i]); fflush(stdout); } printf("\n"); } return 0; }
*Cela*
We just got done doing this for my C++ class I am taking.
Not the most effiecient but the easiest and fastest (coding time) way to do it.Code:#include<stdio.h> #include<stdio.h> int main() { int num, tenThou, thou, hund, ten,one; printf("Enter a 5 digit number: "); scanf("%d",&num); tenThou=num/10000; thou=(num%10000)/1000; hund=(num%1000)/100; ten=(num%100)/10; one=num%10; printf("%d %d %d %d %d\n",tenThou,thou,hund,ten,one); return 0; }
You're all doing this the hard way.Originally posted by verlim
a program should accept one 5 digit number eg 42139, seperate the number into individual digits seperated from one another by three spaces eg. 4 2 1 3 9
That technicly does exactly what your requirements are. Furthermore, you could just apply a simple bit of math (-'0') and stick them into individual integers.Code:int main( void ) { char buf[6]; printf("Enter a 5 digit number: "); fgets( buf, 6, stdin ); printf("%c %c %c %c %c\n", buf[0],buf[1],buf[2],buf[3],buf[4] ); return 0; }
Quzah.
Hope is the first step on the road to disappointment.
Yea well we had just done this challenge in my Advanced Placement Computer Science class and most of the kids in my class had problems with it so I thought that it might be worth posting at HDC.