Skip to main content

Featured

Mastering Hollow Square Patterns in C: Stars, Numbers, Alphabets & Binary

πŸ”’ C Program to Print Hollow Continuous Number Square πŸ“„ Source Code: #include <stdio.h> int main() { int num, k = 0; printf("Enter the number:\n"); scanf("%d", &num); for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { if(i == 1 || i == num || j == 1 || j == num) { // k increments sequentially only along the borders printf("%d ", k++); } else { printf(" "); } } printf("\n"); } return 0; } πŸ“‹ Copy Code πŸ’» Expected Output (Input: 5): Enter the number: 5 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 πŸ”’ C Program to Print Standard Hollow Binary Row Square πŸ“„ Source Code (Fixed Specifier): #include <stdio.h> int main() { ...

C program to sort words in a string based on their length

C Program: Sort Words in a String by Length

πŸ”· C Program: Sort Words in a String by Length

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



void sort(char words[][50], int count)
{
    char temp[50];
    for (int i = 0; i < count - 1; i++)
    {
        for (int j = i + 1; j < count; j++)
        {
            if (strlen(words[i]) > strlen(words[j]))
            {
                strcpy(temp, words[i]);
                strcpy(words[i], words[j]);
                strcpy(words[j], temp);
            }
        }
    }
}

int main()
{
    char str[200];
    char words[50][50];
    int count = 0;

    printf("Enter a string:\n");
    fgets(str, sizeof(str), stdin);

    int len = strlen(str);
    if (str[len - 1] == '\n')
    {
        str[len - 1] = '\0';
    }

    char *token = strtok(str, " ");
    while (token != NULL)
    {
        strcpy(words[count++], token);
        token = strtok(NULL, " ");
    }

    sort(words, count);

    for (int i = 0; i < count; i++)
    {
        printf("%s ", words[i]);
    }
    printf("\n");

    return 0;
}
  

πŸ“˜ Explanation:

This program sorts the words in a given string **based on their lengths** using arrays and string manipulation functions in C.

πŸ”Ή The input string is first taken using `fgets()` to safely read multi-word input.
πŸ”Ή A newline character (`\n`) at the end is replaced with `\0` to clean the input.
πŸ”Ή The `strtok()` function is used to **tokenize** the string by spaces into individual words, which are stored in a 2D array `words`.

πŸ”Ή The `sort()` function uses **nested loops** to compare the length of each word using `strlen()`: - If one word is longer than the other, they are swapped using `strcpy()` and a temporary buffer.

πŸ”Ή After sorting, the words are printed in increasing order of their lengths.

πŸ” Sample Output:

Enter a string:
i love programming in C

i in C love programming
    

🏷️ Keywords:

C string sorting, C program for sorting words, strtok usage in C, sort by word length, 2D array string sort, beginner C string program

Comments

πŸŒ™