Tuesday, July 14, 2009

Please help me do this C program?

Write a program in C that reads any five digit number and displays the number in two parts


diagonally as shown in the user interface screen as in the figure below.


it's suppose to look like this:





Please key in any 5 digit number: 56789


5678 9


567 89


56 789


5 6789





The number displayed is separated into two parts beginning with the rightmost unit digit. The


process continues until the leftmost digit is reached.


thanx alot k..

Please help me do this C program?
#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;





main()


{


long num, rmdr, i, j;


char numstr[32], fmt[16];





/* do


{ */


printf("Please key in any 5 digit number: ");


scanf("%ld", %26amp;num);


/* sprintf(numstr, "%ld", num);


} while(strlen(numstr) != 5); */


for (i = j = 1, rmdr = 0; i %26lt; 5; i++, j *= 10)


{


rmdr += j * (num % 10);


num /= 10;


strcpy(fmt, " ");


strcat(fmt, " ");


strcat(fmt, " ");


sprintf(fmt + i - 1, "%%ld %%0%ldld\n", i);


printf(fmt, num, rmdr);


}


}





NOTE: I commented out the part that uses the strlen, which was only there to make sure the string entered was really a 5-digit number. Also, I realized I should have included %26lt;string.h%26gt;, so I've made that correction.





NOTE 2: I assume the dots are to indent that many spaces. I've made the change to the format string to accomplish that. I've also removed superfluous code.





NOTE 3: The reason I have a strcpy followed by two strcats is that Yahoo doesn't know how to display text faithfully in HTML, so my 3 spaces shrank to 1!
Reply:Thanks alot, your code is very helpful, but it's too complex for what we are studying right now. Thanks once again. Report It

Reply:You could add some bounds checking on input, but this will work just fine::











#include %26lt;iostream%26gt;


using namespace std;





int main()


{


char strInput[6];


cout %26lt;%26lt; "Enter a 5 digit number: ";


cin %26gt;%26gt; strInput;


for( int j=4; j %26gt; 0; j-- ) {


for( int i=0; i %26lt; 5; i++ ) {


if( i == j ) cout %26lt;%26lt; " ";


cout %26lt;%26lt; strInput[i];


}


cout %26lt;%26lt; endl;


}


return 0;


}
Reply:This would be the pseudo code for it





1. Take the number and read it into an integer variable - InputNumber


2. Define two other integers to hold the two values.


call them - Q %26amp; R


3. Set a loop starting with 10: LoopInt = 10


4. Q = InputNumber / LoopInt


5. R = InputNumber - (Q * LoopInt)


6. Increment LoopInt by a factor of 10 (LoopInt * 10)


7. Repeat Step 4 %26amp; 5.


No comments:

Post a Comment