Skip to main content

Featured

C Program to Solve Two Sum Using Brute Force (With Algorithm & Output)

 Introduction The Two Sum problem is a popular coding interview question where we must find two indices of an array whose values add up to a given target. This program demonstrates a simple brute-force solution in C using nested loops and dynamic memory allocation. Problem Statement Given an integer array and a target value, return the indices of the two numbers such that they add up to the target. Each input has exactly one solution, and the same element cannot be used twice. The result should return the indices, not the values. If no solution exists, return NULL.  Algorithm / Logic Explanation Start the program. Traverse the array using a loop from index 0 to numsSize - 1 . Inside this loop, use another loop starting from i + 1 to numsSize - 1 . For every pair (i, j) , check if nums[i] + nums[j] == target . If condition becomes true: Allocate memory for 2 integers using malloc() . Store indices i and j . Set returnSize = 2 . Return the result poi...

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

๐ŸŒ™