Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Patterns

Array

2D Array

String Function Example

Pointers

Recursion Function

Structure

Excersises

Others


C Program to Find Length of the Shortest Word in a Sentence


Write a C program to find length of the longest word in a given sentence.

  • Takes a sentence input from the user character-by-character until a newline is hit.
  • Iterates through the string to detect each word’s start and length by identifying space-separated tokens.
  • Tracks the shortest word by updating minLen and its starting position whenever a shorter word is found.
  • Copies the shortest word to a separate string and prints it along with its length.
Example : pgm.c
#include <stdio.h>

int main() {
    char str[200], shortest[100];
    int i = 0, start = 0, minLen = 9999;  // Large value as substitute for INT_MAX

    printf("Enter a sentence: ");
    while ((str[i] = getchar()) != '\n') {
        i++;
    }
    str[i] = '\0';

    i = 0;
    while (str[i] != '\0') {
        if (str[i] != ' ') {
            int wordStart = i;
            int wordLen = 0;

            while (str[i] != ' ' && str[i] != '\0') {
                wordLen++;
                i++;
            }

            if (wordLen < minLen) {
                minLen = wordLen;
                start = wordStart;
            }
        } else {
            i++;
        }
    }

    for (i = 0; i < minLen; i++) {
        shortest[i] = str[start + i];
    }
    shortest[i] = '\0';

    printf("Shortest word: %s\n", shortest);
    printf("Length: %d\n", minLen);

    return 0;
}

Output :

Enter a sentence: This is a simple test
Shortest word: a
Length: 1