Featured
- Get link
- X
- Other Apps
C++ programming:program to accept your name and print initials:how to display initials:name initials sample in C
In this tutorial, you will find a C++ program which accepts a name and prints initials for example if the input is "Vidhu Vinod Chopra", program will print "V.V.Chopra".
M.K.Gandhi
Following is a C++ program to accept a name and then print its initials. For Example If the input is "Mohandas Karamchand Gandhi"
This program will display M.K.Gandhi
Program Explanation:
Logic:
first print the first character by cout<<arr[0] and a dot by cout<<"." Then a loop runs till end of string and if it finds space, the next character is printed and a dot is printed. So in the above exmple if we input Mohandas Karamchand Gandhi, the output is M.K.G. Now a loop runs in array to go back till it finds a space. Then the statement cout<<\b\b" at line 22 erases 2 characters backside. It erases "G." Now a loop again runs from next character of the the last space till the end of the string. In our example it starts from G and prints Gandhi.
Line 9: input through gets() because cin does not input space
- #include<iostream.h>
- #include<stdio.h>
- #include<conio.h>
- void main()
- {
- clrscr();
- char arr[40];
- cout<<"Enter The Name "<<endl;
- gets(arr);
- cout<<arr[0]<<".";
- for(int i=0;arr[i]!='\0';i++)
- {
- if(arr[i]==' ')
- {
- cout<<arr[i+1]<<".";
- i++;
- }
- }
- if(arr[i]=='\0')
- {
- for(;arr[i]!=' ';i--);
- cout<<"\b\b";
- i++;
- for(;arr[i]!='\0';i++)
- {cout<<arr[i];}
- }
- getch();
- }
Output
Enter The Name
Mohandas Karamchand Gandhi
Mohandas Karamchand Gandhi
- Get link
- X
- Other Apps
Labels:
accept name print initials
c program to accept a name and print initials
C++ to print initials
convert a name to initials
print initials
Comments
Popular Posts
C++ program to display numbers which get reversed after multiplying by 4
- Get link
- X
- Other Apps
Explain the code
ReplyDeleteThanks
DeleteCan u explain same code in c
public static void main(String args[]){
ReplyDeleteString str="karan bharat veer";
char arr[]=new char[40];
arr=str.toCharArray();
int n=arr.length;
int i;
int counter=1;
for( i=0;i<=n-1;i++){
if(arr[i]==' '){
counter++;
System.out.print(""+arr[i+1]+" ");
i++;
}
if(counter==3){
System.out.print(""+arr[i]);
}
}
}
}