Skip to content

Instantly share code, notes, and snippets.

@cosminpopescu14
Created December 19, 2018 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cosminpopescu14/7abe1b107d1b7027d2f5dade28d3234c to your computer and use it in GitHub Desktop.
Save cosminpopescu14/7abe1b107d1b7027d2f5dade28d3234c to your computer and use it in GitHub Desktop.
Compute avreage on a stack
// ConsoleApplication22.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
struct Stack
{
int top;
unsigned capacity;
int* array;
};
/*
Create a stack. Size is 0
*/
Stack* createStack(unsigned capacity)
{
Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
if (stack == NULL)
{
printf("stack null");
exit(-1);
}
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity * sizeof(int));
if (stack->array == NULL)
{
printf("couldn't allocate memory !");
exit(-1);
}
}
//top = last_index
int isFull(Stack* stack)
{
return stack->top == stack->capacity - 1;
}
//top = -1
int isEmpty(Stack* stack)
{
return stack->top == -1;
}
void push(Stack* stack, int item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
printf("%d pushed to stack\n", item);
}
int pop(Stack* stack)
{
if (isEmpty(stack))
return -1;
return stack->array[stack->top--];
}
int peek(Stack* stack)
{
return stack->top;
}
int main()
{
Stack* stack = createStack(10);
int sum = 0;
push(stack, 30);
push(stack, 30);
push(stack, 30);
printf("Dim stiva: %d", sizeof(stack));
for (size_t i = 1; i < sizeof(stack); i++)
{
sum += pop(stack);
}
float average = 0.0;
average = (float)sum / (sizeof(stack) - 1);
printf("Avg is - %f", average);
free(stack);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment