Search This Blog
Welcome to 1printf(), your ultimate destination for C, C++, Linux, Data Structures, and Microcontroller programming! ๐ ๐นLearn advanced coding techniques in C& C++ ๐นMaster Linux internals & shell scripting ๐นDeep dive into Data Structures & Algorithms ๐นExplore Embedded Systems & Microcontrollers (8051,UART, RTOS) ๐นGet hands-on coding tutorials, project ideas,and interview preparation tips Whether you're a beginner or an experienced programmer, this channel will help you
Featured
- Get link
- X
- Other Apps
C Program to Sort Strings Alphabetically and Concatenate
๐ท C Program to Sort Strings Alphabetically and Concatenate
#include<stdio.h>
#include<string.h>
void alfa(char a[][100], int num)
{
char temp[100];
for(int i=0; i<num-1; i++)
{
for(int j=i+1; j<num; j++)
{
if(strcmp(a[i], a[j]) > 0)
{
strcpy(temp, a[i]);
strcpy(a[i], a[j]);
strcpy(a[j], temp);
}
}
}
}
int main()
{
char s[100][100], result[1000] = "";
int num;
printf("How many strings you want to enter:\n");
scanf("%d", &num);
printf("Enter %d strings:\n", num);
for(int i=0; i<num; i++)
{
scanf("%s", s[i]);
}
alfa(s, num);
for(int i=0; i<num; i++)
{
strcat(result, s[i]);
}
printf("Strings in alphabetical order: %s\n", result);
}
๐ Explanation:
✅ This C program takes multiple strings as input from the user, sorts them in **alphabetical (lexicographical) order**, and then concatenates all the sorted strings into a single final string.
๐น `alfa()` is a user-defined function that sorts the array of strings using **bubble sort logic** with `strcmp()` for comparison and `strcpy()` for swapping.
๐น Inside `main()`, the user is asked for the number of strings, which are stored in a 2D character array.
๐น After sorting, we use `strcat()` to append each string in order to the `result` string.
๐น This is useful when you want to create a single combined string from multiple strings in a defined order (e.g., dictionary ordering).
๐ Sample Output:
How many strings you want to enter:
4
Enter 4 strings:
banana
apple
mango
cherry
Strings in alphabetical order:applebananacherrymango
๐ท️ Keywords:
C program, string sorting, alphabetical string sort, strcat, strcmp, strcpy, string array in C, sort strings in C, beginner C string example
Popular Posts
C++ Program for Hybrid Inheritance (All Types Together)
- Get link
- X
- Other Apps
C++ Program for Function Overloading Example
- Get link
- X
- Other Apps
Comments
Post a Comment