Friday, 11 July 2014

C++ program to output alternate letters and numbers for a given input string

This program's aim is :

  • when user inputs: abcd7123, output should be: a7b1c2d3.
  • if no.of letters are more than numbers or vice verse then remaining substring of greater string should be followed. eg: if i/p=abc12345 then o/p=a1b2c345 or if i/p=abcd12 then o/p=a1b2cd

  1 #include<iostream> 
  2 #include<ctype.h> 
  3 using namespace std;
  4 void print_remain(char *,int); 
  5 void print(char *, char *,int); 
  6 int main() 
  7 { 
  8     char a[10]={},b[10]={},c[50]; 
  9     cout<<"Enter the string"; 
 10     cin>>c; 
 11     int len=strlen(c); 
 12     int i=len,l=-1,m=-1,n=0; 
 13     while(i) 
 14     { 
 15         if(isalpha(c[n])) 
 16         { 
 17             l++; 
 18             a[l]=c[n]; 
 19         } 
 20         else 
 21         { 
 22             m++; 
 23             b[m]=c[n]; 
 24         } 
 25         i--;n++; 
 26     } 
 27  
 28     i=len,l=0,m=0,n=0; 
 29     int len_a=strlen(a),len_b=strlen(b); 
 30     if(len_a==len_b) 
 31         print(a,b,len); 
 32     else if(len_a<len_b) 
 33     { 
 34         print(a,b,len_a); 
 35         print_remain(b,len_a); 
 36     } 
 37     else 
 38     { 
 39         print(a,b,len_b); 
 40         print_remain(a,len_b); 
 41     } 
 42     return 0;
 43 } 
 44 void print(char *a, char *b, int i)
 45 { 
 46     int j=0,k=0; 
 47     while(i) 
 48     { 
 49         cout<<a[j]<<b[k]<<" "; 
 50         j++;k++;i--; 
 51     } 
 52 } 
 53 void print_remain(char *str, int indx)
 54 { 
 55     int i=strlen(str); 
 56     while(i-indx) 
 57     { 
 58         cout<<str[indx]; 
 59         indx++; 
 60     } 
 61  
 62 }

No comments:

Post a Comment