You are on page 1of 6

ASSIGNMENT - 2

Name: Franko Francis Slot: A2


Reg no: 20BCE0087 Date: 25-03-2021

1. Recursion Problem

Code:

#include <stdio.h>
int factorial(int n); // function declaration
int main()
{
int n, fact;
printf("Enter a positive integer: ");
scanf("%d", &n); //Taking the number as input from user
fact = factorial(n); // calling function
printf("Factorial of %d = %d", n, fact); // printing output
return 0;
}

int factorial(int n) //function defintion


{
if (n == 1)
{
return 1; // factorial of 1 ia always 1
}
else
{
return n*factorial(n - 1); // calling using recursion
}
}
Output:

2. Stack – Problem

Code:
#include <stdio.h>

int stack[5], top=-1; //declarations


void Push();
void Pop();
void Top();

main()
{
int ch;
do
{

printf("\n Stack Menu: choose an operation");


printf("\n 1. Add an element");
printf("\n 2. Remove an element"); //Giving options to user to choose
printf("\n 3. Display the lastest element");
printf("\n 4. Exit");
printf("\n enter your choice");

scanf("%d",&ch); // Taking input of the option chosen by the user

switch(ch) // Switch case to define each option chosen


{
case 1:
Push(); // calling Push functon
break;

case 2:
Pop(); // calling pop function
break;
case 3:
Top(); // calling top function
break;

case 4:
printf("\n Exit"); // Exit the loop of giving options everytime
break;

default:
printf("\n Enter a valid choice plz"); // Incase if user inputs
value not in option
break;

}
} while(ch!=4); // loop options unless the user gives exit option

void Push() //function definition


{

top++; //incrementing 1
int x;
if(top==4) // checking if the stack is full
printf("Stack overflow");
else
{
printf("\n Enter the element that you want to add");
scanf("%d",&x); // input into x
stack[top]= x; // x value given to stack.
}

void Pop() //function defintion


{
if(top==-1) // checking if the stack is empty
printf("Stack underflow");
else
{
printf("Popped element is %d",stack[top]);
top--;
}

}
void Top() //function definition
{
if (top == -1) // checking if there are no elements in the stack
{
printf("Empty Stack") ; // print Empty stack
}
else
printf("\n ToS is %d",stack[top]); //else print the top most element

}
OUTPUT

You might also like