hello everyone
It all started when Aarav said, “Sorting is easy just compare stuff!” and Rahul laughed, “Then prove it!” So, we kicked things off with the most beginner-friendly sorting method Bubble Sort the one where numbers literally “bubble” to the top like soda fizz!
What’s Going On Here?
You enter a bunch of numbers, and the program sorts them from smallest to biggest. It keeps comparing two numbers at a time and swaps them if they’re in the wrong order. After each round, the biggest number drifts to the end just like a bubble rising to the surface. Sure, it’s not the fastest for huge lists, but it’s perfect for learning how sorting works. Plus, you can even sort more than one set without restarting the program convenient, right?
How It Works
Rahul did all the comparisons fast and accurate as always . Aarav handled the swapping, though he once swapped the same numbers twice just to “be sure”. And I (Daksh) proudly printed the sorted results while pretending I did the hard part. By the end, our numbers lined up perfectly and honestly, it felt like watching bubbles float into order!
Code:
#include <stdio.h> #include <string.h> int main() { int numbers[100]; // Array to store numbers int totalElements; // Number of elements in the array int index, pass; // Loop counters int temporaryValue; // Used for swapping values char choice[10]; // To store user choice (yes/no) do { printf("Enter the number of elements: "); scanf_s("%d", &totalElements); printf("Enter %d numbers:\n", totalElements); for (index = 0; index < totalElements; index++) { scanf_s("%d", &numbers[index]); } // Bubble Sort logic for (pass = 0; pass < totalElements - 1; pass++) { for (index = 0; index < totalElements - pass - 1; index++) { if (numbers[index] > numbers[index + 1]) { temporaryValue = numbers[index]; numbers[index] = numbers[index + 1]; numbers[index + 1] = temporaryValue; } } } // Display sorted array printf("\nSorted Array in Ascending Order:\n"); for (index = 0; index < totalElements; index++) { printf("%d ", numbers[index]); } printf("\n"); // Ask if user wants to continue printf("\nDo you want to sort another set of numbers? (yes/no): "); scanf_s("%s", choice, (unsigned)_countof(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