Saturday, October 30, 2010

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".
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


  1. #include<iostream.h>
  2. #include<stdio.h>
  3. #include<conio.h>
  4. void main()
  5. {
  6. clrscr();
  7. char arr[40];
  8. cout<<"Enter The Name "<<endl;
  9. gets(arr);
  10. cout<<arr[0]<<".";
  11. for(int i=0;arr[i]!='\0';i++)
  12. {
  13. if(arr[i]==' ')
  14. {
  15. cout<<arr[i+1]<<".";
  16. i++;
  17. }
  18. }
  19. if(arr[i]=='\0')
  20. {
  21. for(;arr[i]!=' ';i--);
  22. cout<<"\b\b";
  23. i++;
  24. for(;arr[i]!='\0';i++)
  25. {cout<<arr[i];}
  26. }
  27. getch(); 
  28. }


Output

Enter The Name
Mohandas Karamchand Gandhi
M.K.Gandhi 

No comments:

Post a Comment