Ask users to input a series of integers. The input will end with the number 0. A
ID: 3740438 • Letter: A
Question
Ask users to input a series of integers. The input will end with the number 0. Assume users will never input more than 10 integers before input 0. Print all the input numbers to the screen in the reverse order they are input by the users, and print the maximal number of the input numbers to the screen, in a user friendly manner. An example execution of the C-program is as follows (where the underlined are user inputs): you are NOT allowed to use any arrays and array operations. BUT you can use pointers.
Explanation / Answer
Hence you don't want me to use array,I would use stack as it has the property required as asked in the question.It follows the LIFO property i.e, last input first
output which will help us do the reversal problem as asked.
--------------IMPLEMENTATION--------------
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// A structure to represent a stack
struct Stack
{
int top;
unsigned capacity;
int* array;
};
// function to create a stack of given capacity. It initializes size of
// stack as 0
struct Stack* createStack(unsigned capacity)
{
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*) malloc(stack->capacity * sizeof(int));
return stack;
}
// Stack is full when top is equal to the last index
int isFull(struct Stack* stack)
{ return stack->top == stack->capacity - 1; }
// Stack is empty when top is equal to -1
int isEmpty(struct Stack* stack)
{ return stack->top == -1; }
// Function to add an item to stack. It increases top by 1
void push(struct Stack* stack, int item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
printf("%d pushed to stack ", item);
}
// Function to remove an item from stack. It decreases top by 1
int pop(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top--];
}
int main()
{
int n;
scanf(%d,n);
while(n!=0){
stack(push,n);
scanf(%d,n);
}
int max=-1; //Assuming that the integers are non-negative
printf("Reverse order:");
while(!stack.isEmpty){
int get=pop(stack);
if(get>max){
max=get;
}
printf(get);
printf(" ");
}
printf("%d Maximium number in the stack is:",get);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.