//MODIFIED VERSION: the earlier version wasn't compilable because i accidently left a comment 'uncommented'..Sorry for the inconvenience // Take a string as input from the user. The string will contain only numbers // ('0'-'9') and parentheses ( '(', ')' ). Your task is to find a section in the // string that matches the pattern "k(q)", where k is a single digit, q is a // substring of zero or more characters and the 2 parentheses form a matching set. // Once such a pattern is found, replace it by 'k' occurrences of 'q'. Keep doing // this till you can no longer find such patterns. Output the final string // obtained. // // Author:rahule@iitk.ac.in #include int string_length(char *); //function to find length of the string void display(char *,int length); main() { char s[50]; printf("\nEnter the string\n"); scanf("%s",s); //make sure the entered string is in the correct format.insert necessary checking procedures here,if needed. display(s,string_length(s)); printf("\n"); } void display(char *s,int length) //reads the string pointed from *s upto length 'length' and outputs in the correct format { int num,i,cnt,j; if(length==0) //if length is 0,nothing is left to output.so return return; if(*(s+1)=='(') //if a ''(' is encountered,find its pair ')', and calculate the length of the string between ( and ). Then recursively call the display function //for the string between ( and ) { num=(int)((*s)-'0');//since *(s+1) is '(', *s should be the number indicating how many times the string between ( and ) has to be repeated.So,keep the integer //value of *s in num cnt=1;i=1; while(cnt!=0) //finding the pair of '(' { i++; if(s[i]=='(') //whenever a new '(' is encountered,increment cnt cnt++; else if(s[i]==')') //whenever a ')' is encountered decrement cnt cnt--; } //when cnt becomes 0,s[i] will be pointing to the ')' correspoinding to '(' encountered earlier for(j=0;j0) //if length is still +ve,continue with the next character { display(s,length); } else return; } else { printf("%c",*s); display(++s,--length); } } int string_length(char *s) //funtion to find the string length { int i; for(i=0;s[i]!='\0';i++); //loop till the end of string return(i); }