Consider the following code. (a) What do the functions push and pop really do? (
ID: 3867446 • Letter: C
Question
Consider the following code. (a) What do the functions push and pop really do? (b) What is the result of the code that follows the function definitions? (c) Why is it safe to make s a simple array instead of a cell array? (d) Why are there sprintf functions in the eval line? function s = push(v, s) s = [v s]: end function [v s] = pop(s) v = s(1): s = s(2: end): end x = {5, 14, 2, '*', 6, '+', '-', 3, '+'} stack = __: for ii = 1: length(x) if isnumeric(x{ii}) stack = push(x(ii), stack) elseif ismember (x (ii), stack) elseif ismember(x(ii), '+*-/' [a stack] = pop (stack): [b stack] = pop (stack): c = eval ([sprintf (a) x(ii) sprintf (b)]): stack = push(c, stack): end end [v stack] = pop(stack): disp(v)Explanation / Answer
a) The push function pushes the element v (operand or operator) of the array onto top of stack s and pop function pops out the top element of the stack s.
b) The result = -26
5 14 2
* is applied to top two elements
5 28
5 28 6
+ is applied on 28 and 6
5 34
- is applied on 5 and 34, 5-34 = -29
-29 3
+ is applied on -29 and 3
result = -26
c)
Simple array can easily implement stack
d)
sprintf function result in values of top two elements of stack s , ie a and b operands on which operator xii is applied by using eval.
eg eval(14 * 2) = 28
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.