C Program to Sort a String - Source Code, Output & Execution Flow

C Program to Sort a String

This tutorial explains c program to sort a string with C source code, sample output, and step-by-step execution flow.

#include <stdio.h>
#include <string.h>
int main() {
    char str[] = "dcba", temp;
    int i, j, n = strlen(str);
    for (i = 0; i < n - 1; i++)
        for (j = i + 1; j < n; j++)
            if (str[i] > str[j]) { temp = str[i]; str[i] = str[j]; str[j] = temp; }
    printf("Sorted string: %s
", str);
    return 0;
}
Sorted string: abcd

In this program, the input is read first when required, the core logic is applied step by step, and the final result is displayed using printf(). Follow the execution flow beside the code to understand how each statement contributes to the output.