Smallest alphabet greater than given character

Smallest alphabet greater than given character

Question

Given a sorted array of characters, find an alphabet which is greater than the given character. Get the input from the user. Output must be as follows,

 

Logic

  • Get the input from the user and convert that to ASCII value.
  • If the Last character is Smaller(in terms of ASCII value) than given then print “not found”.
  • Check each character with the given character. If a larger item is found print and break the loop.

Program

#include<stdio.h>
void main()
{
    char c;
    int i,num,n1,count=0;
    printf("enter a character");
    scanf("%c",&c);
    char arr[] ={'a','d','e','j','k','z'};      //sorted array
    printf("Smallest alphabet greater than %c is",c);
    for(i=0;i<100;i++)
    {
        if(arr[i]=='\0')
        break;
        count++;                        //count of character array

    }
    n1 =c;                             // ASCII value of given input
    num= arr[count-1];                //ASCII Conversion (EX: 'a' to 97 )
    if(n1>num)                       //whether last charater is smaller than given
    {
         printf (" not found");
    }
    else
    {

        for(i=0;i<count;i++)
        {
            num= arr[i];
            if(n1 == num)               //found same character
            {
                printf("%c",arr[i+1]);  //print next index character
                break;
            }
            if(n1>num)                  //if smaller increment index
                continue;
            if(n1<num)
            {
                printf("%c",arr[i]);
                break;                  //very important
            }

        }
    }
}

Analysis

worst case – O(n) because we may end up checking till the last character.

best case – O(1)  because at the first comparison itself we can find whether the last item is smaller the given character.

 

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Sree Hari Sanjeev

The founder of Wisdom Overflow. Software Developer at Zoho Corporation.
0 0 votes
Article Rating
Subscribe
Notify of
guest
5.4K Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
5.4K
0
Would love your thoughts, please comment.x
()
x