×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to print the smallest word in a string

Here, we are going to learn how to print the smallest word in a string in C programming language?
Submitted by Nidhi, on July 15, 2021

Problem statement

Given a string, we have to print the smallest word from the given string using C program.

C program to print the smallest word in a string

The source code to print the smallest word in a string is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to print the smallest word in a string

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

int main()
{
    int i = 0;
    int j = 0;
    int flag = 0;

    char str[64];
    char word[64];

    char small[16];

    printf("Enter a string: ");
    fflush(stdin);
    scanf("%[^\n]s", str);

    for (i = 0; i < strlen(str); i++) {
        while (i < strlen(str) && !isspace(str[i]) && isalnum(str[i])) {
            word[j++] = str[i++];
        }
        if (j != 0) {
            word[j] = '\0';
            if (!flag) {
                flag = !flag;
                strcpy(small, word);
            }
            if (strlen(word) < strlen(small)) {
                strcpy(small, word);
            }
            j = 0;
        }
    }

    printf("Smallest Word in string is: %s\n", small);
    return 0;
}

Output

RUN 1:
Enter a string: Indian is a great country
Smallest Word in string is: a

RUN 2:
Enter a string: is are am
Smallest Word in string is: is

RUN 3:
Enter a string: ram mohan ramdas mohandas
Smallest Word in string is: ram

Explanation

Here, we read a string str from the user using the scanf() function. Then we found the smallest word in a string and printed the result on the console screen.

C String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.