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 Remove Duplicates, Ignore Spaces, and Sort Characters in Descending Order

Remove Duplicates and Sort Characters in Descending Order - C Program

๐Ÿš€ C Program to Remove Duplicates, Ignore Spaces, and Sort Characters in Descending Order

๐Ÿ“„ Source Code:


#include<stdio.h>
#include<string.h>

int present(char a[], char ch, int len)
{
    for (int i = 0; i < len; i++)
    {
        if (a[i] == ch)
        {
            return 1;
        }
    }
    return 0;
}

void des(char a[], int len)
{
    for (int i = 0; i < len - 1; i++)
    {
        for (int j = i + 1; j < len; j++)
        {
            if (a[i] < a[j])
            {
                char temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
}

int main()
{
    char str[200], result[200];
    int j = 0;
    fgets(str, sizeof(str), stdin);
    int len = strlen(str);
    if (str[len - 1] == '\n')
    {
        str[len - 1] = '\0';
    }

    for (int i = 0; str[i] != '\0'; i++)
    {
        if (str[i] != ' ' && !present(result, str[i], j))
        {
            result[j++] = str[i];
        }
    }

    des(result, j);
    result[j] = '\0';

    printf("Resulting string: %s\n", result);
}
    

๐Ÿ“˜ Deep Explanation:

This C program performs three core operations on a string entered by the user:

  • ๐Ÿ”น 1. It removes duplicate characters from the string.
  • ๐Ÿ”น 2. It ignores spaces.
  • ๐Ÿ”น 3. It sorts the unique characters in descending order.
  • ๐Ÿ”ธ present() checks if a character is already in the result array.
  • ๐Ÿ”ธ des() uses a simple bubble sort in descending (Z to A) order.
  • ๐Ÿ”ธ fgets() is used instead of scanf() to read spaces.
  • ๐Ÿ”ธ Only unique characters are printed after sorting.

๐Ÿงช Sample Output:


Input:
Hello World

Output:
Resulting string: roledWH
    

Comments

Popular Posts

๐ŸŒ™