Yahoo Interview Question
Software Engineer / Developersvoid printpattern(int num) {
char *stars = "*";
int i = 0;
for(i=0;i<num;++i) {
printf("%s\n%s\n", stars, stars);
strcat(stars,"*");
}
return;
}
the stars pointer should be dynamically allocated, otherwise, "*" cannot be appended to it.
your code just looks shorter, internally strcat iterates through the string to append a "*". In any case the algorithm is no better than O(n2)
Erick's solution is missing one thing. The output expects the star display to be repeated for each i, right? so we need to add one more printf in your for loop. Other than that its fine and yes the algorithm is O(n^2) as strcat has to iterate the full string just to put a "*" at the end of it.
Java:
- AG November 15, 2009