Unit 2 (Stack & Recursion)
Unit 2 (Stack & Recursion)
#include <stdlib.h>
#include <stdio.h>
struct Node {
int data;
};
if (top == NULL) {
newNode->next = NULL;
} else {
printf("Node is Inserted\n\n");
int pop() {
if (top == NULL) {
printf("\nStack Underflow\n");
} else {
top = top->next;
free(temp);
return temp_data;
}}
void display() {
if (top == NULL) {
printf("\nStack Underflow\n");
} else {
printf("%d--->", temp->data);
temp = temp->next;
printf("%d--->NULL\n\n", temp->data);
}}
int main() {
while (1) {
scanf("%d", &choice);
switch (choice) {
case 1:
scanf("%d", &value);
push(value);
break;
case 2:
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nWrong Choice\n");
}
Difference Between Recursion and
Iteration
Recursion and Iteration are the basic ways to repeatedly execute a given set of
instructions in any programming language, and hence, every software engineer must
be familiar with these topics. Many software engineering interview problems can be
tackled by the simple use of recursion.
Recursion is when a function calls itself directly or indirectly, and the function calling
itself is called a recursive function. It is mainly used when the solution to a bigger
problem can be expressed in terms of smaller problems.
To terminate the recursion, we use some conditions so that the function knows when
not to make any further recursive call to itself and return; otherwise, it will lead to
infinite recursion once the function is called. Such conditions are called base
conditions in recursion.
For example, let's define steps for Leo in our example above to get the clue he
needs:
The local variables and parameters being passed by value are newly created each
time the function calls itself. They are stored in stack memory whenever a recursive
call is made and are deallocated when the execution of the current function call is
complete. The state of the functions is also stored in stack memory. Thus, each
recursive call consumes some amount of memory on the stack. In case of infinite
recursion or when recursion depth is large enough to exhaust the memory on the
stack, it will cause a stack overflow error.
When to Use Iteration?
Iteration is when we execute a set of instructions repeatedly until the condition
controlling the loop becomes false. It includes initialization, comparison, executing
statements inside the iteration, and updating the control variable.
In iteration, it is necessary to have the right controlling condition; else, the program
may go in an infinite loop.
For example, let’s write an iterative program to help Leo find his clue:
Reference:
https://www.interviewkickstart.com/learn/difference-between-recursion-and-
iteration#:~:text=The%20main%20difference%20between%20these,more%20space%2Defficient%20
than%20recursion.