Program to find the initials of a name in C++


In the program, we are given a string name that denotes the name of a person. Our task is to create a Program to find the initials of a name in C++.

Code Description − Here, we have to find the initials of the name of the person given by the string.

Let’s take an example to understand the problem,

Input

name = “ram kisan saraswat”

Output

R K S

Explanation

We will find all the first letters of words of the name.

Solution Approach

A simple solution to the problem is by traversing the name string. And all the characters that appear after the newline character or space character are the initials and need to be printed in upperCase.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
void findNameInitials(const string& name) {
   cout<<(char)toupper(name[0]);
   for (int i = 0; i < name.length() - 1; i++)
      if(name[i] == ' ' || name[i] == '\n')
   cout << " " << (char)toupper(name[i + 1]);
}
int main() {
   string name = "ram kisan\nsaraswat";
   cout<<"The initials of the name are ";
   findNameInitials(name);
   return 0;
}

Output

The initials of the name are R K S

Updated on: 15-Sep-2020

811 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements