Dremendo Tag Line

Input a name and print the initial along with title in C

String Methods - Question 5

In this question, we will see how to input a name and print the initial first and then the title in C programming. To know more about string methods click on the string methods lesson.

Q5) Write a program in C to input a name and print the initial first and then the title.

Example:
Input ->   MOHIT KUMAR AGARWAL
Output ->  M.K. AGARWAL

Program

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

int main()
{
    char s[50];
    int i,lsp;

    printf("Enter a name\n");
    gets(s);

    // Finding the last space position
    for(i=strlen(s)-1; i>=0; i--)
    {
        if(s[i]==' ')
        {
            lsp=i;
            break;
        }
    }

    printf("The initials of the name is\n");
    for(i=0; i<lsp; i++)
    {
        if(i==0 && s[i]!=' ')
        {
            printf("%c.",s[i]);
        }
        else if(s[i]==' ' && s[i+1]!=' ')
        {
            printf("%c.",s[i+1]);
        }
    }

    // Printing the title
    for(i=lsp; i<strlen(s); i++)
    {
        printf("%c",s[i]);
    }
    return 0;
}

Output

Enter a name
Mohandas Karamchand Gandhi
The initials and the title is
M.K. Gandhi
video-poster