Skip to main content

Featured

C++ Program to Perform Linear Search on a Vector

  C++ Program to Perform Linear Search on a Vector Introduction In this C++ program, we will learn how to perform a Linear Search on a vector. The program first takes the size of the vector and its elements as input. Then it asks the user for the element to search. If the element is found, it displays the index where it is located. Otherwise, it displays a message indicating that the element is not found. C++ Program #include<bits/stdc++.h> using namespace std; int main() { int num, search, found = 0; cout << "Enter the size of the vector:" << endl; cin >> num; vector<int> v(num); cout << "Enter " << num << " elements in vector:" << endl; for(int i = 0; i < num; i++) { cin >> v[i]; } cout << "Enter element that you want to search:" << endl; cin >> search; for(int i = 0; i < num; i++) { ...

C Program to Sort Strings Alphabetically and Concatenate

Sort and Concatenate Strings in C

๐Ÿ”ท 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

Comments

Popular Posts

๐ŸŒ™