Steven
Steven

Reputation: 13

How to iterate through a given integer input, and give output of Largest to Smallest digits?

Theory wise, I understand how to do this problem.

For an example, if the given input was 9536, the output would be 9653.

I want a way to do this use concatenation, and to cycle through each digits and when finding a digit that was larger than the rest it is stored as the first 'character' in an empty string r.

I was able to solve this using php(my main language), but not C. I am preparing for a lab position and this lab uses C as their main language, so I am trying to brush up on my basic C skills.

Thank you for your help

Upvotes: 1

Views: 120

Answers (2)

Weather Vane
Weather Vane

Reputation: 34585

It is easy to sort using the qsort() provided. In this example, I could have asked for a string input directly, but you wanted an integer. It doesn't use the "concatenation" you wanted, but you haven't shown any code.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    int compare(const void *A, const void *B) {
        return *(char*)B - *(char*)A;
    }

    int main() {
        int number;
        char numstr[21];
        printf("Enter an integer: ");
        if (scanf("%d", &number) != 1)
            return 1;
        sprintf (numstr,"%d", number);
        qsort(numstr, strlen(numstr), 1, compare);
        printf("%s\n", numstr);
    return 0;
    }

Program output:

Enter an integer: 9536
9653

Upvotes: 0

DrKoch
DrKoch

Reputation: 9772

Three steps:

  1. Read the input one character at a time, convert character to integer and store in an array of integers.
  2. Sort array
  3. Print each digit in the (now sorted) array

Upvotes: 1

Related Questions