C Program to Find Length of the Longest Word in a Sentence
Write a C program to find length of the longest word in a given sentence.
- Reads a full sentence from the user character-by-character until a newline is encountered.
- Scans through the sentence to detect the start and length of each word separated by spaces.
- Tracks the longest word by updating maxLen and its starting index whenever a longer word is found.
- Copies the longest word into a new string and prints it along with its length.
Example : pgm.c
#include <stdio.h> int main() { char str[200]; char longest[100]; int i = 0, start = 0, maxLen = 0, len = 0; 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 > maxLen) { maxLen = wordLen; start = wordStart; } } else { i++; } } // Copy the longest word into a new string for (i = 0; i < maxLen; i++) { longest[i] = str[start + i]; } longest[i] = '\0'; printf("Longest word: %s\n", longest); printf("Length: %d\n", maxLen); return 0; }
Output :
Enter a sentence: C language is powerful and expressive
Longest word: expressive
Length: 10
Longest word: expressive
Length: 10