# Coding help for C programming

Discussion in 'C' started by sumedh yadav, Aug 18, 2012.

Joined:
Aug 18, 2012
Messages:
17
0
Trophy Points:
0
Consider an integer in which each digit is either 0 or 1. Write a program to rearrange the digits such that all the 0s appear before the 1s. Output the resulting number.

sample input:
01001010101
sample output:
00000011111

2. ### hobbyistNew Member

Joined:
Jan 7, 2012
Messages:
141
0
Trophy Points:
0
I think I'd try something like reading the user input into a char array, parsing the input string making sure it's either a 1 or 0, and if it is, process the string within a function.

Code:
```char input[33] = { 0 }, *p;
long result = 0;

// validate input;
// process input;

result = strtol(input, &p, 2);
// print result
```
Before writing and testing the function, try strtol directly to make sure you get the expected result.

Code:
```char *p;
printf("%ld", strtol("01001010101", &p, 2));
```
Give it a try and post your code if you need any help.
Good luck.

Joined:
Aug 18, 2012
Messages:
17
0
Trophy Points:
0
till now we at are not taught use of arrays,strings.we are just being taught loops,if & else statements,functions.

Joined:
Aug 18, 2012
Messages:
17
0
Trophy Points:
0
till now we at are not taught use of arrays,strings.we are just being taught loops,if & else statements,functions.

5. ### hobbyistNew Member

Joined:
Jan 7, 2012
Messages:
141
0
Trophy Points:
0
what you might try is a couple of int variables for counters - one for 1s and another for 0s. If you use getchar for the input loop, you should be able to determine the number of 1s or 0s by using input - '0'.

After exiting the input loop, use the two counters in loops to print the respective 0s and then 1s.

Joined:
Aug 18, 2012
Messages:
17
0
Trophy Points:
0
thanks i got the logic and arrived at the answer