Program to find largest and smallest character in a String

Description

To find largest and smallest character in a string, extract character from string
and compare this with maximum and minimum character. Here z is considered
as minimum and A is considered as maximum. For detail Follow the below code.

C/C++

/* C Program to find largest and smallest character in a String */
//Save it as LargestSmallestCharacterInString.c

#include<stdio.h>
int main(){

    char str[100];

    printf("Enter a String : ");
    scanf("%s",str);

    //Declaring maximum and minimu charactter
    char max = 'A';
    char min = 'z';
    int i;

    for(i=0;i<strlen(str);i++) {
        
        //Checking minimum character
        if(str[i] < min) {
            min = str[i];
        }
        
        //Checking maximum character
        if(str[i] > max) {
            max = str[i];
        }
    }
    printf("Max : %c", max);
    printf("\nMin : %c", min);

    return 0;
}
Input:
Enter a String : 
Hello

Output:
Max : o
Min : H

Java

/* Java Program to find largest and smallest character in a String */
//Save it as LargestSmallestCharacterInString.java

import java.io.*;
import java.util.Scanner;

public class LargestSmallestCharacterInString {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter a String : ");
        String str = scanner.next();
        
        //Declaring maximum and minimu charactter
        char max = 'A';
        char min = 'z';
        
        for(int i=0;i<str.length();i++) {
            
            //Checking minimum character
            if(str.charAt(i) < min) {
                min = str.charAt(i);
            }
            
            //Checking maximum character
            if(str.charAt(i) > max) {
                max = str.charAt(i);
            }
        }
        System.out.println("Max : "+max);
        System.out.println("Min : "+min);
    }
}
Input:
Enter a String : 
Hello

Output:
Max : o
Min : H

Related Programs

1) Program to find largest and smallest digit in a Number
2) Find Smallest element and it’s position of an Array
3) Program for finding Second Largest Element Of Array
4) Program to form a number using entered digits
5) Program to Find the smallest missing number
6) Program to Find missing odd number in first n odd number
7) Program to generate Random number in a given Range
8) Program to reverse a number
9) Program to Check Leap Year
10) Program to find maximum and second maximum if elements of array is space separated input
Share Me

Leave a Reply