This blog is under construction

Wednesday, 17 July 2013

C program to find the smallest and largest character in a string

Write a C program to find the smallest and largest character in a string.


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

  int main() {
        char data[256];
        int small, large, i = 0;

        /* get the input string from the user */
        printf("Enter your input sting:");
        fgets(data, 256, stdin);
        data[strlen(data) - 1] = '\0';

        /* assing large and small to first character in i/p string */
        large = small = data[i];

        /* find smallest and largest character */
        while (data[i] != '\0') {
                if ((data[i] >= 'a' && data[i] <= 'z') ||
                        (data[i] >= 'A' && data[i] <= 'Z')) {
                        /* finding the smallest character */
                        if (data[i] < small) {
                                small = data[i];
                        }

                        /* finding the largest character */
                        if (data[i] > large) {
                                large = data[i];
                        }
                }
                i++;
        }

        /* print the results */
        printf("Smallest Character in the given string: %c\n", small);
        printf("Largest character in the given string: %c\n", large);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input sting:Programming Language
  Smallest Character in the given string: L
  Largest character in the given string: u


No comments:

Post a Comment