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
No comments:
Post a Comment