1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Coding help for C programming

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

  1. sumedh yadav

    sumedh yadav New Member

    Joined:
    Aug 18, 2012
    Messages:
    17
    Likes Received:
    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. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    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;
    
    // read input;
    // 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.
     
  3. sumedh yadav

    sumedh yadav New Member

    Joined:
    Aug 18, 2012
    Messages:
    17
    Likes Received:
    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.
     
  4. sumedh yadav

    sumedh yadav New Member

    Joined:
    Aug 18, 2012
    Messages:
    17
    Likes Received:
    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. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    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.
     
  6. sumedh yadav

    sumedh yadav New Member

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

Share This Page