hello everyone
After sorting numbers, Aarav thought he was the “Sorting King.” But Rahul grinned and said, “Cool, now let’s see if you can sort words!” And that’s how we ended up using Bubble Sort for strings same logic, just with text instead of numbers!
What’s Happening Here?
You type in a bunch of words like apple, banana, mango and the program sorts them alphabetically by comparing two words at a time. If one word should come before the other, it swaps them. So “banana” and “apple”? Boom swapped!
How It Works
Rahul was the word wizard, checking which ones came first alphabetically . Aarav did the swapping again, though he still tried to put “zebra” before “apple” just for laughs. And I (Daksh) made sure the final sorted list looked neat and tidy like a mini dictionary .
Code:
#include <stdio.h> #include <string.h> int main() { char words[100][100]; // Array to store words int totalWords; // Number of words int index, pass; // Loop counters char temporaryWord[100]; // Used for swapping words char choice[10]; // To store user choice (yes/no) do { printf("Enter the number of words: "); scanf_s("%d", &totalWords); printf("Enter %d words:\n", totalWords); for (index = 0; index < totalWords; index++) { scanf_s("%s", words[index], (unsigned)sizeof(words[index])); // Safe input } // Bubble Sort logic for strings for (pass = 0; pass < totalWords - 1; pass++) { for (index = 0; index < totalWords - pass - 1; index++) { if (strcmp(words[index], words[index + 1]) > 0) { // Compare strings strcpy_s(temporaryWord, sizeof(temporaryWord), words[index]); strcpy_s(words[index], sizeof(words[index]), words[index + 1]); strcpy_s(words[index + 1], sizeof(words[index + 1]), temporaryWord); } } } // Display sorted words printf("\nWords in Alphabetical Order:\n"); for (index = 0; index < totalWords; index++) { printf("%s\n", words[index]); } // Ask if user wants to continue printf("\nDo you want to sort another set of words? (yes/no): "); scanf_s("%s", choice, (unsigned)sizeof(choice)); } while (strcmp(choice, "yes") == 0 || strcmp(choice, "YES") == 0); printf("\nOkay, exiting the program.\n"); return 0; }
Output:
| ← Previous | 🏠 Homepage | Next Chapter → |
No comments:
Post a Comment