- 2071 Shrawan · 4 marks
Rewrite string characters alphabetically
Short answer
Compare each character with later ones; if a later character has a smaller ASCII value, swap them. After sorting all pairs, the characters appear in ascending alphabetical order.
Write a program to read a string and rewrite its characters in alphabetical order.
Logic. Every character of the string is compared with the characters after it (a simple exchange sort). Whenever a later character has a smaller ASCII value, the two are swapped. After the loops the characters are in ascending order. For mixed upper and lower case letters, convert the string to one case first (tolower), because capital letters have smaller ASCII codes than small letters.
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[100], t;
printf("Enter a string: ");
scanf("%99s", s);
int n = strlen(s);
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
if (s[i] > s[j]) { /* swap to keep smaller first */
t = s[i];
s[i] = s[j];
s[j] = t;
}
printf("Characters in alphabetical order: %s\n", s);
return 0;
}
Sample run
Input: computer
Enter a string: Characters in alphabetical order: cemoprtu
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Sort names and addresses alphabetically · Computer Programming, chapter 8
- Reverse a string using functions · Computer Programming, chapter 7 · asked 2×
- Display characters between given ranges · Computer Programming, chapter 5
- Correct program: character arrays · Computer Programming, chapter 7
- Copy string converting lower to upper using pointer · Computer Programming, chapter 9 · asked 3×
- Check string consists of alphabet only · Computer Programming, chapter 7
- 8086 ALP: display only alphabetic characters · Microprocessor, chapter 3
- Program for RK-4 first order IVP · Numerical Method, chapter 6
- Program for RK-4 second order IVP · Numerical Method, chapter 6
- Display N characters using default arguments · Object Oriented Programming, chapter 3