2 votes 2 votes Let S be a stack with operations push, pop, top, empty. What is displayed after following segment of code executes . for(i=1; i<=5; i++) s.push(i); while(!s.empty()) printf("%d", s.top()); ans with explanation DS stack + – amit166 asked Aug 8, 2018 amit166 748 views answer comment Share Follow See all 10 Comments See all 10 10 Comments reply arvin commented Aug 8, 2018 reply Follow Share i think we will have a stack overflow because we dont have any condition for decrement of while loop and everytime it will print top of stack. 2 votes 2 votes Soumya29 commented Aug 8, 2018 i edited by Soumya29 Aug 8, 2018 reply Follow Share After for loop- 5 4 3 2 1 After while loop- Printed $\rightarrow 555555...........$ As $s.top()$ just returns top element of the stack without popping it, So while will go in infinite loop. 1 votes 1 votes arvin commented Aug 8, 2018 reply Follow Share @soumya29 : but there is no decrement for while case or you can say there is no popping it only displays top while stack is not empty. 0 votes 0 votes Soumya29 commented Aug 8, 2018 reply Follow Share @arvin. Stopping condition is $!s.empty()$ When stack becomes empty, s.empty() will return true so $!s.empty()$ will return false. 0 votes 0 votes arvin commented Aug 8, 2018 reply Follow Share @soumya29 but how can u say that the top is decrementing as we are not popping 0 votes 0 votes Soumya29 commented Aug 8, 2018 reply Follow Share @arvin. Oh..Yes,, I misread the question. It's s.top(). . You are right. 0 votes 0 votes srestha commented Aug 8, 2018 reply Follow Share yes, here stack overflow error will occur rt? 2 votes 2 votes arvin commented Aug 8, 2018 reply Follow Share @soumya29 yes because its not s.pop() @srestha it will be having overflow 1 votes 1 votes amit166 commented Aug 8, 2018 reply Follow Share THANKU 0 votes 0 votes kr.ankit commented Aug 14, 2018 reply Follow Share @arvin the while loop will execute infinite times but should we call the final answer as Stack Overflow? Because the contents of the stack will be fixed to 5,4,3,2,1. The while loop will print infinite times but the stack is not overflowing right? 0 votes 0 votes Please log in or register to add a comment.