Q:

C program to print the smallest word in a string

belongs to collection: C String Programs

0

C program to print the smallest word in a string

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

Program:

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to print the biggest word in a string... >>
<< C program to print the biggest and smallest palind...