![Page 1: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/1.jpg)
UNDB
ESTRUTURAS DE DADOSESTRUTURAS DE DADOS
Prof. Alessandro GonçalvesProf. Alessandro Gonç[email protected]@gmail.com
![Page 2: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/2.jpg)
Revisão de CExercícios – individual (5 min)
1) Crie um programa em C que aguarde a digitação de três variáveis e exiba seus valores de forma concatenada
Ex: usuário digitou '1', 'a', 'x' e a saída a ser exibida é
1ax
![Page 3: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/3.jpg)
Função getchar()
#include <stdio.h>#include <stdlib.h>
main() { char ch; ch=getchar(); printf("%c\n",ch); system("PAUSE"); return 0;}
Lê o teclado até que se pressione ENTER
![Page 4: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/4.jpg)
Função putchar()
#include <stdio.h>#include <stdlib.h>
main() { char ch;
printf("digite uma letra minúscula : ");ch=getchar();putchar(toupper(ch));putchar('\n');
system("PAUSE"); return 0;}
Exibe um caractere
![Page 5: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/5.jpg)
Operadores incremento e decremento
#include <stdio.h>#include <stdlib.h>main() { int i; printf ("Digite um número\n"); scanf("%i", &i); printf("i = %i\n", i); printf("i++ = %i\n", i++); printf("i-- = %i\n", i- -); system("PAUSE"); return 0;}
[variável] ++ Incrementa 1 unidade após a operação[variável] - - Decrementa 1 unidade após a operação
![Page 6: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/6.jpg)
Operadores incremento e decremento
#include <stdio.h>#include <stdlib.h>main() { int i; printf ("Digite um número\n"); scanf("%i", &i); printf("i = %i\n", i); printf("++i = %i\n", ++i); printf("--i = %i\n", --i); system("PAUSE"); return 0;}
++[variável] Incrementa 1 unidade antes da operação--[variável] Decrementa 1 unidade antes da operação
![Page 7: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/7.jpg)
Estruturas de condição - if
If [condicao] {[comandos se verdadeiro]
} else {[comandos se falso]
}
![Page 8: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/8.jpg)
Operadores relacionais
> maior que >= maior ou igual < menor <= menor ou igual== igual!= diferente
![Page 9: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/9.jpg)
Operadores lógicos
&& e|| ou! não
![Page 10: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/10.jpg)
ExercíciosExercícios – individual (5 min)
1) Crie um programa em C que aguarde a digitação de duas variáveis e exiba qual delas é maior
![Page 11: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/11.jpg)
#include <stdio.h>#include <stdlib.h>
main() { int x,y; printf("digite numero 1: "); fflush(stdin); scanf("%i",&x); printf("digite numero 2: "); fflush(stdin); scanf("%i",&y); if ( x > y) { printf("1 eh maior\n"); } else if ( x < y) { printf("2 eh maior\n"); } else printf("são iguais\n"); system("PAUSE"); return 0;}
![Page 12: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/12.jpg)
Operador ternário
main(){int x,y,max;printf("Entre com dois números: ");scanf(“%d%d”,&x,&y);max=(x>y)?1:2;printf("max= %d\n",max);
}
Qual será o resultado ?
Maneira simples de implantar testes com duas possibilidades: sim/não, > ou <=, 0 ou 1...
![Page 13: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/13.jpg)
Estruturas de condição - switch
switch(variável){case constante1:
seqüência de comandosbreak;
case constante2:seqüência de comandosbreak;
default:seqüência de comandos
}
![Page 14: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/14.jpg)
Estruturas de condição - switchmain(){
char x;printf("1. inclusão\n");printf("2. alteração\n");printf(" Digite sua opção:");x=getchar();switch(x){
case '1':printf("escolheu inclusão\n");break;
case '2':printf("escolheu alteração\n");break;
default:printf("opção inválida\n");
}}
![Page 15: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/15.jpg)
Video
Programador x Webdesigner
![Page 16: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/16.jpg)
Array
Vetor unidimensional
Matriz de 1 linha
Ex: int x[9];
É um vetor com 10 posições, cada uma cabendo um inteiro
![Page 17: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/17.jpg)
Pilha – implantação em C
Definição das variáveis
Adicionar 1 elemento – Push
Extrair 1 elemento – Pop
Listar a pilha
Destruir a pilha
![Page 18: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/18.jpg)
Pilha – Definição das variáveis
#include <stdio.h>#include <stdlib.h>
#define MAX 5char *pilha[MAX];int qt = 0;
![Page 19: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/19.jpg)
Pilha – Exibe pilhaExibe_pilha() { int i; printf("\n\npilha atual"); printf("\n-----------\n"); if (qt == 0) { printf("\nPilha vazia."); } else { for (i = qt-1; i >=0 ; i-- ) { printf("---\n”); printf("|%c|\n",pilha[i]); } printf("---\n“); } printf("total de elementos: %i\n",qt); printf("------------------------------------------------\n",qt); }
![Page 20: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/20.jpg)
Pilha – Inclui elemento
push (char *elemento){ if (qt >= MAX){ printf("Estouro de pilha. Impossivel incluir"); exit; } else { printf("\nOperacao PUSH no elemento %c", elemento); pilha[qt] = elemento; qt++; }}
![Page 21: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/21.jpg)
Pilha – Exclui elemento
pop (){ if (qt == 0){ printf(“Pilha vazia. Impossivel excluir"); exit; } else { printf("\nOperacao POP no elemento %c", pilha[qt-1]);
qt--; }}
![Page 22: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/22.jpg)
Pilha – Programa Principal
main (){
exibe_pilha();push(‘a’);push(‘b’);push(‘c’);exibe_pilha();pop();exibe_pilha();pop();exibe_pilha();pop();exibe_pilha();
}
![Page 23: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/23.jpg)
Desafio – inversão de pilha
Crie uma pilha em C. Inverta a pilha e exiba seus resultados.
![Page 24: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/24.jpg)
Pilha invertida – Definição das variáveis
#include <stdio.h>#include <stdlib.h>
#define MAX 5char *pilha[MAX];char *pilhainv[MAX];int qt = 0;Int qtinv = 0;
![Page 25: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/25.jpg)
Pilha – Exclui elemento
char *Pop (){ char *r; if (qt == 0){ printf(“Pilha vazia. Impossivel excluir"); exit; } else { printf("\nOperacao POP no elemento %s", pilha[qt-1]); r = pilha[qt-1]; qt--; } return r;}
![Page 26: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/26.jpg)
Estrutura de repetição em C
Sintaxe:
while(condição) {
comando;}
Ex:
main(){
char ch;while(ch!='a') ch=getchar();
}
![Page 27: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/27.jpg)
Estrutura de repetição em CSintaxe:do{
comando;}while(condição)
Ex:
main(){
char ch; do {ch=getchar();}
while(ch!='a');}
![Page 28: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/28.jpg)
Estrutura de repetição em Cchar ch;printf("1. inclusão\n 2. alteração\n 3. sair\n");printf(" Digite sua opção:");do{
ch=getchar();switch(ch) {case '1':
break;case '2':
break;case ‘3':
printf("sair\n");}
}while(ch!='1' && ch!='2' && ch!='3');
![Page 29: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/29.jpg)
Lista
Pode-se inserir um elemento em qualquer posição
Pode-se excluir qualquer elemento
Serial
início
Fim
![Page 30: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/30.jpg)
Lista encadeada
Elemento 1 aponta para elemento 2 que aponta para elemento 3...
Último elemento aponta para “vazio”
1 2 3 null
![Page 31: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/31.jpg)
Lista encadeada - inclusão
Descobre em qual posição deve entrar
NOVO ELEMENTO aponta para onde o elemento apontava
Elemento anterior aponta para o NOVO ELEMENTO
1 2 3
novo
null
![Page 32: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/32.jpg)
Lista encadeada - exclusão
Varre a lista e descobre o elemento
Elemento anterior aponta para onde o elemento excluído aponta
1 2 3
Elemento excluído
![Page 33: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/33.jpg)
Lista encadeada - problemas
Como saber o início da lista ?
Ponteiros perdidos
Alocação dinâmica de memória
1 2 3
início
![Page 34: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/34.jpg)
Estruturas
Tipo de dado que define nova estrutura de dados, agrupando com tipos primitivos ou complexos.
Exemplo:struct lapis {
int dureza;char fabricante;int numero;
};
![Page 35: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/35.jpg)
Estruturasmain(){
struct lapis p[3];p[0].dureza=2;p[0].fabricante='F';p[0].numero=482;p[1].dureza=0;p[1].fabricante='G';p[1].numero=33;p[2].dureza=3;printf("dureza = %i\n",p[1].dureza);printf("fabricante = %c\n",p[1].fabricante);printf("numero = %i\n",p[1].numero);
system("PAUSE");}
![Page 36: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/36.jpg)
EstruturasExercício (15 min):
Crie uma estrutura para guardar dados de até 100 alunos:Nome, Série, Email
![Page 37: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/37.jpg)
Ponteiros
Tipo de dado que “aponta” para outro dado
Sintaxe:tipo *nomevar;
*nomevar = &variável2;
Como se comporta na memória ?
![Page 38: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/38.jpg)
Ponteiros - exemplomain(){
int x,*px,*py;x=5;px=&x;py=px;printf("x= %d\n",x);printf("&x= %d\n",&x);printf("px= %d\n",px);printf("*px= %d\n",*px);printf("*py= %d\n",*py);x = 7;printf("*px= %d\n",*px);printf("*py= %d\n",*py);
}
![Page 39: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/39.jpg)
Ponteiros – operações++ - aponta para a próxima posição de memória- - aponta para a posição de memória anterior
Sintaxe:*p++*p—
Diferenciar*p++ # (*p)++*p- - # (*p) - -
![Page 40: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/40.jpg)
Ponteiros – operaçõesmain(){
int x[5],*px,*py;
px = &x[0]; x[0] = 2; x[1] = 5; x[2] = 9; x[3] = 15; x[4] = 21; printf("x[0] = %i\n",x[0]); printf("*px = %i\n",*px); *px++; printf("*px = %i\n",*px); printf(“\n”);}
Manipular o código acima com “px” e observar resultados.
![Page 41: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/41.jpg)
Ponteiros – exercíciosExercício – individual (20 min)
Criar um programa em C que aguarde 5 números e armazene em um vetor. Exiba estes números através de ponteiros, de forma descendente.
![Page 42: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/42.jpg)
Função MallocReserva espaço de memória para alocação dinâmica de variáveis
Sintaxe:
Variável = malloc(sizeof (tipo));
Ex:
v = malloc(100* sizeof(tipo));
Que é o mesmo que a alocação estática
int v[100];
![Page 43: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/43.jpg)
Função FreeLibera espaço de memória alocado dinamicamente por alguma variável, destruindo seu conteúdo
Sintaxe:
free(variável);
Ex:
v = malloc(100* sizeof(tipo));free(V);
![Page 44: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/44.jpg)
Ponteiros de estruturasComo gerar uma lista assim ?
5 0 1 3 NULL
![Page 45: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/45.jpg)
Ponteiros de estruturasVer exemplo em C
![Page 46: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/46.jpg)
Lista duplamente encadeada
Elemento 1 aponta para elemento 2 que aponta para elemento 3... e vice-versa
Existe o “ponteiro” de fim, além do início
Último elemento aponta para o ponteiro fim
1 2 3
Início Fim
![Page 47: UNDB ESTRUTURAS DE DADOS Prof. Alessandro Gonçalves Alessandro.inovacao@gmail.com](https://reader036.vdocuments.pub/reader036/viewer/2022062818/5706383e1a28abb8238f031a/html5/thumbnails/47.jpg)
Lista duplamente encadeada
A lista pode ser lida em qualquer ordem facilmente
Se torna um pouco mais difícil para implementar
Muito mais maleável
1 2 3
Início Fim