Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://www.forum-invaders.com.br/vb/showthread.php/40655-Desafio-C-Programa-Caixa
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct
- {
- int size;
- int count;
- int *items;
- } box;
- void swap(int *a, int *b)
- {
- int t = (*a);
- (*a) = (*b);
- (*b) = t;
- }
- int box_add(box *thebox, int item)
- {
- if(thebox->count < thebox->size)
- {
- thebox->items[thebox->count] = item;
- return(thebox->count++);
- }
- return(-1);
- }
- int box_remove(box *thebox, int pos)
- {
- if((pos >= 0) && (pos < thebox->count))
- {
- thebox->items[pos] = 0;
- thebox->count--;
- int i = pos;
- while(i < thebox->count)
- {
- i++;
- if(thebox->items[i])
- {
- swap(&thebox->items[i], &thebox->items[i-1]);
- }
- else
- {
- break;
- }
- }
- return(1);
- }
- else
- {
- return(0);
- }
- }
- int box_find(box *thebox, int item)
- {
- int i;
- for(i = 0; i < thebox->count; i++)
- if(thebox->items[i] == item)
- return i;
- return -1;
- }
- void box_show(box *thebox)
- {
- int i;
- for(i = 0; i < thebox->size; i++)
- printf("[%d]", thebox->items[i]);
- printf("\n");
- }
- void menu(box *thebox)
- {
- int value = 0;
- char option = 0;
- while(option != 's')
- {
- option = 0;
- printf("\nSelecione a opcao desejada\n[a]Adicionar\n[r]Remover\n[p]Procurar\n[m]Mostrar\n[s]Sair\nOpcao: ");
- scanf("%*[^\n]");
- scanf("%*[^arpms]%c", &option);
- scanf("%*[^\n]");
- switch(option)
- {
- case 'a':
- printf("Digite o valor que deseja adicionar: ");
- //scanf("");
- scanf("%*[^1-9]%d", &value);
- value = box_add(thebox, value);
- if(value >= 0)
- {
- printf("Adicionado na posicao: %d\n", value);
- }
- else
- {
- printf("A caixa esta cheia.\n");
- }
- break;
- case 'r':
- printf("Digite a posicao que deseja remover: ");
- scanf("%*[^0-9]%d", &value);
- value = box_remove(thebox, value);
- if(value)
- {
- printf("Removida!\n");
- }
- else
- {
- printf("Posicao invalida!\n");
- }
- break;
- case 'p':
- printf("Digite o valor que deseja procurar: ");
- scanf("%*[^1-9]%d", &value);
- value = box_find(thebox, value);
- if(value >= 0)
- {
- printf("Encontrado na posicao: %d\n", value);
- }
- else
- {
- printf("O valor nao existe na caixa.\n");
- }
- break;
- case 'm':
- box_show(thebox);
- break;
- case 's':
- break;
- default:
- printf("Opcao invalida!\n");
- }
- }
- }
- int main()
- {
- box mybox = {0, 0, NULL};
- while(mybox.size < 1)
- {
- printf("Informe o tamanho da caixa: ");
- scanf("%*[^1-9]");
- scanf("%d", &mybox.size);
- }
- mybox.items = calloc(mybox.size, sizeof(int));
- menu(&mybox);
- free(mybox.items);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement