Here, we will see how to find the initials of a name using a C program. Below are the examples:
Input: Geeks for Geeks
Output: G F G
We take the first letter of all
words and print in capital letter.Input: Jude Law
Output: J L
Approach:
- Print the first character in the capital.
- Traverse the rest of the string and print every character after space in capital letters.
Below is the C program to print the initials of a name:
// C program to print initials
// of a name
# include <stdio.h>
# include <string.h>
# include <ctype.h>
// Function declaration
void getInitials(char* name);
// Driver code
int main(void)
{
// Declare an character array for
// entering names assuming the
// name doesn't exceed 31 characters
char name[50] = "Geeks for Geeks";
printf("Your initials are: ");
// getInitials function prints
// the initials of the given name
getInitials(name);
}
void getInitials(char* name)
{
int i = 0;
if(strlen(name) > 0 &&
isalpha(name[0]))
printf("%c ", toupper(name[0]));
while(name[i] != '\0')
{
if(isspace(name[i]) != 0)
{
while(isspace(name[i]) &&
i <= strlen(name))
{
i++ ;
}
printf("%c ", toupper(name[i]));
}
i++;
}
printf("\n");
}
Output
Your initials are: G F G
Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(1), as constant extra space is used.