Programação Avançada em C Usando Algoritmos e Estruturas de Dados Fundamentais

Tamanho: px
Começar a partir da página:

Download "Programação Avançada em C Usando Algoritmos e Estruturas de Dados Fundamentais"

Transcrição

1 Programação Avançada em C Usando Algoritmos e Estruturas de Dados Fundamentais The Ualg Informatics Lab Universidade do Algarve jvo@ualg.pt! " # $% & ' (') ' * +, - (. / 0 $1" 1#,2, 34 & " $ " - 7 6, 8 & $& 2 9 :, ; 67 " - <, = #",16> " = & : : & - $? 1#62 9 6< % $& B % = & : " #7 6, 3@! " 8, 8,, = #6, < % & 8 " C 2 #, $ D " #6>, 8, $ E (F G & #19 H, 3( G, #, > " # 9 :, 7 I J 6, 8 " $1, 367 " - <, K > 6$61" 4 11J LMM7 #",16> " 7 & : : & - $ (& #H M367 " - $" $M2 8 ME (F MJ 1M & 9 " - > 6" 9 :, 7, #1, J, #, = #",16> " = & : : & - $K 'O ' P " 7 & - 8 P 1#" "1K P 9 61" Q.. K P, - R #, - 7 6$7 & K =, 36S& #- 6, T U '. F K A P? (

2 Índice 0. Preâmbulo 1. Introdução! " # $ % & # ' ( 2. Arrays e Ponteiros ) % * & +,! % -

3 ! # ' ( 3. Reserva dinâmica de memória " # ' ( 4. Primeiras noções de complexidade ' # ' ( ' ) ' * * ) & # ' ( 5. Algoritmos elementares de ordenação &! & ) & ) * & ) & & # ' ( 6. Mergesort # ' (

4 7. Quicksort,,,,, %,, &! *, +!,, # ' ( 8. Introdução às listas ligadas % - # ' ( 9. Primeiras noções de Projecto e de Projecto por Contrato # ' IR! ( & + # ' (

5 10. As listas ligadas revisitadas!! % ) & +, # ' ( 11. Tipos de dados abstractos 12. O tipo de dados abstracto pilha $! $!! ' % % $ $ & ' %! '! ' + # ' ( 13. O tipo de dados abstracto fila de espera $!!! $ $ # ' (

6 14. As filas revisitadas!! % # ' ( 15. Implementação em C de ADTs com múltiplas instâncias & & & & $ $!!! % # ' ( 16. O tipo de dados abstracto polinómio +! # ' ( 17. O ADT matriz esparsa,,! %!,,,

7 , *, & # ' ( 18. Primeiras noções sobre árvores # ' ( 19. Árvores binárias %! % # ' ( 20. Acervos e filas com prioridades &!! # ' ( Referências bibliográficas

8 Referência rápida sobre C R1. Preliminares R2. Algumas características do C R3. Exemplo de programa R4. Elementos de sintaxe! %! &! +!,,,, - ) - ) - ) - ) - ) - & ) - + -, ) (

9 - - R5. Controlo de fluxo do programa & %! & % & % & % & & %! & + % ' R6. Funções + +! % + * R7. Arrays e Matrizes, *, " R8. Ponteiros &! % R9. Sinónimos de tipo R10. Estruturas

10 R11. Uniões R12. Campos de bits R13. Enumerações R14. Directivas de Pré-processador R15. Biblioteca de funções & & &! % (! &! %! Índice Remissivo

11 0. Preâmbulo? $ " $1#9 19 #, $ 8 " 8, 8 & $ S, " : J, #1" 8 & 7 & - 9-1& 8 " 7 & : J "1-7 6, $ 7 " - 1#, 6$ 9 " 9 : " $19 8 6& $& 8 " - S& #: 5167, 8 "> " #5, 8 9 6#6# ( B, H, 3" #6, 8, $ 36- H 9, H " - $ 8 " J #& H #, :, < % & K, 36- H 9, H " : = & 7 9 J, 9 : 39 H, # 8 " 8 " $1, 9 " ( $" H 9 #, : " - 1" 9 :, 8, $ 36- H 9, H " - $ 9 $, 8, $, 719, 3: " - 1" 7 & : :, 6$ 1" : J & 8 " J #& >, $ 8, 8, $ (? 36- H 9, H " : = 9 :, 36- H 9, H " : J " 9 " -, K 8 " " $7 #61, 7 & - 8 " - $, 8, K " 1#" :, : " - 1" " S67 6" - 1" K 9 " J " #: 61" 9 : " 3">, 8 & - > " 3 8 " 6-16: 68, 8 " 7 & : & 7 & : J 9 1, 8 & # ( B % & " 6$1" & 9 1#, 36- H 9, H " : 8 ", 31& - > " 3, 719, 3 9 " J " #: 61, :, 6& # - > " 3 8 " J #& 6: 68, 8 " 7 & :, : , K " $J " 7 6, 3: " - 1" - & 9 " $" #" S" #" $ $9, $ 7, J, 7 68, 8 " $ 8 ", #61: 167, 7 & : J & - 1" 6#& $ (? 9-1, #, 6$1& K, 36- H 9, H " : = 1" : : " 7, - 6$: & $ 8 ",2 $1#, 7 < % & $9 S67 6" - 1" $ J, #, J " #: 616# 9 :, 6: J 3" : " - 1, < % &, 8 " 9, 8, 8 " " $1#9 19 #, $ 8 " 8, 8 & $K, 3H & #61: & $K J #& H #, :, $ " : " $: & $6$1" :, $ (? & 7, $, #: & $ " $1#9 19 #, $ 8 " 8, 8 & $ 7 & : = - % & " $1, #" : & $, $" # : 9 61& & #6H 6-, 6$ ( 0 $1, " $7 & 34, $" H 9 68, -, $ 8 6$7 6J 36-, $ 8 "? 3H & #61: & $ " 0 $1#9 19 #, $ 8 " D, 8 & $ " : : 9 61& 7 9 # $& $ 8 " - S& #: 5167, J & # " $1" : 9-8 & S& #, K &, 3H 9 - $ 8 & $ - & $$& $ J #I J #6& $ 7 9 # $& $ 8 " 0 - H " - 4, #6, ( 0 $$" - 7 6, 3: " - 1", & #6H 6-, 368, 8 " 8 & 36> #& " $15 #" 3, 7 6& -, 8, 7 & :,,2 & #8, H " : J #, H : 5167, $" H 9 68, -,, J #" $" - 1, < % & 8, $ :,1 #6, $ (? - & $$, " J " #6-7 6, " : $, 3, 8 ", 9 3, K : & & $ 9 " &, $$9-1& K - % & $" - 8 & 8 6S 7 63K : 9 61, $ > " " $ 6-16: 68,16> & J, #, & #" 7 4 " H, 8 & (? & 3& - H & 8 & 36> #& , : & $ 9 :, 36- H 9, H " : 7 3, #, K 8 " 3" 619 #, S5 7 63K $" : & S#" 9 " - 1" " 8 " $- " 7 " $$5 #6& " - 1 S67 &, $$& 7 6, 8 &, " $1, $ :,1 #6, $ (? J " $, # 8 " $1" " $163& - % & $" J #" $7 6-8 " 8 & #6H & # 9 " 3">, & 8 " $" - > & 3> 6: " - 1& 8 " J #& H #, :, $ 8 " K 8 " $6H -, 8, : " - 1" - & 9 " $" #" S" #" $9, 7 & ##" 7 < % & ( G, #, J #& $$" H 9 6# " $1" & 2 " 716> & K 7 " 8 &, J #" $" - 1, : & $ - & < " $ 8 " J #& " 71& " 8 " J #& " 71& J & # 7 & - 1#,1& 9 " - & $, 9 8, : - & 8 " $" - > & 3> 6: " - 1& $6$1" : 5167 & 8 & $ J #& H #, :, $ $9 2 $" 9 " - 1" $ (

12 B % & J #"1" - 8 " : & $ $" # ", 9 $16> & $ -,, J #" $" - 1, < % & 8, $ " $1#9 19 #, $ 8 " 8, 8 & $ ( = & - 7 " - 1#, : - & $ -, $ " $1#9 19 #, $ 8 " 8, 8 & $ S9-8, : " - 1, 6$K J, #, 8 6$7 9 16#: & $ " 639 $1#, #: & $, $ > 5 #6, $, 31" #-,16>, $ $9, 6: J 3" : " - 1, < % & " : = ( C > & 39 : ", 9 & & K & $6>, : " - 1" - & S6-, 3 9 :, #" S" # - 7 6, #5 J 68, K :, $ 7 & : J 3"1, K $& 2 #" = ( & 8 & $ & $ 7 & - 7 " 61& $ $% & 8 "> 68, : " - 1" 639 $1#, 8 & $ ( A 1636, : & $ " " : J 3& $ 6-1" - $6>, " " 1" - $6>, : " - 1" ( R, " : & - > " 3 8, 6-1#& 8 9 < % & 8 " 9 : 7 & - 7 " 61& :, $ 1, : 2 : 8 " J & 6$, & - > " 3 8, 6: J 3" : " - 1, < % & " : = ( R, " : 6-8, 8 " 9 :, S& #:, $6$1" : 5167, 8 " $8 ", 6-1#& 8 9 < % & 8 & $ " 3" : " - 1& $ S9-8, : " - 1, 6$ 8, J #& H #, :, < % & K 7 & : &, - & < % & 8 " 16J & $ & 9 8 " 16J & $ 8 " 8, 8 & $,2 $1#, 71& $K,1, & $ 1I J 67 & $ :, 6$,>, - <, 8 & $K 7 & : & & 8, $ :,1#6 " $ " $J, # $, $ (?,2 & #8, H " : K J & #1, - 1& K " : 6- " - 1" : " - 1" J #5167, ( G, #, 9 " & 3" 61& # J & $$, 6# S, " - 8 &, $9, J #I J #6,, 9 36, < % & K 7, 8, 7, J 19 3& 1" #: 6-, 7 & : 9 : 7 & - 9-1& 8 " " " #7 7 6& $K 1" - 1,16>, : " - 1" & #8 " -, 8 & $ J & # & #8 " : 7 #" $7 " - 1" 8 " 8 6S , 8 " ( 8 " - 16S67, # " #" J #& 8 9 6# 2 &, $ J #5167, $ 8 " J #& H #, :, < % & 1" : > 6-8 &, $" # #" 7 & - 4 " 7 68 & 7 & : & 8, $, 716> 68, 8 " $ :, 6$ " S67, " $ - & J #& 7 " $$& 8 " " - $6- & M, J #" - 8 6, H " : 8, J #& H #, :, < % & ( D " S, 71& K J #& H #, :, # 8, & #8 " : 8 " 7 & : 9-67, # ( = & : 9-67, # 7 & :, : , K :, $ S9-8, : " - 1, 3: " - 1" 7 & : 9-67, # " - 1#" J #& H #, :, 8 & #" $ ( P,2 " # 3" # 7 I 8 6H & " 68 " - 16S67, # 7 I 8 6H & 8 " 9 " J & $$, $" # 1636, 8 & 9, - 8 & - " 7 " $$5 #6& K 1& $$6: 1% & 6: J & #1, - 1" 7 & : & $,2 " # " $7 #"> " # 7 I 8 6H & (? & $" H 9 6#: & $ 9 :,,2 & #8, H " : J #, H : 5167, 9 $, - 8 & 6-1" - $6>, " " 1" - $6>, : " - 1" " " : J 3& $ 8 " 2 &, $ J #5167, $ 8 " J #& H #, :, < % & " : = " $J " #, : & $ " $1, # 7 & - 1#62 9 6# J, #, & $9 7 " $$& 8 " $1" J #& 7 " $$& 8 " " - $6- & M, J #" - 8 6, H " : (? J #& H #, :, < % & " " $1#9 19 #, 8 " 8, 8 & $ " : = 9 : 1" :, #" 3,16>, : " - 1" :, 8 9 #& 7 & :, J 367, < " $ " : >, #6, 8 $$6:, $ 5 #", $ 8, " - H " - 4, #6, 6- S& #: 5167, K 8, 6- S& #: 5167, 8 " H " $1% & " 8 & $ 7 & : J 9 1, 8 & #" $ " : H " #, 3( 0-7 & - 1#, : & $, J 367, < " $ 8, $ " $1#9 19 #, $ 8 " 8, 8 & $ " : 5 #", $ 9 " > % & 8 " $8 " & $ $6$1" :, $ & J " #,16> & $K, & $ 7 & : J 63, 8 & #" $K " 6-1" 36H - 7 6,, #16S67 6, 3( D " $1"

13 J & - 1& 8 " > 6$1, K " 8, 8 & & 7 & - 1" 8 & ",,2 & #8, H " : J #, H : 5167, $" H 9 68, K & 36> #& 6-1" #" $$, - 1" J, #, 9 :,, : J 3,, , L " - H " - 4 " 6#& $K 6- S& #: 5167 & $K " $19 8, - 1" $ " 8 & 7 " - 1" $ 9-6> " # $615 #6& $K :, $ 1, : 2 :, & 9 1#& $ J #& S6$$6& -, 6$ 9 " 9 " #" :, 719, 36, # & $ $" 9 $ 7 & - 4 " 7 6: " - 1& $ - & : 2 61& 8 " 9 : J #& H #, :, 8 ", J #" - 8 6, H " :, & 3& - H & 8, > 68, K ", &, 9 68, 71, 9 " 9 " #, J #" - 8 " #, 8 " $" - > & 3> " # & $ $" 9 $ J #& H #, :, $ 8 " 9 :, S& #:, $6: J 3" $ :, $ $6$1" : 5167, (? & #H, - 6, < % & 8 & 7 & - 1" 8 & 1& #-, & 36> #&, 7 " $$ > " 3, & - & > 6< & " : J #& H #, :, < % & :, $ 1, : 2 :, & 3" 61& # " - > & 3> 68 & 4 5 : 9 61& - & 8 " $" - > & 3> 6: " - 1& 8 " J #& H #, :, $ ( C 1" 1& 8 & 36> #& " $7 #61& " : 6: " $ B " & :, - ( C 7 I 8 6H & = " $7 #61& " : Arial Narrow K 7 & : & " : #include <stdio.h> /* Primeiro programa. */ int main() { } printf( Olá mundo! ); return 0; C $ 7 & : " - 15 #6& $, & 7 I 8 6H & $% & " $7 #61& " : G & #19 H 9 $ ( G & # 9 :, 9 " $1% & 8 " 9-6S& #: 68, 8 " K 1& 8 & $ & $ 68 " - 16S67, 8 & #" $ - & : " $ 8 " >, #65> " 6$K S9 - < " $K "17 ( $% & " $7 #61& $ " : - H 3 $ ( G, #,, 3 : 8 & $ " 3" : " - 1& $ H #5 S67 & $ 8 " : & 8 " 3, < % & 7 & : & & $ 8 6, H #, :, $ 8 " " $1#9 19 #, & 9 S39 & H #, :, $K 9 7, 6, 8 " 1" 1& 7 & : 36: 61" $, J #"1& J, #, 68 " - 16S67, # & $ " 3" : " - 1& $ 8 " $6-1, " 8, 36- H 9, H " : (

14 ? & $ : " 9 $, 39 - & $ J " 3& $" 9 " $1 : 9 3& J " #:, - " - 1" (? & $ 7 & 3" H, $ 8 & D " J, #1, : " - 1& 8 " 0 - H " - 4, #6, 0 3" 71#I - 67, " - S& #: 5167, 8, R, , 8 " 8 " = 6-7 6, $ " " 7 - & 3& H 6, 8, A - 6> " # $68, 8 " 8 &? 3H, #> " 9 " 7 & : 6H & 1 : 3" 7 7 6& -, 8 & 8 6$7 6J 36-, $K & - 8 ", $ :,1 #6, $, H & #,, J #" $" - 1, 8, $ 1 : > 6-8 &, $" # 3" 7 7 6& -, 8, $ ( 0 : J, # , # H & $1, #6, 8 ", H #, 8 " 7 " # G, 9 3,! " - 19 #, J " 3& $" 9, J & 6& -, " 3,2 & #, < % & 8, J #6: " 6#, > " # $% & " 3" 71#I - 67, 8 & $, J & - 1, : " - 1& $ 8, 8 6$7 6J 36-, G #& H #, :, < % & ( " 7 & - 4 " < & 6H 9, 3: " - 1" & $ : " 6& $ " &, : 2 6" - 1" J #& J 7 6& #" S3", < % & J #& J & #7 6& -, 8 & $ J " 3, A - 6> " # $68, 8 " 8 &? 3H, #> " " J " 3& 9, L 4 " A, 3H - S& #:,167 $ ;,2 (

15 1. Introdução A :, 3H & #61: & 7 & ##" $J & - 8 ", 9 :, S& #:, 8 " #" $& 3> " # 9 : J #& 2 3" :, (, 6$ 7 & - 7 #"1, : " - 1" K 9 :, 3H & #61: & 9 : 7 & - 9-1& S6-61& $ 8 " 6- $1#9 < " $ J #" 7 6$, $ " & #8 " -, 8, $ 9 " #" $& 3> " 9 : 8 "1" #: 6-, 8 & J #& 2 3" :, ( A :, 3H & #61: & 8 "> " $,16$S, " # 9 : 7 & - 9-1& 8 " J #& J #6" 8, 8 " $ 7 & : & L ' ( D "> " 1" #: 6-, # - 9 : 7 & - 9-1& S6-61& 8 " J, $$& $ S " E ( =, 8, J, $$& 1" : 9 " $" # J #" 7 6$, : " - 1" 8 " S6-68 & 8 " S " Q ( =, 8, J, $$& 8 "> " $" # $9 S67 6" - 1" : " - 1" $6: J 3" $ " S , U ( D "> " #" $& 3> " # & J #& 2 3" :, " : 1" : J & 163 J, #, 9 ", $& 39 < % & J #& , 1" - 4, 6-1" #" $$" " S , F ( " :. & 9 :, 6$ " - 1#, 8, $ " / ( " : ' & 9 :, 6$ $, 8, $ ( B, #" $& 39 < % & 8 " J #& 2 3" :, $ 9 $, : & $, 3H & #61: & $ 7 9 & 8 " $" : J " - 4 & J & 8 " 8 " J " - 8 " # " : 9 61& 8, $ " $1#9 19 #, $ 8 " 8, 8 & $ 9 " , : ( 8 & - & $$& 6-1" #" $$" 8 " $" - > & 3> " #, 3H & #61: & $ " S67 6" - 1" $ ( 9 61, $ > " " $K, - 67, 4 6J I 1" $" 9 " 1" #" : & $ 8 " " - 7 & - 1#, # 9 :, $& 39 < % & J, #, 9 : 7 " #1& J #& 2 3" :, " $15 -, , < % & 8 ", 3H & #61: & $ " S67 6" - 1" $ ( A :, " $1#9 19 #, 8 " 8, 8 & $ - % & :, 6$ 8 & 9 " 9 :, S& #:, 8 " & #H, - 6, # >, 3& #" $ #" 3, 7 6& -, 8 & $ " " : 7 9 & $ " " : J 3& $ $" " :, $ :,1#6 " $K, $ 36$1, $K, $ 5 #> & #" $ " & $ H #, S& $ ( B & " $19 8 & 8, $ " $1#9 19 #, $ 8 " 8, 8 & $, - & < % & 8 " 16J & $ 8 " 8, 8 & $ 9 :, - & < % & 7 " - 1#, 3(

16 ? :, 6& # J, #1" 8, $ 36- H 9, H " - $ 8 " J #& H #, :, < % & J #& J & #7 6& -, : J " 3& : " - & $ 9 : 7 & - 9-1& : - 6: & 8 " 16J & $ 8 " 8, 8 & $ J #6: 616> & $ & 9 J " S6-68 & $K, $$6: 7 & : &, 7, J, 7 68, 8 " 8 " 7 & - $1#9 6# - & > & $ 16J & $K & 9 16J & $ 8 " S6-68 & $ J " 3& , 8 & # (, $, S6-, 3 & 9 " 9 : 16J & 8 " 8, 8 & $ A : 16J & 8 " 8, 8 & $ 9 : 7 & - 9-1& 8 " >, 3& #" $ " 9 :, 7 & 3" 7 < % & 8 " & J " #, < " $ $& 2 #" " $$" $ >, 3& #" $ ( 0 " : J 3& L C 16J & 8 " 8, 8 & $ 7 & - $6$1" 8 & $" H 9 6-1" 7 & - 9-1& 8 " >, 3& #" $ int. K 'K E K (((K K B INT_MAX INT & - 8 " INT " #" J #" $" - 1, : & $ >, 3& #" $ : 5 6: & $ " : - 6: & $ 8 & $ 6-1" 6#& $ (? $ MAX INT MIN & J " #, < " $ $& 2 #" & $ $% & : 9 61, $ " " : & $ & J " #, 8 & #" $, #61: 167 & $ " K 1" $1" int +, -, *, / % 8 " 6H 9, 38, 8 " " 8 " $6H 9, 38, 8 " K & J " #, < " $ 8 ",1#62 9 6< % & K "17 ( G & # 9 " #, % &, - & < % & 8 " 16J & 8 " 8, 8 & $ 1% & 6: J & #1, - 1" 0 $$" - 7 6, 3: " - 1" J & # 1# $ & #8 " - $ 8 " #, " $ ( ' ( A : 16J & 8 " 8, 8 & $ J #& J & #7 6& -, 9 :, 6-1" #J #"1, < % & J, #, & $ >, 3& #" $ H 9, #8, 8 & $ " : : " : I #6, E (? 9 8, :, & #H, - 6, # ", 8 & 7 9 : " - 1, # 7 & - 7 " 61& $ Q ( G & $$ , : 9 " & 7 & : J 63, 8 & #, 9 8 " & J #& H #, :, 8 & # -, > " #6S67, < % & 8, 7 & ##" 7 < % & 8 & $" 9 7 I 8 6H & ( 0 $1" $, $J " 71& $ $" #% & 639 $1#, 8 & $ 8 " $" H 9 68, (!, : & $ 7 & : " <, # J & # > " # & 9 ", 36- H 9, H " :? B P = S#" 9 " - 1" : " - 1" #" S" #68, 8, 9 6 J, #,, S#" - 1" $6: J 3" $: " - 1" J & # - & $ & S" #" 7 " J, #, & #H, - 6, # " J #& 7 " $$, # 6- S& #:, < % & ( 0 : = K, $,2 $1#, 7 < " $ 8 & : 9-8 & #", 3 $% & K " : 316:,, $" K #" J #" $" - 1, 8 & $ J " 3& $ 16J & $ J #6: 616> & $ 8 " 8, 8 & $ L char K int, float, double ( 0 : = K 9 $, : & $ 9 : - : " #& S6 & 8 " 2 61$ J, #, #" J #" $" - 1, # - : " #& $ (? $$6: K & $ $% & J & # int - " 7 " $$68, 8 " 6-1" 6#& $ 9 " > 6> " : 8 " - 1#& 8 " 36: 61" $ " $J " 7 S67 & $ 9 " 8 " J " - 8 " : 8 & - : " #& 8 " 2 61$ 9 " 9 $, : & $ J, #, & $ #" J #" $" - 1, # (

17 G, #, S, , #,, J #" $" - 1, < % & K >, : & $ 7 & - $68 " #, # 9 : 7 & : J 63, 8 & # 8 " = & - 8 " & $ 6-1" 6#& $ $% & #" J #" $" - 1, 8 & $ 9 $, - 8 &, J " -, $ Q 2 61$( C $ >, 3& #" $ J & $$ > " 6$ J, #, " $$" $ Q 2 61$ $% & L... K.. 'K. '. K. ' 'K '.. K '. 'K ' '. " ' ' ' C $ 7 & : J 63, 8 & #" $ 8 " = 9 $, : & $6$1" :, 8 " - 9 : " #, < % & #6& -,19 #, 3 J, #, #" J #" $" - 1, # 6-1" 6#& $ $" : $6-, 3K J " 3& 9 " L ' '. '. E. ' ' Q '.. U '. ' F ' '. / ' ' ' O G & #1, - 1& K & - : " #& 8 " 6-1" 6#& $ 8 6S" #" - 1" $ 9 " J & 8 " #" : & $ #" J #" $" - 1, # 9 $, - 8 & Q 2 61$ 8, 8 & J & # E * ( 0 $$" $ 6-1" 6#& $ 7 & : " <, : " :. " > % &,1 ' O ( 0 $1" $ $% & & $ 36: 61" $ 8 " >, #6, < % & K & 9, H, :, 8 " >, 3& #" $ J & $$ > " 6$K J, #, 6-1" 6#& $ $" : $6-, 3 8 " Q 2 61$( P " " : > " 8 " Q 2 61$ 16> " $$" : & $ * K " - 1% & J & 8 " #6, : & $ #" J #" $" - 1, # E E F / >, 3& #" $ 8 6S" #" - 1" $ ", H, :, 8 " >, 3& #" $ $" #6, 8 "., ' E F F ( B & 7, $& H " #, 3K J, #, 9 : 7 & : J 63, 8 & # 8 " 2 61$K (K J, #, 9 : 7 & : J 63, 8 & # 9 " #" J #" $" - 1" n 6-1" 6#& $ 9 $, - 8 & 2 61$K " n 6$16#% & E 6-1" 6#& $ 8 6S" #" - 1" $K $" - 8 & & $ 36: 61" $ 8 " >, #6, < % &. " n E ' ( C 9 " > 6: & $ > & J, #, 6-1" 6#& $ $" : $6-, 3(? #" J #" $" - 1, < % & 8 " 6-1" 6#& $ 7 & : $6-, 3 S" 61, 9 $, - 8 &, 9 63&, 9 " $" 7 4, :, #" J #" $" - 1, < % & " : 7 & : J 3" : " - 1& J, #, E (

18 ! & 31" : & $, & - & $$& 7 & : J 63, 8 & # 8 " Q 2 61$( C $ >, 3& #" $ J & $$ > " 6$ J, #, " $$" $ 1# $ 2 61$ 7 & , :, $" # & $ : " $: & $ L... K.. 'K. '. K. ' 'K '.. K '. 'K ' '. " ' ' ' ( 0 : 7 & : J 3" : " - 1& J, #, E K & 2 61 :, 6$ " $ 9 " #8, - & - : " #& & 9 & 2 61 :, 6$ $6H - 6S67,16> & 9 $, 8 & J, #, , # & $6-, 3 8 & - : " #& ( P " " $$" 2 61 S& #. " $1, : & $ -, J #" $" - <, 8 " 9 : - : " #& J & $616> & $" " $$" 2 61 S& # ' 1" #" : & $ 9 : - : " #& - " H,16> & ( B : " #& $ J & $616> & $ 7 & : " <, : J & #. " & $ #" $1, - 1" $ 2 61$ #" J #" $" - 1, : & >, 3& #,2 $& 39 1& 8 & - : " #& ( B : " #& $ - " H,16> & $ 7 & : " <, : J & # 'K $" - 8 & & $" 9 >, 3& #,2 $& 39 1& 8, 8 & J " 3, 8 6S" #" - <, " - 1#", 9, - 168, 8 " 8 " - : " #& $ 9 " $" 7 & - $" H 9 " : #" J #" $" - 1, # 7 & : & - : " #& 8 " 2 61$ #" $1, - 1" $ " & >, 3& # " : #6& -,19 #, 3 #" J #" $" - 1, 8 & J & # " $$" $ : " $: & $ 2 61$( ' '. '. E. ' ' Q U '. ' Q ' E ' ' '? $$6: K " : 2 & #, 9 : 6-1" 6#& 7 & : $6-, 3K #" J #" $" - 1, 8 & 9 $, - 8 & Q 2 61$K 1" - 4,, 6-8, E * >, 3& #" $ J & $$ > " 6$K & $ $" 9 $ 36: 61" $ 8 " >, #6, < % & $% & " ' Q ( P " 16> " #: & $ * 2 61$ " - 1% &, H, :, 8 " >, #6, < % & >, 6 8 " 'E *, ' 'E O ( B & 7, $& H " #, 3K 9 : 6-1" 6#& 7 & : $6-, 3 #" J #" $" - 1, 8 & 9 $, - 8 & n 2 61$ 1" #5 E n >, 3& #" $ 8 6S" #" - 1" $ " 9 :, H, :, 8 " >, #6, < % & 9 " >, 6 8 " E, ' ( A :, :, - " 6#, 8 " $,2 " #: & $ 9, 6$ $% & & $ 36: 61" $ 8 " >, #6, < % & J, #, & $ 6-1" 6#& $ - & 7 & : J 63, 8 & # 8 " = 9 " " $1, : & $, 9 $, # #" 7 & ##" # $ :, 7 #& $ 8 " S6-68, $ - & S67 4 " 6#& 8 " 7,2 " <, 34 & limits.h. G, #, & $ 6-1" 6#& $K " $$" $ 36: 61" $ $% & 8, 8 & $ J & # L INT MIN " INT MAX (

19 0 : = - " H & 7 6, : & $ " $J, < & " J #" 7 6$% & " $7 & 34 " - 8 & " - 1#" double ou long double ( char, int, long int " " - 1#" float,!, 3& #" $ 1 J 67 & $ J, #,, 3H 9 - $ 16J & $ " : 7 & : J 63, 8 & #" $ 8 " '/ 2 61$ # 7 4, # * 2 61$., E F F $4 & #1 " 6-1 '/ 2 E O / *, Q E O / O 9 - $6H - " 8 $4 & #1 " 9 - $6H - " '/ 2 61$., / F F Q F 3& - H Q E 2 'U O U * Q / U *, E 'U O U * Q / U O 9 - $6H - " 8 3& - H Q E 2 61$., U E T U T / O E T F S3&,1 Q E 2 61$ J #" 7 6$% & O 8 H 61& $ S& 9 2 3" / U 2 61$ J #" 7 6$% & 'F 8 H 61& $ 3& - H 8 & 9 2 3" *. 2 61$ J #" 7 6$% & 'T 8 H 61& $! 6: & $ J & #1, - 1& 9 " #" J #" $" - 1, < " $ 6H 9, 6$ $6H - 6S67, : K " : H " #, 3K 7 & 6$, $ 8 6S" #" - 1" $ J, #, 16J & $ 8 6S" #" - 1" $ (! ", : & $, H & #, 7 & : & & $ 16J & $ 8 " 8, 8 & $ - & $, 9 8, :, & #H, - 6, # ", 8 & 7 9 : " - 1, # 7 & - 7 " 61& $ ( A : J #& H #, :, & #H, - 6, & $ 8, 8 & $ #" 3, 7 6& -, - 8 $ 7 & : & $ 7 & - 7 " 61& $ 8 & J #& 2 3" :, " : #" $& 39 < % & ( G & # " " : J 3& K 9 : " 8 61& # H #5 S67 & & #H, - 6, & $ $" 9 $ 8, 8 & $ 8 " S& #:,, 9 " #" J #" $" - 1" : J & - 1& $K 36-4, $ " S6H 9 #, $ H " & : 1#67, $ ( A :, & #H, - 6, < % & 8 " 8, 8 & $ 8 " $1" 16J & 1& #-, & J #& H #, :, :, 6$ 3" H > " 3K K :, 6$ S " 7 & : J #" " - 8 " # " :, 6$ S " :, - 1" # K K 8 " " $1" - 8 " # & 9 : " 34 & #, # ( G & # " " : J 3& K 7 & - $68 " #" : & $ 9 " " : > " 8 " 6: J 3" : " - 1, #: & $ & " 8 61& # H #5 S67 & 7 & : J 3"1&, J " -, $ - " 7 " $$5 #6& 7, , # 8 6$1-7 6, $ " ", -, $ " - 1#" J & - 1& $ 8 & J 3, - & (

20 ! "# $ "% &! '# $ '% ( ) 0 -/ + / *,* *,* = ) int main() { float a, b, c, d; printf("abssissa do ponto A:"); scanf("%f", &a); /*... */ printf("dist: %f \n", dist(a, b, c, d)); return 0; } 78 dist ) double dist(float x, float y, float z, float t) { float dx = x - y; float dy = z - t; return sqrt(dx * dx + dy * dy); } 2 sqrt ( math.h

21 ( dist x y z t 2 ( ! "#$"$ #% %&#!&%' ()$ %&#$ * %' +, %, ) -!.!/"$ %0'!/"!,! "1* ), 12!#!/"! - 3$! * ),!'!# ' %/ 1* $ 0%, ) 4)' ) $ ' % $ / 1, %,! )' $ ' / )'! 4)' $ ' - ' % 3$! * ),!' ) %1/, % #!2!#1# % 4%, % 4)' * )/!/"! 1/, 1. 1,$ %0,! $ ' 4!#"), %, ) *!0) / )'! 8 4%, % 4)' * )/!/"! 1/, 1. 1,$ %0 49 %' %#!' ) '!' : #),!, %, ) 8 ; / 14% )*!#%<=! 3$!! ">),!21/ 1, % * %#% %! "#$"$ #% >) ) %4! ) % '!' : #) - % 4?* 1%! % %"#1: $ 1<>) ),!' ) $ %# %! "#$"$ #% * %#%,!21/ 1# $ ' "1* ),!, %, ) 3$! #!* #!!/"! * )/") A struct point { float x; float y; };!! 4#!.!#A struct point A, B;

22 A.x=1.0; A.y=1.0; B.x=4.0; B.y=2.0; )' ) % )*!#%<>),! 4?* 1%! ",!21/ 1, % * %#% %! "#$"$ #% - * ),!' ) * % %#, 1#!4"%'!/"!! "#$"$ #% 4)' ) %#&$ '!/"),! 2$ / <=! )#!!' * 0) A double dist(struct point p, struct point q) { }; float dx = p.x - q.x; float dy = p.y - q.y; return sqrt(dx * dx + dy * dy); 0"!#/ %"1. %'!/"! * ),!# %' ) "!# $ %, ) % * %0%. #% 49 %.! typedef * %#% 1/ 2)#' %# ) 4)' * 10%, )#,! 3$! 3$!# %' ) 4#1%# $ ' / )'! * %#% ) / ). ) "1* )! % 1' 2%4101"%# %! 4#1"% 8 typedef "!' %!&$ 1/"! 1/"%! A typedef <tipo elementar ou estruturado> <novo identificador>!' * 0) A typedef int Number; ) 4% ), %! "#$"$ #% point "!#1%' ) - typedef struct { float x, y; } point;! * )#"%/") * ),!# %' ) "!#! 4#1") % 2$ / <>) %/"!#1)#, %!&$ 1/"! 2)#' % A double dist( point p, point q) { /* como antes */ }; )"!! 3$! ) typedef / >) 1/"#),$ $ ' / ). ) "1* ) %*!/ % $ ' 1/?/ 1' ) ()$ $ ' % %: #!. 1%"$ #%+,! $ ' "1* ) 3$! * ), 1%!#! *!41214%, ),! )$"#% 2)#' % 8 * #) &#%' % 4)' * 0!")!#1%

23 #include <stdio.h> #include <math.h> typedef struct { float x, y; } point; double dist( point, point); int main() { point a,b; printf("primeiro ponto:"); scanf("%f", &a.x); /*... */ printf("dist: %f \n", dist(a,b)); return 0; } } point. }! " # double dist(point p, point q) { }; float dx= p.x - q.x; float dy=p.y - q.y; return sqrt(dx * dx + dy * dy); } $ % # $ & ' " %"$ #%0'!/"! 3$! / %, % / ) 1' *!,!,! %&#$ * %# '!' : #),!, %, ) 3$!! %'!0! * #?*#1)! "#$"$ #% 8!' * 0) A typedef struct circle{ point center; float radius; } /* ou o que é a mesma coisa: */ typedef struct{ point center; float radius;

24 } circle;! " # "" $ " %!&% # " &' " ( circle acircle, bcircle; acircle.center.x = 0.0; acircle.center.y = 0.0; acircle.radius = 1.0; bcircle = acircle; /* OK*/ ) *!"! " %!& # + (, $ " $ & &% - " ".!"/ + $! " &" & * * 0& # 1 ) 2 $ " $ & #!" " ' # % 3 )!" % & ' # :; <= >!!" " &" 2 " #? *!* &!" " " % & 3 * % " ' #

25 ?! "% &" * & & $ 3$ &" * char & -. int & # "!" struct s { int i,j; }; &" i " &" j # > " &&" & & % #? 2$ * $ $ 0 ' #? & $ " # & % " % 3 " # + ( union u { char lowbyte; int word; };

26 $ * $ * " char lowbyte word % ' # & 2" " * $ " & $ lowbyte word word $ lowbyte # ( union u aunion; aunion.word=0x105; /* 105H = 261D */ printf("%d", aunion.lowbyte); > ( 0 * ' + * 3 & " " " " * lowbyte $ * highbyte, " ( typedef struct { unsigned char low, high; } lhbytes;

27 typedef union { lhbytes byte; int word; } bytesword; + " ( bytesword bw; bw.word =261; printf("%d %d \n", bw.byte.low, bw.byte.high); # + " * " * ( bytesword bw; bw.byte.low =5; bw.byte.high =1; printf("%x \n", bw.word); 2 ( + (, " % & * 2 $ " " $ # #$ & " " & # " % 0!&" " " &" -" & " " ".# > " * & 2% $ *! 3 *! *!" & "! % & && " & $ & "!&% &&% &' # 0!& $ &!&

28 " & " & & % && " &! 3&!& " % " $ & " # 45 5 < : = # " * & " " &% # # " * " & & " & " &% # # + & * " " * " " " % * 0 $ & " (. ". " " &. " ".! &. "!. # + & * " " * & # # " " # #include <stdio.h> #include <string.h> #include <ctype.h> #define COMPMAX 128 typedef struct {int letras, espacos, palavras;} contador; int main() { char dentro=0, texto[compmax]; int i; fgets(texto,compmax,stdin); for (i=0; i<strlen(texto); i++) { if (!dentro &&!isspace(texto[i])) { dentro=1; printf("%c",texto[i]); }

29 else if (dentro && isspace(texto[i])) { dentro=0; } } /* printf("\n%d %d %d \n", c.letras, c.espacos, c.palavras); */ return 0; }.. &. + * *!2 #! &" " $ #! &"!* " & - &". & #! * "! 3!&

30 2. Arrays e Ponteiros & ) " " & & " & " " " - R.# 2 " " " & R R & " " & " # n * " & - & ".$ $ " " $ " d X Y X " & " $ * (x1, x2,..., xn) Y (y1, y2,..., yn) " % ( = d = =? & "$ & * 3 &% * 0 2 "! % & " # + " * " * & $ " "$ & R & & $ & R $ " % 3 &" 0 # * & 2 * * 3 " % $ ) * " % " n $ 3 '! " % * & & " & # " % " 2 " * " " % 0& &( # % 0 " " * 2 % #, 3 & &% $ $ * % & )" & " # + $ )" & 3 #

31 ? $ 3 & " # " " * & & " & " " R # & " & " "! ( ai int ai[10]; & " ai "! ( " & 2% ai[0] " # /* 1ª Versão */ #define N 10 int i; int ai[n]; ai[0]=1; for( i=1; i<n; i++) ai[i]=0; % #define N 10 int i; for( ai[0]=1, i=1; i<n; ai[i++]=0); > " % % " & " # 3$ int ai[]={1,2,3}; int bi[3]; bi=ai; + > *!2 % ( for( i=0; i<3; i++) b[i]=ai[i];

32 " for( i=0; i<3; bi[i]=ai[i++]);? * * # + & $ ( #define N 10 typedef struct { float x, y;} point; point apoints[n]; apoints[0].x=0.0; apoints[0].y=0.0; /* Programa que calcula a distância entre dois pontos de R n */ #include <stdio.h> #include <math.h> #define N 10 double distn(float[], float[], int); void read(float[], int); int main() { float x[n], y[n]; printf( Ponto X: ); read(x, N); printf( Ponto Y: ); read(y, N); printf( d= %f, distn(x, y, N)); return 0;

33 } double distn(float p[], float q[], int n) { int i; float sum = 0.0; for (i=0; i<n; i++) sum += (p[i]-q[i])* (p[i]-q[i]); return sqrt(sum); } void read(float a[], int n) { } int i; for(i=0; i<n; i++) { printf( Coordenada %d, i+1); scanf( %f, &a[i]); printf( \n ); } > 3 "!&" " & " #!& " &!& & " )" & " % " " * " #? $!& " %!2!&% )" &#? 3 $ 3 " & " % - ". " % # + & " " & & " " & &" & '$ * " &" #! " " & " ai $ & " # " * -. & % ' * & & #

34 int ai[10]; " 3 * & ' > & " " & " " #, 2 * " & * & & " " % $ " 0 sizeof(<tipo>) "! % # + " -" ". # sizeof size_t <: =, " - ". & 0 * " 0 # " 0* " & " " " (

35 char c=3; char *ptr_c; /*declaração de ponteiro para um char */ * "!2 % ptr_c=&c; /*endereço do char c */ "% ptr_c!& &!? * 3 $ 0 & "!& -".$ $ -. & 2% -.#? & " # + " " " 3& void* # * " 0 &" void* # * &" 0 " ptr_c $ & *ptr_c $ & ( printf("%c", *ptr_c);, & 3 * & -*. " " " & " # + " ( #define N 10 int ai[n]; ai[2]== *(a+2); /* É sempre verdade */

36 *! & & & * " 3 & " 0 & $ " " $ * " " sizeof " * % # ) * int ai[3]; int bi[3]; /*... */ bi=ai; /*ERRO*/ * " " & "! " % $ & 0 " " " #? " & * & $ & % " * & % $ * "!" %! " # $ &"! " % * & & ( int soma( int *, int); int main() { int a[]={1,2,3}; int n = sizeof(a) / sizeof (int); pritnf("%d", soma(a, n)); return 0; }; int soma( int *x, int n) { int i, s=0; for(i=0; i<n; s+=x[i++]); return s; & " " & 3 ) * 3 " " sizeof #

37 < ; <= 9 <: = #? -. " " # > 3 " n "3 "!" - 0. " " " & " # int a[3]; int *ptr=&a[1]; # ptr+1; ptr-1; * " & $ & " & $ " ptr 3 " & " - & ". ' *!* " " " & -. " " # + 3 " & 2 & % " 0 " # + " char float " $ * " ' & 3 & 3!" #? " * " & " 2 # + ( int a[5], *ptr1, *ptr2, i; ptr1=&a[1]; ptr2=&a[2]; i = (int) (ptr2-ptr1); " & % (ptr2-ptr1) " ptr_diff_t * 0!" stddef.h # #? & - " &" $ >, >=, <, <=, ==,!=. " * " & " 2 #

38 #?!& " " * ( # # > " / # # 2 " / (void *) 0 /* ou */ NULL " " " < = < : :. int x, *ptr_x, y; ptr_x=&x; *ptr_x=0; y=*ptr_x+3;. void swap( int *, int *); int main() { }; int i=1, j=2; printf("i:%d, j:%d \n",i,j); swap(&i,&j); printf("i:%d, j:%d \n",i,j); return 0; void swap( int *x, int *y) { int tmp; tmp=*x; *x=*y; *y=tmp; :9 = + " 3 &&$ & % 0 && " $ & &' " 3& 3 2 #? & " & " '\0' :

39 char str[]={'a','b','c','\0'}; > &$ 3 & " ( char str[]="abc"; 3 " & &" &" " & *!2 " $ " " # 1 " &0! " & " <string.h> " #? $! " % " $ * " & " string, strlen " $ # #$ " " && & " && " # +! " % 0 "! "( /* 1ª Versão: usando arrays */ int strlen1( char s[]) { int len=0; while (s[len]) len++; return len; }; /* 2ª Versão : usando ponteiros */ int strlen2( char *s) { char *p=s; while (*p) p++; return p-s; }; * a while (*p!='\0') p++; /*Programa de teste */ int main() { char str[]="abc"; printf(%d",strlen2(str));

40 } return 0; " % 0 % " "" char str[]="abc"; /* array */ char *ptr="abc"; /* ponteiro */? &!" " " $!" " & ( # "!& & 0 * " $ #$ & # > " 3 & &" " # $ 3 ptr++ & # str++ # "!2 # # ptr="zybaz"; & " 3 ) % " " / " " 3 &" " # 3 " &0 &&#

41 <: = 9 = 9 <= > " 3 * & #define N 10 ) & const int n=10; 3$ & n & &" " " # &" " ' " " &" "/ * &" & # const int *ppci=&n; /* ppci: ponteiro para constante inteira */ > " &" " " &" " 0 & " & " # > " " &" " " % # int i=3; ppci=& > + i " % &" "$ " % 0 3 ppci # <: = 9 = 9 <= & * * &" "$ " &" " " % # & " &" " "! ( int i =4; int * const pcpi =&i; pcpi = &i; /* ERRO */

42 % 3 ) " &" " # "" $ 3 ) " " &" " # <: = 9 = 9 <= 9 = 9 <= $ " " &"" &" "$ " % 3 ) " " " " ' " # & % " 3! & ( const int ci=1; const int * const pcpci=&ci; 0 " " <: = 9 ; <= > " ' " & &'! " % 3 " 0 # 3! " "! " # & " $ "! " 3 ) $! " "! " # & % "! " % * &!* " "! " % # $ &"! " min max!" & ( int min(int a, int b) { return (a<b? a : b);

43 } int max(int a, int b) { return (a > b? a : b) ; }, "! " $ # #$ "! " " * " 3 & - " & 2 2. & ( int int int (*pf)(int, int)=0 / * int *pf(int, int) 3 & %! " % * " " int. & " && " pf "! " % & ) " " & pf # + &!2 " ( pf = max; /* equivalente a pf=&max; */ pf = min; " &% &! " % 3 " 3! "! ( f() { }; int a, b; a=min(10,20); /* Chamada directa à função */ b=pf(10,20); /* Chamada à função através do seu ponteiro, */ /* e a abreviação de (*pf) (10,20); */ " % "! " % " ) & " 3 ( 0& "! " + & $ * " & " # &%

44 & & " * $ $ " " * & $ $ &"! " % & # " &!" * " 3! " % * & # > * " 0 $ )" $ $ " % " " * & & # + 2 & &' & "! " % " )" $ & & 0 $ & & " & & $ & " &! " % * & & " " - ".! " % & " # + " 3 " & 0 )" # include <stdio.h> int min(int, int); int max(int, int); int calcula(int (*) (int, int), int*, const int); int main() { int a[]={1, 2, 3}; const int n = sizeof(a) / sizeof(int); int maximo, minimo; maximo = calcula(max, a, n); minimo = calcula(min, a, n); printf("min: %d - max: %d \n", minimo, maximo); return 0; }; int calcula(int (*pf) (int, int), int *a, const int n) { int i, res=a[0]; for (i=1; i<n; i++) res = pf(res, a[i]); return res; };

45 ? 3 2% " &' $ "!& " " % &' # 1 -.!0& " &! " % " &! " % *! " % )" $ calcula 0 $ & # <: = <= =? & 3 " 2 $ & " # -> typedef struct { float x, y; } point; point p, *pp; p.x=0.0; pp=&p; pp->y=0.0; " %! * ( (*pp).y=0.0; = < 9 <: =! * " 3 & ( int ai[5]; 3 * " " 3 & & ( int*api[5]; + "% & 0 & %! + "

46 * " " / " % api ' " # 2% " $! " % * " &" " false n! " &" " true & &"0 # const char* bool (int n) { }; static const char * names[]={"false", "true"}; return (n? names[1]: names[0]); > " " ) # "" $ "% &!& "!&0 & "# " % (! " % &! * " " & " )" & " " # "$ " " " 2 # & 0 # $ static names static 0 & " " )& & - & % "" &. " "! & # $ 0 & static! " % " & * "! " % 3 & 2 " "! & % $ " &" " &! " % # "" $ 0 &")" & $ $ " % 0 &)!! " % " 3!" # <9 = 9 :9 * " " * & & "!" " " #, & * 3 " (

47 & * & &!& & "!" " " * *!& $ & ( > fact & " 3 &" &" "! " % main # "! " % main 3 & $ 3 & & " ( * &"3 " " & * 3 & -* 3 " '.# $ " & argc # # argc * 3 " $ " " " &0 " " &" &" " " & *! & # & $ " argv[0] "fact" argv[1] " "3" - $ " / " % ".# # argv $ * & * & " &% -" stdout &. ' " " & *! & $ & ( int main(int argc, char *argv[]) { int i; printf( O meu nome e os argumentos com que foi chamado são: \n ); for(int i=0; i < argc; i++) printf(" %s \n",argv[i]); return 0; }; *!" " &"!2 " " * " #

48 < : = # & " & " " $ &"! " % *!* (. + " & #. * " & " 3 " " '" $ $ " &&" " &&" # # + & " % * 2 % & printf " * # 0 2!* &" " # 2.1. int *pi=0, i=1; 2.2. int a[]={1, 2, 3}; int pi=&i; int *pi = a; *pi += i; pi++; ++i; *pi; i #, 2 $!" " $ &"! " % * " & " & && " 3& #? $ &' " 0 & ( # + & &'!&" # # "! " % & " * % "$ "! " % " # +! " % " & " & && * " % "! " % & " "! " % #

49 *! " % & " " " " #? $ &' " 0 ( #, 2 $!" " $ "!" * &" " && " " #? $! " "! " $ &' " 0 ) #

50 3. Reserva dinâmica de memória 0 * " " " & #? 3 $ 0 3!" * " % #? $ 0 - $ 0 &! * *! " % * & * *! " %. * % & 3! #!" * 3 * " % 0 / 0 & -# #$ * %!" " " )& & ". " * " & & % / 0 0& % & " *! " %!" 3! #? & 0 * " & " " * " # % " " 0 * &" 0 * " 3 " 0 $ " # &% 0 " 3! " - &%. " & ' # " & ' 3! & 0 & % & &" ' #? 2 0 % & 0 " &# > &' "!2 " & ' " & " # int *pi; pi = (int *) malloc(sizeof(int)); /* (int *) é uma coerção ou conversão explícita */

51 $ " " ( pi = (int *) malloc(sizeof * pi); * sizeof * " " &0 ' " " &' " " " " % # > " 2 " &! " " & '$ stdlib & ' " # > '! " % 3 & " " $ " * " 3 &" ) " " # void *malloc( size_t n); void *calloc( size_t, size_t);! " % " " & ' " % " & 2 malloc " % n $ NULL! # " & $ " * &" $ 0 * pi # " " ) & ( malloc void* int *pi; pi = (int *) calloc(1, sizeof * pi);! " % & " & 2 ' * # & calloc 3 " 0! # malloc NULL ' " ) $ * $ 3!" #? $ ' %! # ' & " '!& &" $!& $ ' " $ & ( if( pi == 0) { fprintf(stderr, Memória insuficiente );

52 } exit(1); " " & " & '$ *!2 " & "0 &' & ( % " ) $ &!& & 3 stdio.h $ " &!& ( # $ % stdout $ " ) % * $ % $ 3 &% # # $ % stdin $ " " % * $ % $ 3 & # # $ % stderr $ 3 &% / $ " % &&" # ) * & printf("abc"); * " fprintf(stdout,"abc"); int i; scanf("%d", &i); * " fscanf(stdin,"%d", &i); " " " $ & & " % printf "! " )! &&"!& $ #, " 0 " % &"& 2 fprintf(stderr, <mensagem>) * $ * ) &&" $ stderr &"" 0 &% #

53 * " &0 ' " & " 0 #! " % free '! " malloc calloc # +! " % " ' ( void free(void *); $ & ' * & " " pi $ & " free(pi); " ' " & " * & $ " " ( # " 0 * " &!& * $ # #$ * " & # # " & " & " / # 1 & /! " % 0 & " %! & free malloc calloc # 1 " 0 * 0! # <=< :9 : < < : = " & ' 3 & " - " &$ 2 ".# + $ " " % &" " / + $ " % & % * " " &0 # * " "$ * " 3 &!&!& " " & % #? $ " % * & & " & " " * " " )" " 0 " & "

54 & " # "! " " & "!& "! * " ' # " & " " &0! * 3!" * $ & " " " #? $ " % * 2 " & " & " " " &0 & " #! &"! " % callocf. > " ( double distn(float*, float*, int); void ler(float*, int); float *callocf(unsigned); " int main() { int n; float *A=0, *B=0; printf("nº coordenadas: "); scanf("%d", &n); /* verificar n aqui */ A = callocf(n); B = callocf(n); printf("ponto A\n"); ler(a, n); printf("ponto B\n"); ler(b, n); printf("d: %f", distn(a, B, n)); free(a); free(b); return 0; }

55 float *callocf(unsigned n) { }; float *data; data = ( float *) calloc(n,sizeof(float)); if (!data) { } " * " fprintf(stderr, Memória insuficiente ); exit(1); return data; double distn(float*, float*, int); void ler(float*, int); " %! #, 2 * " & % & " & " $ " %! " &0 " "! " * " # + & " & $ & * " & # A[i] *(A+i) <=< :9 : < < : : <=? " " & & 2 " "! " % * " & " 2 " $ & & " " $ &"" " 2 & 2 " $ & " " 2 & " & " $ & " (? & " $ # "$ % *!2 3 (

56 int *ptrelem = (int *) calloc(l*c, sizeof(int)); + " 2% ' ) ( "! " % 0 & calloc2d " ( 0 " % & m = calloc2d(l, c);? 3 $ * & & " ( m[i][j] = 3; 3 $ "% 3 " " $ " ptrelem[i] *(ptrelem + i) m[i][j] *(*(m+i) + j). &! " %!" & " &" " calloc2d " " & " 2 # * & &"! $ *! 0 &!&(

57 > &' * " 3 " ( pplinha = (int **) calloc(l, sizeof(int*)); for (i=0; i < l; i++) pplinha[i] = &ptrelem[i*c]; "% &! " % * 2 l & " $ " 3 &$ 3 " ( c " int **calloc2d( unsigned r, unsigned c) { int i; int *pe, **pr; pe = (int *) calloc(r*c, sizeof(int)); if (pe == NULL) { fprintf(stderr, "Erro na alocação de memória. \n"); exit(1); }; pr =(int **) calloc(r, sizeof (int *)); if (!pr) { fprintf(stderr, "Erro na alocação de memória. \n"); free(pe); exit(1); };

58 for(i=0; i<r; i++) pr[i]=&pe[i*c]; return pr; }; + 2% ( int main() { int i,j; int **matriz; matriz=calloc2d(2,3); for(i=0; i<2; i++) for(j=0; j<3; j++) printf( %d \n, matriz[i][j]); /*... */ free2d(matriz); return 0; }; " *! " % * '! " % 3 " ( void free2d(int **pp) { free(pp[0]); /* liberta toda a memória reservada para guardar os elementos da matriz */ free(pp); /* liberta a memória reservada para os endereços das linhas da matriz. */ }; < : = #!* * & " " & ' & 2$!" " "! " (

59 # > " # "!* & # int main() { int *pi; printf( No. inteiro: ); scanf( %d, pi); printf( %d \n, *pi); return 0; } # " " ( #include <stdio.h> #include <stdlib.h> int main() { int i, n, m; int *a, *p, *e; printf("n: "); scanf("%d", &n); printf("m: "); scanf("%d", &m); a = (int *) malloc (n * sizeof (int)); p = a; e = a+n-1; while (p<=e) *(p++) = p-a+1; do{

60 # } for (i=0; i < m; i++) { } do { p++; if (p>e) p = a; } while (!*p); printf("%d ", *p); *p = 0; n--; } while (n>0); free(a); return 0; # ) $ $ #? & " # # + * *!2 & " # & # & " # " % $ * "" "" % + & &" " " "! " % * & & " " 2 # % ( & & " " &% " " " & $ ' &" " % # # " " &' ( int ***new3i(unsigned, unsigned, unsigned); void free3i(int***); int main() { int i, j, k, ***tensor; unsigned pag = 2, lin=3, col=4;

61 tensor = new3i(pag, lin, col); } for(i=0; i<pag; i++) for(j=0; j<lin; j++) for(k=0; k <col; k++) tensor[i][j][k] = i+j+k; /* mais processamento sobre o tensor */ free3i(tensor); return 0; + &! " & ' " & & $ &! % $ & "$ ' " * & " &! " % main # # " " % " $ " 2 " # 2 " % ( " & & " # " * & & " 2 & * " 2 # " 2 " & 2 " # ) " 2# > 0 & - ' 2. 0 & & " " $ & #? $ & $> sam 4 3 2!0 & * & " 2 " & " $ & / 2 & * " 2 #

62 4. Primeiras Noções de Complexidade & % &" & " &( & ' # % * 2! 0 " " 0 & # & &! * " ' * * # "! " &! " & # + & * " " # 3 " $ %!&" * $ & $ " " " & & "!&" % # & ) $ " & 0 " &" * & ( # & " &0 # & " " * 2!? " * " # )& " " )& # & " &0 " &# * &!& " & * 2! -!&. &!&

63 " " * 3 * ' #? 2$ $ # + " 0 3 * " # "" $! "$ " & " % &!& # " & # > & & % " &" "!& * " & &"! % & $ " % #? 3 $ )& " 2!!" " % % & 0 # 3 " % " " * " % " &!& $ *! " &0 " &" " % # " * 2 3!& $ & " 0 &!"$ " % & # > & " 0 0& " " &)& -. "" #, " " 0 & &" " "!&% & " 2 " & & % & # * * " & & * & &% 3 & " & " * & & # > & " &" 3 " % * " & & -. " " # " &&2 # + " " " &" " $ " " $ " ' " " 2 " # " % &&2 - $ " & " " " & - $ " " " 2.# > " & 3 " " " & & #

64 $ * &" " &&2 " $ " 3 ' & " * & # $ &" "! " % * " &" 0 " # int getmax(int *a, int N) { int i, mx = a[0]; for (i=1; i<n; i++) if (a[i] > mx) mx = a[i]; return mx; + = } = ( & " " 0 " " "! "! " % & # > & " & " % $ % mx=a[i]! " % & #!&$ " " % " ' " # & " " & ( # & # $ & & * " 0 " &&" " & " 0 " # & $ * = = = =

65 " % &" " * " & # # + 3 # $ & " % ' " " # #? & # $ & & * " 0 " &&" # & $ = = = = + " $ 2 $ % &" " * " & # & " " " " " 0 & $ # #$ " & * 3 & % " " # "" & * & " & % * * " # " $ "" & " & " ( " " % &" 0 * " &" " 0 & # 545 < : < ==: :? 3 " 0 & $ " " * & $ # #$ " &" & && " " " # % "$ " & & " 3 " & # * &!&" & -. * "!& * " & && * ' " & " $ * " 3!&" " # " 0 & # > & '& & " &%!& " 0 #

66 ? * 2 * & -. '& 3 " $ " " ( 3 > " * * & " % > " # + " 0! * 3!&" * $ *!2 & $ & '& " * # + $ " 0 " % 3 0 * " # 3 " & # > & &!! "$ &" 2" ' & &% " 2 # 57 5 < : = # 3 && " " % > " # # " & '& 3 * * " & $ * & 3 " &" " -" " " &. 3 &! -" ".#

67 . "! " % " &" 0 2 " & " /. " & &! " % * " # #? & & " ' $ " ". " & " % (? -.., " (? -. -### -... " " & & # #.? "! " % " && " " #. " & " " & # & & " " 56 5 ==<= < < : < < " %> 3 " "! 0& # + " %! 0& & " " " 3& " &" " #? &!& "!& " %> & "! 2% #! " % " > " &" "! " = > > > 1 & * " % > "! " % &" " # 2 * 3 > -.$ $ &

68 " > $ 3 2 * 3 &" " > $ * 3 & $ & & > #! " & # + * $ $ # 1 " " * > 3 $ " % " & " " # 3 > "% 3 3 > $ & & & '& ) & " & &" "$ # #$ & % " % " " " $ " > > ) &$ > / " $ >? " > * 0&$ > & &$ > " " & $ > $!& $ > & % " &&" & $ # #$ &!& " & #? & & "

69 $ && " " $ && " " # & " % " & ) && " " " &!&#! " && " & "! " % " " $ # 2% & ) &#! * && -. * # Crescimento Cúbico, N 3 Quadrático, N Pseudo-logarítmico, N Log(N) Linear, N Logarítmico, Log(N) N? & % $ "! " " " " && " & & $ " && " " " &!& #

70 Crescimento Factorial, N! Exponencial, 2 N Cúbico, N N + && " " 3 # " &" " 3& 2"!!!" # " " * " & # > 3! % $ $ $ * " % 3 " " 0 & & # " " & % & # & " "! " % " " # & " " " & &! " $ # #$ -. - )! ". " # > & & 0 3 & 2! " $! #? & % $ & *

71 "$ & 0 $ 0 & 2 "! - " ".#! -!.! -.!?! -!. # # 2 3& # # " * " &) 3 " " " &!& $ "! # * & && " $ " & " " & -. "!?! -!. 3" " & 3& 3" $ $ " " &? 2 * & % " " &!& "% $ $ " " & " # & "% & * " " & ' % 0 & 2 " # 2 * 3!&" & '&!$ * " $ " $ & 1 & % " * * & " * "

72 &" & & " 3 " % " # + 2 # 1 " " * " % % "0 # > " & " &" & " & " * * & " "! % " ) " $ " 2 0 " &0 & & &" "! 3&$ * 0 & & " " && &'" & # 5 5 < : < < < =: : < < < =: < & 0&$ 3 & % " % & % 3 " % &" # & " " "$ & &!&"# " 0& $! " % 2 & &"!!" ' # $! " % 3 & & ' #, 2 & * " " &" % " " " & " # > & % "! " &! " & & "!" &! " 0&# 2! " % & $ 2 & &! " % # > " $ " factorial factorial n n! ( $ 3

73 = =, "%! " % 3 " ( int factorial (int n) { } int i, t=1; for (i=2; i<=n; i++) t*=i; return t;, "% $ & $ " % * factorial!" & ( 3 " ( = = int factorial (int n) { }; if (n==0) return 1; return n*factorial(n-1); "! % % & % 3 ) #! $ && * * & % * " && $ " & % # + & % " " & " &! " %!& $ & & ( factorial(3)

74 3 * factorial(2) 2* factorial(1) 1 * factorial(0) & "!* " " &! & & &!&!& " & # " factorial $ 2% & " " 0 &$!&" "% # "" $ 3 " &0 &" * $ * "! " % & $ & * 0 " &"! " & % #! " & % & " " 0 & &! " % " & % - * & " " ".#? " $ " &0 " % & #! " &&% "! " & $ % 0&( & -&&2 &" % " % " 3 & & & " " & & " factorial " if (n==0) return 1 / & & " " & 2 * " # < < 9 : = > & % $! " % & 3 & * % &"$ & " & # * % * & & % % &!& " & 3 (

75 Θ = = + Θ > & & & * "" " % #! " % " " &" "! " Θ = > > > > 2 * 3 -.$ $ 3 2 * 3 &" " #! " & # + * $ $ 0 " # &!" > * 3 "% 3 3 > # "%! " % &!& & " & * " & % # "! " %! 2 % & & "$ if / & &" " / & &"0 $! " % " 0 return " " & '! " % & " * 3 " " & " # & $ "" &" " * &% 3 & #

76 ? " " &" & %! " &!& & " & & # + & $ * " % " $ * " &" $ & " & * &&2! " % &!& 3 " (,! 2 " &" &" & " & #? & " & & ) $ = = = = = = = >? * " %> $! * 3 # " &! " % & * & " * & " " $ " " *! " % & " & " & 2 # > & %! " % 3 ( Θ = = + Θ > " " &" & (

77 = = = = = = = ? * 3 > " * " & 3 % 3& & " #? " % 0& * % 3& & " 3 ( + = = ( = + = < < <= < + &" "! " & & & % & " &!& +! " -.$ & * & " " -.# > & % "% 0 3 #

78 &" $ 2" " " $ " $ $ " " $ ( # & = Θ ε ε > = # = Θ & = Θ # & = Θ + ε ε > = Ω " ( Ω = > > > 2 * 3 -.$ $ 3 2 * 3 &" " #! " & #? $ 0 #!" > $ * ' >? $ &% # " & " & (

79 & $ #? 3 $ & & $ " $ * = = = Θ > # " & " & ( & $ #? 3 $, 2 * ε = = = # #$ "% & & ( # = = = Θ 5 5 < : = # #.. " % & 3 * * " & $ * & 3 " &" " -" " " &. 3 &! -" ".# + & '&! " % " " )" " & " & % &)& # # " & '& & " &

80 #.. Θ = = + Θ > Θ < = + Θ " & % " & " &

81 5. Algoritmos elementares de ordenação + % & & * " % " % # > " % % 2 & $ & $ " $ 3 & $! &0 & / " " #? & " % " % * " " " " " " " " &"! % " & # " * % 0 " "" * &" 3!) # & ) & " 2 " % * 0 "% " " % # + " %!&"$ 2 % & & * " % & "!0& & " # & ) " " % &!&" * * " * # 545 < :9 : < < :9 : < < < <9 " * & &% " # - ". " & &% 3 & &" " & * " &% # -&. * &&2! " % & # &% & " &% # " " $

82 &&2 " $ " $ & 0 * * & $ " " * " % " $ " # " & &% " - $ $ ###$. " & & #? 3 $ " * % & -. * * * & $ $ # % 3 " $ $ * * & $ $ 2 2 "% 2 # > " %!" & " &" % $ σ * σ σ / $ " * " % 3 ( σ $ σ $ ###$ σ, 2 * & &% & $ % " % 3 " & #? 2 " " &" % " &$ $ & " σ ( # " σ $ # 0 "% &0 " * $ " & &% " #? $ " % 3 0 " & & # σ? $ & &% " & "! % "$ " " $! & * " & &% " " " ", " $ " % 0 20 & &% * " 0 "! & " " * " " " # " % * " " & " % # 3 " &3 &&2 " % # > &3 " & (

83 # # > & " # 1 &3 " " &&2% " % # & " " & * " " & - * " &.$ " & 3 / ' " &0 # &3 ". * & " % " 3! " ' & &% * $ " $ " % " & ' $ &. * " & &' & &% "! " & - $ ". n " / & & * " ' " % &!& * * & " % " &$ $ " " % " & &%! " &! *! " & " " & $ " & " " & " # & $ " % 2 " & # # & 2% #, " % " % "" " # " % "" & &% " 3!&" " * " " ) " ' " & # " % " $ & &% 3 " & " ' " & " ) " * & ' $ & & ) # " &!" " " % 3 * " " % "" $ & &% 0 " ) * * " "$ " * " * " % " $ " % * & * " & "$ & # # #, " % 2 & " %! " ) " % & &% " $ $!& & &% 0 " "? % $ " " ) " % " & " 2 " % # # > " #, 0. & - &0&.. " & $ " " & " % " % " "

84 " ' - )&.# + " ' 3 " 2 " &" " ' # > * " & ) % 0 $ "" $ & $ " )& " % " & ' $ 3 0 $ & " && # 57 5 <9 =< < > " % &%! " &" & #? &&" & &% & " & $ & & * 0 " % & &% # $ &&" & " " & & & * 0 " " % $ & " 3 * & &% " #! " &% " & &% -". " # == < := -" )&. * & & &" " " %!" $ * " % 3 " &0 & #! " % " " " & &% N " #

85 void selection( type *a, int N) { } int i, j, n=n-1, im; for(i=0; i< n; i++) { } im=i; for(j=i+1; j<n; j++) if (less(a[j], a[im])) swap(a[i], a[im]); im=j; /* im - indice do min*/? &' $ 3 " &0!" "!& " " ( " " / type, $ * & & " % / less * & " swap,, 2 * $ & $ " " " & " " &$ " "!&" ) # $ 2! " " & & #, & & && 0 ) 3 & $ # &' & " "$ " & % #? $ * " & " " )& #include <stdio.h> " & % $ 3 & 0 " & " "!& stdio.h # & 2! "!& " & " &' * &3& & % & &! " #

86 $ &" & &' )! ) $ " " * 3!& " 0 0 " #? & &% " ) ( /* file: type.h */ typedef int type; #define printfstring "%d " #define Key(A) #define less(a,b) #define swap(a,b) (A) (Key(A) < Key(B)) { type t=a; A=B; B=t;} " * " & * $ ssort $ "! ( > ssort <Enter> "% &' & "! " % selection ( #include <stdio.h> #include <stdlib.h> #include type.h #include sort.h int main(int argc, char *argv[]) { int i, N=argc-1; if (argc ==1) { printf( Utilização: ssort <sequência de números separados por espaços> ); exit(1); } type *ai= (type *) malloc (N*sizeof *ai); if (!ai) {

87 } } fprintf(stderr, Memória insuficiente ); exit(1); for(i=0; i<n; i++) ai[i]=(type) atof(argv[i+1]); selection(ai,n); for(i=0; i<n; i++) printf(printfstring, ai[i]); free(ai); return 0;? "! " % selection &" * " & ) "# void selection( type *a, int N) { int i, j, n=n-1, im; for(i=0; i<n; i++) { im=i; for(j=i+1; j<n; j++) = if (less(a[j], a[im])) = Im=j; = swap(a[i], a[im]); } } " & "0 &0 & " # " % $ ' & & & % * 0 && # > & " " 2 * i for && " 3 & # "% " 0 & *!&0 * " & &% " &&" -" ".# & $ % & & & 3!& " 2 * " & % & & $ $ " & $ # &" $ & % (

88 = = = = " * + = = = * " & 3 ( = + = = = * ( + = = + + = " $ % &" " * " & # 3 * & * ". & &% 0 " $. & &% & &. & &% & " % ) "$ & & #?!& &#? $ " " && "" % & $ $ - & & &!" & swap 3 " 2 *!2 " %!2 3 & " " * " *.!& * && & # " & * " % 3 # + + < 56 5 <9 + " " % &% " " " % &$ " & 2 *!2 & %!& " &$ " &0 #, " &" & " " * 3 # + & " bubble sort & &% &" " &" * " &"! #, "% " 3 " ( void bubble( type *a, int N) { int i, j;

89 for(i=1; i< N; i++) for(j=n-1; j>=i; j--) if (less(a[j], a[j-1])) swap(a[j],a[j -1]); }? * " "$ &' 2 " ( = < - " 3. $ & & - 0.$ & & - 0 " % & &.# + $ & " & " "! bubble sort &% # " % 0 ) &"" " % & " " &"!&" * &% 3 # & * "!2 3 " " " * & * " % & &# % " & 3 * 0 " # " % " % 0 & & #? " 0 &" % " " && for #

90 3 * * " & &% 0 " " % 3 -. " $ 3 3 * 3 % & * % " #? * > & " %!&" " " % & 0 " &% " # 5 5 <9 :9 =< > && "! " % " * # && bubble " " " &"0 & " "$ * & &% " " # & $ " % ' " " % # &" & & " % " % # " % " % 3 3 " % * " ' 2 * " &# " & & 3 "! " $ " " & & &3 & " % " % && & # "% & $ " " " " * " " &"! % ( " " 3$ * )" & & " % i " % " $ " % " %!" $ 0 * % * & " -& &. " " &" " #? &" $ & & &% * &" & & " * % * $ " &0 # i " "

91 ? & &% " " & $ " % & ( = < - " 3., % "$ &!&"$ 3 " ( void insertion( type *a, int N) { } int i, j; for(i=1; i< N; i++) for(j=i; j>0; j--) if (less(a[j], a[j-1])) swap(a[j], a[j-1]); + % 0 &" " ( # #? " && " * " " &" & * " * & & $ * & &% * & & 0 " # + " %!2 % % " % # * & & " * & &" $ & " ' "! & " & % # + % " (

92 void ainsertion( type *a, int N) { } int i, j; type t; for(i=1; i< N; i++) { } t=a[i]; for(j=i; j>0 && less(t, a[j -1]); j--) a[j]=t; a[j]=a[j -1]; " % * 3 " $ 3 * " " " & 3 # + "$ & " &)&!& * $ & & '$! " % 3 && 2 0 *! " % && $ ainsertion bubble 0 *! " % selection # " " % " % $ & " " $ * " " "!& " % ainsertion * " # # 5 5 < : = & &% && + + > $ " & &"! * & &% * " 2 " % (. &%. & -. &. " % # + & '&$ " & $! " " %

93 a) insertion. ainsertion &. bubblesort #? " " &! " selection ainsertion # 3. + & * " " " " &" "! " " % # > 0 & " & & " & " % # % ( "! " # $ & " "! " " ' selection, insertion, bubble ainsertion!" # # " * 3 $ & " " a N " $ & )" & " # i "! " % " % $ "! " % ainsertion * ( )" & " " i[0] )" & " " " $ a i[1] ### $ )" & " a i[n-1] # a # + 2 " " " " " " &" 0!& #? 3 " $ " 3 &&2 " $ $ " " $ " &" "$ " " % # " "! " % " &! " % $ & &% " & ainsertion ' " # i. ii. iii. " #

94 6. Mergesort " & " " &!)& " & & & " " #? " " & " " " # > " " 3! # $ * " " " " &" " & " & $ " " # + " 3 &" & & $ " & 3 " 2 " " * " # % "% & "! % " # > 0 &" * &!& 0! " & # 1 & 0& # >! " & " " " " " # 545 <= : : > 3 & ( # & &% " & " & & - ". " / # > " & & &% & " ' / # " "! % " # # & &%

95 0 " & " % ( + &!& "! ( #include "type.h" void mergesort(type *a, int n) { } int m=n/2; if (n < 2) return; mergesort(a, m); mergesort(a+m, n-m); merge(a, n, m); > & "% 3 &" & " #? & # &" " &$ & 0 " & & & $ & & * " & #? " & " " & " ) " & &" "

96 & & # 3 * " " &" " " " &#! " & * &" " $ " #? " & "% $ " & " ' -& &%. & " &" & " & &% " $ # " "%! & &% 2 * " % " % 3! " $ " % & " ' & &% " $ & &"& & * 3 * # " & &% & 2 "! "!&" & " ( void merge(type *a, int n, int m) { } int i; int l2r=0; /*left to right index */ int r2l=n-1; /*right to left index */ static type aux[maxn]; for(i=0; i<m; i++) aux[i] = a[i]; for(i=m; i<n; i++) aux[i] = a[n-1+m-i]; for(i=0; i<n; i++) a[i] = less(aux[r2l], aux[l2r])? aux[r2l--] : aux[l2r++] ;! " % " &. * " " a " * * - n % " " " $ & " m=n/2 a # -)" &. " > && & " # > " && & $ " $ " a " #? & $ && " &"! % ( a

97 -)" &. " > % &" " & 0 & # * *!2 3 & & " " " & 20 & " " " #, * " &$ & & $ * && - &&. aux " " " 3 && -&&. " " "$ 2 * " & '" & # aux 57 5 <=< <9 > & % 3 " " " % " $ mergesort!" % 3 " & " & ( Θ < = + Θ " &" 2 & & " & & " 0 &" * & "% $ # #$! " % merge, " & &"? $ &% # # $ &" & * & '& 3 mergesort & & " % * $ 3 * &" 3 " #? $! " % " & & " % merge & &% " $ * 3 " #

98 " "! " % * " % " & & &% # merge " &" & -. & " #? $ "! " % %! " % ainsertion *!2 " % " # merge, o 0 * " " %!" &! " % "% & & " " " $ 3 & && " & " ainsertion & &% $ # #$ & &% " 2 & " " &) $ &!2 " # " & " &)& ainsertion $!& "!& * " % " " & 3& % $ & " * 0 " &" & ainsertion # "! " % * " " & & " " $ " ) $ & " %!!0& # # 5 5 < : = & &% && + + > " & & & * " 2 # #, &" * "! " % * " &" " ) # + & '&! " % " # # + # # + & '&! " % * 2 mergesort " &! " % "% " (

99 /* Função de junção no lugar baseada em ainsertion. Args: a colecção a ordenar, constituída por 2 subcolecções garantidamente ordenadas. A subcolecção direita começa em m. n número de elementos em a m = n/2 */ void poor_merge_in_place(type* a, int n, int m) { int i, j; type t; for(i=m; i<n; i++) { t=a[i]; for(j=i; j>0 && less(t, a[j-1]); j--) a[j]=a[j-1]; a[j]=t; } } # " " "! " " % "! " % & # ainsertion mergesort merge_in_place, & & " # "!" n #

100 7. Quicksort >! # # # "% 3 quicksort " % # > 3 & 3 quicksort " % 0 &" " ) $ &! " % $ " " % & # quicksort!&!0& "$ " " " " " #, " 0 & 3 * & 3 " & &% quicksort,, " " > - # "" $ " 0& * & &"!&" * #, " & "" * & 3 * " % 3 0 # 545 : =: + " $ quicksort " & ( # + & " * & # # " " " ( # > " & & % " * & / # > " & & % & /

101 #, & " " & # " & " " $ 0 " & " " * & 2 $ " $ 3 & & " %!" # *! $ " " " * " "!" # % * $ 3 ""# 57 5 < = : := : & & & 3 * 0 &" &2 #? % & & & " $ $ $ # " & " & $! ' $ p # -)" &. - ". -. & & " * 0 " % - " %. # "$ & $ & &" $ " p * " * # ' && " 0 " ( / " " * & & / " * #

102 ! && $ & & " # > "!& ( "% * * $ p $ " % " " * p # " % * * & " $ " )" & $ "% (? " &" & * p " #!& & & " %!" $ > & " * & & 3 & " * p # & % 0 * " & " " # " & " $ 0 " " " #, 2 * & % - %. &" $ " $ " " %!" $ "!& " &&% # > &' & " " &% 3 (

103 #include type.h void quicksort(type *a, int n) { int i; if (n < 2) return; i = partition(a, n); quicksort(a, i); quicksort(a+i+1, n-i-1); }; int partition(type *a, int n) { int i, last=0; swap(a[0], a[rand() % n]); for(i=1; i < n; i++) if (less(a[i], a[0])) swap(a[i],a[++last]); swap(a[0], a[last]); return last; } + % 3 )& - &0&.# 3 " " " " ) * " & " $ 2" & * " & " $ $ & #!" " # 56 5 < = ==: % & " & ""$ 0 " " * " -. ' #, 3 % $ " " " ' $ 3 " (

104 # + & - 3 ).# p a[n-1] a[0] #? & * 3 " &" " $ " * * # a[l2r], p #? & * 3 " &" " $ " * " * # a[r2l] p #, 2 * " %! $ % & #! $ " " " & % ' &$ " " 2% ( > & " * " )" & & 2 # " $ 3 & l2r r2l p & " * " % - %. $ $ & " " & # l2r + (

105 + & "! " " " "! ( int partition(type *a, int n) { int l2r=-1; /*left to right index */ int pp=n-1; /* pivot position */ int r2l=pp; /* right to left index */ for(;;) { } do ++l2r; while(less(a[l2r], a[pp])) ; a[l2r] == a[pp] "% && 0 * l2r " % & 0 * do if(--r2l < 0) break; while(less(a[pp], a[r2l])); if(l2r >= r2l) break; swap(a[l2r], a[r2l]);

106 } swap(a[pp], a[l2r]); return l2r; 5 5 <=< <9! " " quicksort 3 & % # + & "! * &" "!* (. a[i] 0 " %!" $ i " n-1 #. " " a[0] $ a[1] $ ###$ a[i-1] % * a[i] #. " " a[i+1] $ a[i+2] $ ###$ a[n-1] % " * a[i] #!& " & "! & & &% " # & $ " " ) & % & -&. n " " " # " n/2 " ) & " 2*n/2 " n/2 " " & # + & && n/4 " ) & % # $ & " 3 &" n + + = +!& $ & " ) & % & &% "! &" & & " $ " & % n & " & ( Θ < = + Θ

107 " n! & & " & & n & " " % #? &% # # $ n n n > & 3 &&2 " " & n-1 1 " ) & % #! " % quicksort & ' n 2$ $ & % 0 n " ) # + & " ) " &" " & " # % $ & " & * " & % 3 ( Θ < = + Θ * $ * * " & $ " " " &% # # $ n 3 n #? * " 3 * & 3 " & #? " " $ " ) " & &% # &" $ n " # % " %! - $ $ n.$ % 20 & & & " n $ & " # $ * & % 3 & " & ( Θ < = + Θ = " 3 * #? " & " " " " * 3 0! 0! 0 -" " * " ". & ' & * " %! 0 #? 3 $ " % ' " $ & " & n & " " " & " & n # & " 0 % & * $ & " 1/n!.

108 $ " " & " " % " # < <9 = < ; <= < <9 =, " ) * & % * " & & ' 2 " " & * " # ) *!&"$ & 0 3 %!&" * " ) & " " & * " #,! 3 " * & 3 " % &" & "!&" " & & * " #, "! " % quicksort ( " if ( n< 2 ) return; if ( n < C) ainsertion(a,n); " * & & " % 3 &)&$ " # C " $ * %!* " " & )& # >! & & & * " 3 " * & &$ & ( void quicksort(type *a, int n) { if (n < C) return; /* */

109 }; & $ & &% " & $ & quicksort $!& " # + 3 *!&" & $ & ainsertion # + &% &" &2 " "! " % ( void hsort(type *a, int n) { quicksort(a,n); ainsertion(a,n); }; # # # < <9 : < < : 9 < 6 = = " & " & " 0& & # > "" & $ "!& " " " - *. " ' $ 3 " & &% " #! " $ " # + " " & &% $ "% 3 p=mediana{a[0], a[n/2],a[n-1]} ( # 3$ mediana{1, 8, 4}=4; mediana{1, 1, 8}=1 " " & #!& &)& $ * " & " " & " " & " # = # + <stdlib> % 0 " " "! " % # " " " % quicksort qsort

110 ! " % " & * 2!"! " % & % " qsort " # " * * $ "! " % & % % * void* # * " * "! " % qsort & ) " ( #include <stdlib.h> #include <stdio.h> int intcmp( const void *p1, const void *p2) { int i = * (int *)p1; int j = * (int *)p2; if (i <j) return 1 ; else if (i==j) return 0; else return 1; } int main() { int i; int a[] = {0, 1, 8, 5, 4}; qsort(a, sizeof(a)/sizeof(int), sizeof(int), intcmp); for(i=0; i <n; i++) printf( %d, a[i]); return 0; }; 5 5 <9 : = :9 := " " " % $! & & * * #

111 " % * 3 & #? * * * * & 0 $ " $ " " $ " & #? " $ " & $ * & % & " ' # ' " " " % & 3 * &" " '& # # # # # 5 5 < : = " " ( - ". - %. " & * * " & % & 0& * &? " % & 0& * & & & " ( # # &&" / # # &&" # " " ) & % " % )& * & $ & &% 0 "!* # > " & " 3 % )& * & % " % " % $! " % " " " & &% #, & & " # " #

112 # # # # " " " % & % & 0& * & $! " % " " " & &% #, & & " # > * &" & " " " " % & 0& * & & " % &$ $ & & * " $! " % # " " " " % & 0& * & & 2% " # " " " " % & 0& * & & 2% &" " & & & * " " # # " * 3 $ & " " a N " $ & " " # p "! " % " % $ "! " % quicksort * ( " " " p[0] " " " " $ a p[1] ### $ " " a p[n-1] # a # " " " * & $! " % " " " & &% #, & & " #

113 8. Introdução às listas ligadas > % & " & &% * " * " % & % # " " " "!& " " -. "!&"$ # #$ & #? " $ $ " " "! &0 & # & " % " " 20 # > * 3 *! 0 - " ". & " "! "!&" &0 $ & 0 " " " " " " 0 " % & % #? & $ & " "" # &"0 * &"& " $ & " " % &!" # " -" " " ". " # " % % "! &" " # " "$ & " "$ " " " &0 # *! " &0 2" " " ' " & " "!2 " % " # * " " &0 ' # $ % & # 3 0 # & )! $ " # + & ) " * " / - " %. && / - " %. "" $ " " " 0 *

114 &!& % " " # 3$ 3 " $ && & "" $ "!" # 545 := = =: <= <9 < : =, " $ & $ 3 & &% " ' * & " ' &"3 -. % " ' # 1 " " "! ( + "% $ 2 3 &" "% #? $ 2 3 * " ' " $ &" && # # # < :9 : " " & " ( 2$ $ " ' / & " $ $ " " ' / & $ $ " ' / & $ * 3 " " " ' #! " " ( & /

115 & $ & " /!& 0 2 / " " " ' / " ' / / & / & & / &" &" #! " " * & " " % " " ' " " $! " " * & " % " ' 56 5 : <: = : < <9 ; <=? " "! " $ & "$ &!" * &&2 & " ' #, % ( struct node {

116 }; int item; struct node *next; + & % &"3 * * &!" & # *!" $ & " next $ " &!" ' # > node node & " * " " % * " & # "" $ " % 3 ) & $ * s ' s #? $ " % 3 ) ( struct s { }; int i; + > struct s ss; + > % node " ( # &"? * 2 &' * & "!" - ".# 0!& typedef int type / type " & % struct node # #, 2 * " &!* " " $ &" &2 struct node * *!&0 &' * & "0!" $ " $ # & & $ $ & list_pointer node_pointer link $ " % ( typedef int type;

117 typedef struct node* link; struct node {type item; link next; };,! " % * &" ' $ " " 3 # "% * 0& * * & 3 " ( &' 3 ( #include <stdio.h> #include <sdtlib.h> typedef int type; typedef struct node* link; struct node { type item; link next;} ; void f() { link first, second, ptr; first= (link) malloc(sizeof *first); if (! first) { fprintf(stderr, "Memória insuficiente"); exit(1); }; second= (link) malloc(sizeof *second); if (! second) { fprintf(stderr, "Memória insuficiente"); exit(1); };

118 }; first->item=3; first->next=second; second->item=1; second->next=null; printf("neste momento a lista contém:"); for( ptr=first; ptr; ptr=ptr->next) printf("%d \n", ptr->item); free(second); free(first); /* equivalente a free(first->next); free(first); */ +! " % -. 3 & " 0 &" ) $ & " # 5 5 < : = #! " % &! " " " ' $ # #$ f! * second " first NULL # #! " % &! &" & " ' / f # " " % % " ' & " &% #

119 9. Primeiras noções de Projecto e de Projecto por Contrato & & " % & * ) "!& "! " % & ) " * &" ' " # + " % f(), " 0 * &" & &' * & $ " & " ( # # " &' * $ " * # 545 < <, " & " " & + " " 3 %!0& & " # & 0 " " 3& " 0 # ' " $ & &" % & # & 0 " " 3& )" # "! & & $! & 3 &! " % * 0 "! " "!0& "# +! & 3! & & # > & $ " 2% "! " " " " ) $ " 2

120 * & "$ & # 0& % - * * " " " % &. 3$ $!&! &! & # 3$ & " $ " & $ "! 0& " " 2% * " &' 0 # > "!)& & % " & & * & "! " %! " $ " " "$ & "!&!" $ &! "" &! " # "" &" " ) & ( % & "% " " % -# #$ && "./? "% 0! " / 2 & " & % / "! - * ". / " 2! 0 / & & / 1 &% 2% / & 2% "" & % $ &"! " ( 3 " " & / &&2% & " &! " % * " 0 / % &" " 2 / & %! " " % 3 " &! & % ) #, " "!&% & & &" " #

121 + $ & "! " * " $ " * " % % & " &) & # > " " 0& * " & & " % &" & $ " % $!2 + " "! &" & " " 0 % # + $! & % $ * ' 0! " % & # & & $ & % ' $ 2% $! "" " " "$ " * " & 2 "" #? & & * 2% 2 & 3 # &%!& $ )& 3 & # 57 5 : < <=? " "! & &!* " " & #, $ * "!& &" " '! " # > & " " & #? $ " " " % # & " '! &" " ) #? $ 2 * * % ) * " ) & 2 " " $ " % '! " " % & & " & " *! " % & " &' #

122 <9 <= : < =! " % & 3 " & " & " " #?! " " " & $ & & $ & " & #! " % & " & $ # #$ 3!" % " (! " % 3!" & 3!" & "! " 3 " " #! "$! " % &! " % # >! "! " $ #$ "! " 3 " & " & #!! " 2$ & "! % &" $ # #$ " $ " & # > " " "! #

123 "$! " % &! " % # + $ & " ( A() { } /* */ y = B(x); /* */, " & " " & "( > " " & &" &"! " " &% * & " )

124 ! " % &! " % " & 2 # 56 5 < := 9 : = < IR * & & " & " " R * & " & ) " &% # " " # main A n n A A, B, n d d callocf ler distn printf A free d calloc sqrt " -. * " " & " " &%! " 2 # " " ) # " * &! " $ " " % ' & # $ & B & "! " % " & #? * &" & * " & "% #

125 5 5 9 = <= < : < >!&!& "!& "" " " $ " % $ 0 2 #!& " % " & )!& & &&% $ 2!& 2% $ " # &&% & &!&! * &!& #!& $ &&% 3$ " $ " # &&% $!& % & " & # % 3 " " * &" & % $ " & " " ) " " & " " % - 0&.!& # 2 3 & &! " &" &" " & &" # && & 2$ &"!0 #!& 2% 0 &" &!& & * " & $ " " " " " " #!& * " "!* " " & ( +!& " & (, 2% & & " ) ( & & * & " & /? ( & & * "!! /

126 + " - & &.( & & * &!&% /!& * "" $ $!& * % 0 " $ & ( & " & % # <9! " & " & " $ $ &" $ 2 & # > & " & " & " &% " &0 "! " * * & " &#! " & - & " * % &) * * '. 2 * & " & # > & " & 2 " & " # " & " % ( > & / + " &) $ % &0 %! " / + "! " % *! &! " * 3 # " & & " & '!& " % 2 #, & "!$ * $ 3 & " # + & " & * " "! " % " % " " &0 *! " % " $ * % " #? (

127 "!" &! $ " & $ 3 "!" $ & " $ $ & # " *! " % 3 % * " "!" # $ "!" 3 " &0!&" "!" /? $ 0 $ " " & "! " % # > & " $ " $ "! " & "! % - " " &. "! " * & " & " # + " & " ( $ $ &" &" # +! " &&" " " & $ " $ &&" # " &! " # 3$! " * & " & & " " "! % ) # <= & % " 2 " " & " " "! " % ( "! " & " 2 " &!!" # & % 0 " & %! " &" # > & % $ " &&" $ % (! " &" $ * " & $ & " &&" $ & " $ $ ' & & " & " # & % & " & " & " $ " $ " )!& & % &&2!& " % " &" "! " %

128 & # " *! " % & & % & " & " " % & & " - ". " 2 #? " " *! "! " & # "!! & % " 0 & " # 5 5 < = : = < < )& & & 0& * & " " " $ $ # " & )& & $ * & * $ " & ( & / " " " &? 3 )& 2 " " " " " " # 9 : : : :9 : " & 2 ' ) ' * "! " " &0!" 2 & ) * 0 " &0 # 9 :9 9!""! " % " & "! " % # & "$! " "!"" #!"! " % "! " & & "! " % # & "$ " $!" 3 # <= : : : < < : : : <! " % "%! " % * "! $ " & " * "! " % $ " &0 #

129 5 5 < 9 " 3 & 3&" & " & &" # 3&" &? & " -.! " & " " $ " " )& " $ &!# $ # + 3&" & " " % % #, % 3! % * " " & 0! # & "$ " % "!& "! # " & % & ' &! 3 &" # $ " % 0 * % # 3&" &? & " $ * 2 " 3 ' &" #, 3&" % 3 & % & * " & % # " &$ " $ &" * %!& * "! " % 3 & #? $ &"! " % " $ # 3&" % * 0 " & "! y = log(x) 3 # 3&" % " )& * 0 x>0 " 0!2 ( & "! " % # & % )& log " & " ( " & -* & " *! " % * " 3.$ & -* & " *!&.# % # 2 ' # " * & " &' )!& "#, ' &" % 3 & % &!& ' & % # " &$ " $ &" *! " % "!2 ' " # & ' &" % " e y ==x, e

130 3 &" " &" " " # * " 3 " ' &" % & & #!" % 3 ' &"! " % &!" % "! " % & " -! " * 2.# > &" " ( "Eu, função fulana de tal, comprometo-me a fornecer um estado final em que a pós-condição está satisfeita, se e só se for chamada com a pré-condição satisfeita" &" & " " %!!$ "%! " %!& 0 & " * * ( " & % # 1 & " & & " " &' * 2 #? 3 & "! *! " % & * "!& & " $ 3! " " &!& 3 ' &" #? 3 $ 2$ 3 " & & "0 " &' * " & &" #? ( x = a*a + 1; /* x > 0 já que é a soma de 1 com uma quantidade positiva ou nula */ y = log(x);, " & &" 3 "!&!&% &'! " $ &" * " &$ #, 2 *! " % * 3&" % 0!$ " % 0 " & " &! " % # * & 3 &! " " " " " * $ $ & 3 " #

131 > "" (? & && -& *! " % 0 " && " " % &!& " *! " % 0 *!2./ & & "% / % # * &" & 3 & "! " -!" & & ".$ $! " & " &%!! # " * " % 0 20 * " 2! #? $ " "! % 2 0 * " # % %! " * " ) $ " " # + ( > &! " % 0 * 3&" % 0! / % & % % 3 " " / % 3&" % 3 " " & " -! " % *!2 &./, % ' &" % 3 " " '! " % / * & $ &" &! " % ' & * & # > &'! " % $ " & " & "0 $ 3 " ( /* Retorna o item do primeiro nó do argumento, list. Pré-condição: list!= NULL */ type lsthead(link list) { return list -> item;

132 } * $! * "! " * " " & $ &" " &" $ * % "! $ * "! " str * " " & # lst > " 2 &"!& % " $ " " & % # + &" 0!" "? &" "! " % "$ assert. & ( #include <assert.h> type lsthead(link list) { } assert(list!= NULL); /* ou simplesmente assert(list); */ return list -> item; % " &! $ 0 0 assert " & " &%!& " *!& % # ' $!&% % 0 & & & #define NDEBUG " #include <assert.h>. 5 5 < : = # " * % * " & & '

133 #. " 2%! " % &" % & #? *.? " % " # " #!* &" " *

134

135 10. As listas ligadas revisitadas! " * "!& & " " & $ $ " $ & " ' 3, " NULL # "! " " * 2 0 #? * ) & " & " " 2 " &' # $ "! "!& " #, " % # $ " & sllist.h $ " % #&$ " & sllist.c #!& & "!&! " "#? sllist.h $ "!& 0 " & ) * & "! " " & # + "! % " & $! " % $ & "0 & ( &%! "! " % / " "!& /? 3 ' &" + & + &' & ( > ' - " $ " ".! " % #

136 !& 0 $! " % $ 3!" % $ & sllist.c & "0 & "! # + "! % " & " $ &0 ( &%! "! " % / " "!& /? 3 ' &" / + & " " "% $ & " * " % " / + " "% /? & % $ 0 " % $ " o /? 0 3 o!& # < < <: =!& ( sllist.h "!& " " / "& 0 " ) sllist.c typedef int type; typedef struct node* link; struct node {type item; link next;}; /* PRE: plst!= NULL POS: Retorna o item do primeiro nó da lista argumento, apontada por plst. */ type lsthead(link plst); /* Altera o valor do item do primeiro nó da lista identificada

137 pelo argumento plst, com o valor do segundo argumento t. PRE: plst!= NULL POS: plst->item == t */ void lstsethead(link plst, type t); /* PRE: plst!= NULL POS: Retorna a cauda da lista referida por plst. */ link lsttail(link plst); /* Verifica se uma lista está vazia. POS: Retorna 0 se plst!= NULL, retorna 1 caso contrário */ int lstempty(link plst); /* Retorna o comprimento de uma lista identificada por plst, i.e., retorna o nº de nós da lista. */ int lstlen(link plst); /* Insere um nó à cabeça dada lista identificada por ptr_link. O item do nó inserido tem o valor t. PRE: ptr_link!= NULL POS-CONDIÇÃO fraca: *ptr_link!= NULL POS-CONDIÇÃO forte: *ptr_link == newnode, onde newnode é o nó criado para guardar o valor t. Excepção: Se não houver memória suficiente para criar um novo nó, a função escreve uma mensagem de erro e aborta o programa. void lstinsert(link *ptr_link, type t); /* Retorna um link para um novo nó. O novo nó tem como item o valor do argumento t e como next o valor NULL.

138 POS (fraca): o valor retornado é!= NULL. Excepção: Se não houver memória suficiente para criar um novo nó, a função escreve uma mensagem de erro no stderr e aborta o programa. */ link lstnnode(type t); /*Troca as caudas das duas listas argumento pl1 e pl2 PRE: (pl1!=null) && (pl2!=null) POS: pl1->next = lsttail(old pl2); pl2->next = lsttail(old pl1); */ void lstswaptail(link pl1, link pl2); /* Remove o 1º nó da lista identificada pelo argumento plink, libertando o bloco de memória respectivo. PRE: (plink!= NULL) && (*plink!= NULL) POS: *plink = (old *plink)->next */ void lstremovehead(link *plink); /* Remove todos os nós da lista; liberta toda a memória que a lista utilizava. A lista é identificada por p_link, um ponteiro para link. PRE: plink!= NULL POS: *plink== NULL */ void lstremove(link* plink); + & & " " & "0 #, 3 " -)" &". * & & % $ * "! " % * &"& 2 * % " $ $ * "! " % 3 & & 3&" %! $ 2 * 3 $ " % 3 & 2 " & ' &" %! #, 2

139 & " & & % 3 "!& " & ' " )!& % #!" 2 # + 3 <nome> "!& 0 "! " % & <nome> # > " %!2 " " " $ 3 &" " % * # < <9 < 9 ; <= : = #include "sllist.h" #include <stdlib.h> #include <stdio.h> /* Descrição: Retorna o item do primeiro nó da lista argumento, referida por plst. Estrutura de dados usadas: Não se aplica Algoritmos usados: Não se aplica Argumentos: plst ponteiro para o primeiro nó da lista; PRÉ-CONDIÇÃO: plst!= NULL Primeira versão: <nome e do programador> - <data> Alterações: { <Descrição> - <nome e do programador> - <data> } */ type lsthead(link plst) { return plst -> item; } /* Altera o valor do item do primeiro nó da lista argumento plst, com o valor do segundo argumento t. PRE: plst!= NULL POS: plst->item == t */ void lstsethead(link plst, type t) {

140 } plst -> item = t; /* POS: Retorna a cauda da lista referida por lst. PRE: plst!= NULL */ link lsttail(link plst) { return plst -> next; } /* POS: Verifica se uma lista está vazia. Retorna 0 se plst!= NULL, retorna 1 caso contrário */ int lstempty(link plst){ return!plst; } /* Insere um nó à cabeça da lista identificada por ptr_link. O item do nó inserido tem o valor t. PRE: ptr_link!= NULL POS-CONDIÇÃO fraca: *ptr_link!= NULL POS-CONDIÇÃO forte: *ptr_link == newnode, onde newnode é o nó criado para guardar o valor t. Excepção: Se não houver memória suficiente para criar um novo nó, a função escreve uma mensagem de erro e aborta o programa. */ void lstinsert(link *ptr_link, type t) { link tmp = lstnnode(t); tmp->next = *ptr_link; *ptr_link = tmp; } * $ &"0 * &"& "! " "! " % lstinsert & & " " % 0 $ # &"& link link* * 3 " &0 " " ' & #

141 link lstnnode(type t) { link tmp = (link) malloc (sizeof *tmp); if(!tmp) { fprintf(stderr,"lstnnode: Mem. insuf. \n"); exit(1); } tmp -> item = t; tmp -> next = NULL; return tmp; } /* Remove o 1º nó da lista identificada pelo argumento plink, libertando o bloco de memória respectivo. PRE: (plink!= NULL) && (*plink!= NULL) POS: *plink = (old *plink)->next && o 1º nó da lista foi libertado */ void lstremovehead(link* plink) { link tmp = *plink; *plink = (*plink) -> next; free(tmp); }

142 /* Remove todos os nós da lista; liberta toda a memória que a lista utilizava. A lista é identificada por ptr_link, um ponteiro para link PRE: ptr_link!= NULL POS: *ptr_link == NULL */ void lstremove(link *ptr_link) { while(*ptr_link) lstremovehead(ptr_link); } /*Troca as caudas das duas listas argumento pl1 e pl2. PRE: pl1!= NULL; pl2!=null POS: pl1->next = lsttail(old pl2); pl2->next = lsttail(old pl1); */ void lstswaptail(link pl1, link pl2) { } link tmp = pl1 -> next; pl1 -> next = pl2 -> next; pl2 -> next = tmp;! " # $ % $ & ' ( ) % # * # + " $ " #% $ & ' lstswaptail,

143 /* Retorna o comprimento de uma lista identificada por plst, i.e., retorna o nº de nós da lista. */ int lstlen(link plst) { } int n=0; for( ; plst; plst=plst->next) n++; return n; # '! " # $ $ $ $ $ " % % * " % # ( + " $ $ # " # # $ $ % *, Uma lista simplesmente ligada é uma ligação nula ou uma ligação para um nó que contém um item e uma ligação a uma lista simplesmente ligada. $ & " % # $ # " $ " # $ $ % * ( " % # & ' % % $ $ # " $ " # $ $ % * ( ( # * % " ( # ' * " # % & % " $ % $ ( & ' " # % % ( /* Versão recursiva */ int lstlenr(link plst) { if (lstempty(plst)) return 0; else return 1+ lstlenr(lsttail(plst)); } /* Liberta a memória de todos os nós da lista versão recursiva */ void lstremove( link l) {

144 }; if (!l) return; lstremove(l->next); free(l); /* Percorre a lista do princípio para o fim aplicando em cada nó a função passada como segundo arguemento */ void lsttraverse( link l, void (*visit) (link)) { }; if (!l) return; visit(l); ou (*visit)(l); lsttraverse(l->next, visit); $ $ & ' " % ' $ $ # % % & " $, void f( link l ) { printf(printstring, l->item); printf( \n ); }; % * $ $ ", int main() { link l=null; /* */ lsttraverse(l,f); return 0 ; } ;

145 & # $ * #* $ " $ % * & ' f " $ % "! " # % " # ( + * % g & ' ( #include sllist.h void g() { link list=null; lstinsert(&list,1); /* */ lstinsert(&list,3); /* */ lstprint(list); lstremove(&list); } " % " $ & ' * " $ " g # * f g % % " $ & ' f " $ ( # % # % $ % & $ # $ % $ " %! $ $ " $ * $ $ # ( * # $ $ " $ ( # # $ * " # ( * # & ' $ # % # " # & ' $ " & # # $ & ' & ' $ % & * " " % & $ # $ ( * " # % #

146 & ' % & # " # # $ #, & ' % & # " # # $ % #, + " + " # & ', lstinsert(&plst,2); # & ', lstinsert(plst,2); # $ $ & ' * " $ " #% # # $ ( # % * # # & $ # " & $ $ $ $ " % # $ % & " % $ (! " # * " #% # $ $ & ' " # % & ' # ( " # & ' $ $ " #, # l % % # out $ ' $ $ $ $ ( * % # & % & $ # $ " % l " % $ " # # % % * * #! ( $ * max $ $ $ $ max % & $ # max l $ out (

147 ! " # $ %, * $ # # & ' $ max % $ * #* " " $ $ ( max & ' % $ ( : l!=null ) max * % & $ # ' & ' NULL link lstfindprevmax( link l) { link prev=null, max=l; while (l->next) {

148 } if (less(max->item, l->next->item)) { prev=l; max=l->next; } l=l->next; } return prev; # % $ & ', % $ % " $ # $ $ & ', link lstselection( link l) { link prev, max, out=null; while (l) { /* Aqui a pré-condição de lstfindprevmax é garantidamente satisfeita */ prev=lstfindprevmax(l);

149 } /* Move o nó max da lista de entrada */ if (prev) { max=prev->next; prev->next=max->next; } else { /* o max é o primeiro da lista */ max=l; l = l -> next; } /* para a lista de saída, out */ max->next=out; out=max; } return out; "! " # $ # % % # " # # $ ( " $ # $ " " % ( " " NULL ( & ' $ * % & $ # " $ " $ % $,

150 * % " " * ' % % & ' $ " % $ # % ( # % * % " $ % # plist " ' " " " # ( # % * & ',! % " # " % " " # % % # # " $ % $ $ " # ( % $ # $ $ " $ * ' $ * ( " # & ' " * # " & ' $ * # % % # " # # $, /* Insere um novo nó identificado por pnode numa lista circular simplesmente ligada, imediatamente a seguir ao nó identificado por plink_last. plink_last é um ponteiro para link, que aponta para o último nó da lista. PRÉ: (pnode!=null) && (plink_last!=null) */

151 void clstinsert( link *plink_last, link pnode) { } if (! *plink_last) { /* lista vazia */ } else { } *plink_last=pnode; pnode->next=pnode; pnode->next=( *plink_last)->next; (*plink_last)->next=pnode; # * $ " $ $ " & ' $ % $ % $ * $ " & " * $ $ & ' clstinsert ( void clstinsert( link *plink_last, type t) { link pnode = lstnnode(t); if (! *plink_last) { # * *plink_last = pnode; pnode->next = pnode; } else { pnode->next=( *plink_last)->next; (*plink_last)->next=pnode; } } /* Retorna o comprimento de uma lista circular simplesmente ligada */ int clstlen(link plist) { int n=0;

152 } link tmp=plist; if (! plist) return n; # * do { tmp = tmp-> next; n ++; } while(tmp!= plist); return n; & # # % % # ' $! $ %! % % ( ) $ % # & " " % % # $ $ $ $ # % # (! " # " & $ " #! * & ' % $ $ $ " % " % " $ # # % # $ " # # $ ( " % # % % # $ " # # $ ( " " $ # " $ " # $ $, typedef int type;

153 type struct node *link; struct node { }; /* ou struct node { }; */ link prev; type item; link next; link prev, next; type item; # $ " # # $ ' % $ % % # ( % % # ' * % " # $ # pn, pn == pn->prev->next == pn->next->prev. $ * $ " $ $ # % " " $ $ $ % # % #$ $ ( # $ # $ " # # $ " * # $ # " % $ " " " ( # $ " # # $ $ " #% " & % " $ # " " $ " #% $ " # & $ # " % $ " & ' % ( $ % " $ & & # $ " # # $ ( $ & # $ " # # $ % & " % * & ' " dllst (

154 /*Remove de uma lista duplamente ligada o nó referido por pnode; PRE: pnode!= NULL */ void dllstremove(link pnode) { pnode->prev->next = pnode->next; pnode->next->prev = pnode->prev; free(pnode); } /*Insere o nó referido por pnode à direita do nó referido por *ptr_link de uma lista circular duplamente ligada PRE: (ptr_link!= NULL) && (pnode!=null) */ void dllstinsertright(link *ptr_link, link pnode) { if(! *ptr_link) { /* lista vazia. Depois da inserção temos a configuração da figura*/ *ptr_link=pnode; pnode->next = pnode; pnode->prev = pnode; } else { /* lista tem pelo menos um nó.ver figura abaixo. */ pnode->next = (*ptr_link)->next; (*ptr_link)->next = pnode; pnode->prev = *ptr_link; pnode->next->prev=pnode; } }

155 ( # & $ $ # " # # $ $ % $ $ & ' # * # ( $ $ * % " " % " $ $ $ ( ( % * & ' % $ # " # # $ % # # " " " " ( & ' % % " % $ & $ " $ % $ ( " % " " % $ & ( % * & ' % $! # " # # $ % # # " " " " ( ( " # * ' % * $ & ' * $ $ % $ ( & ' /* Remove o 1º nó da lista identificada pelo argumento plink, libertando o bloco de memória respectivo. PRE: (plink!= NULL) && (*plink!= NULL) POS: *plink = (old *plink)->next && o 1º nó da lista foi libertado */ void lstremovehead(link* plink) ( % * & ' " % % " " $ % $ $ * #* " " % " # $ ( * $ % $ ( % # % " " % $ & $ & ' (

156 ( $ % $ $ ( " # * * % * $ & ', /* PRE: plist!= NULL POS: mostra no ecrã todos os valores dos nós da lista plist. */ void lstprint(link plist) % * & $ # $ & ' lstapply " % # % $ " & ' % $ % " ", $ void lstapply (link plist, void (*fn) (link, void*), void *arg) " " % & $ # " " & ' plist fn " #% % $ & ' % $ % " plist $ arg ( % # & ' lstapply $ # " " # & ', int lstlen(link plist) $ $ # " $ " plist ( $ % * & ' * $ * # $ # " # $ ( ( " # & ' $ $ & ' " # # $ $ #, % ( % * & ' % * % $ # % % # " # # $ ( % # % " " % $ & $ & ' (

157 ( " # & ' % ' $ $ $ " $ # % % # ( ( % * & ' $ $ " " $ # % % # " # # $ * ( ( " # & ' * & ' % * % $ # % % # $ " # # $ $ " # * % # $ $ " # * ( ( " # & ' $ $ % $ " " # % % # $ " # # $ ( ( $ # % % # $ " # # $ ( % $ $ #! " " $ & * % * ( + $ $ % $ # ( % # % " " % $ & $ &, + $ " " * $ $ # ( + $ " " $ # " " * # % "! % $ " ( % + $ " " $ # " " & ' % % " " * int $ $ # " & ' " $ " pf * # $ $ ( $ + * #* " " # # $ % % & ' $ $ # $ $ % ( pf ( $ # " # # $ % n $ % $ $ " $ " $ ( $ $ ',

158 # " % # ( + * #* " % #% # $ l c " % # % # $ # ( " n-1 n $ * % # $ # % * # ( 1 $ $ * $ % $ $ $ ( " $ * % # $ $ * % % " $ $ * # $ n (! " # % $ l c % " % # " # # $ % $ " $ " $ # " % # % $ " % # # $ $ ( ( * $ % $ # * " % * % % $ " # ( " $ % " $ $ % $ % # % % % # # % $ % $ % ( " % # " % " % * $ % " % # " & ' $ % % # # $ ( % " & ' $ * * # # $ % $ & % " # $ " ( + * #* " # # & ' $ % $ # & ' $ " # $ " ( # & '! " $ " % % # $ # $ " * " & ' $ % ( % % & $ * $ $ # $ ( " % $ " % " (

159 % $ " " $ " % % % $ ( " # $ $ $ " % ( " $ * % " % " " * ( " $ * # # % % # $ % $ " $ % $ " ( " # $ % $ * $ % $ & # " " # & ' $ " $ # ( +! % & ' " $ * $ $ " * ' $ # $ ( " $ * $ % * * (! " #, " * *, " " $, " % $ $ " % % $ $! % % ( (! % % ( % % #

160 11. Tipos de dados abstractos $ $ " % $ % % # $ * #* $ " % % $ $ % # # $ $ " $ $ $ " & ' $ * # $ " ( + % # * $ " # * # $ " * $ " & & " $ " # ( ) " # * " & $ * # * # $ % # ' % $ # % $ $ $ % $ " $ $ $ $ % # & ' $ & ' # $ ( " $ $ $ % $ # " # + " $ $ $ % $ * # % # % & ' $ " & * # % * # " % # " * $ " & $ " * % ( + " & ' $ $ $ & " # " & ' % " # " $ $ % # " # % ( + % " % % # ' " $ * " # & ' * $ # ( # # $ " & ' $ " # % " "! " #% % $ " # & ' % # " # & ' $ " $ $ $ % (

161 # $ " & ' ' $ " # %! " #% " " # $ % + " * # $ * # $ * #* " $ % $ % % % ( " # & ' $ # # $ $ $ " #% % $ $ $ " * $ & % $ * #* ( " # % " * & $ % & ' $ % % + * % # ( $ # " & ' $ # " $ $ % $ # % % # $ # " # # $ " # $ " # # $ ' # " " $ & ' % $ # % $ % # ( % * & ' " #% $ # % $ # ' " + ( $ " # # $ & % ' $ ( % % % * #* " $ ' $ (! " # #* <string.h> ' $ + * " ' " $ % % $ $ % % ( # $ " " $ % $ $ % " & ' $ $ " ( # $ ' " * # $ " & ' $ $ " # # $ # " % # ( " & ' $ $ $ * $ " * # % # * # * $ " $ ( $ " $ # " % # # " & ' $ $ $ $ % $ # " " $ (! " # " $ " % % $ $ " % % # ( ) % % ' & $ " # & ' $ $! ' $ % % % " " $ * " $! % & ' (

162 + ' % $ & ' % # " & ' $ $ $ ( % % % # ' ' % # " & ' ( * #! " # $ + (

163 12. O tipo de dados abstracto pilha " # # #! %! " # # $ $ $ " $ $ $ % ( ) # " # $ $ $ # " & ' % " & ' (! " # * # & ' $! " % % $ " #! " # "! % & ' # " # " " % $ & ( " # " $ * % % " % # $ # $ $ ( # $ $ $ n # n IN " 0 " $ L=(l0,l1,..., ln-1) l i 0<= i<n # ( ) # * * " $ " ( n=0 L=() % # $ $ & & # $ % ' $ # % # $ # " $ % " ( % " & ' * # " $ % % $ push " & ' $ & ' # " $ % % $ pop ( $ $ % % # %! " # $ % % % (

164 , " # $ " " $! # $ " $ % $ $ # % # % $ " # " $ ( ) % $ " * $ % $ % # ' % ", $ % # " " " $ % " " " " " $ " %

165 " + " " " " " ", % $ % % & ' " $ % % % (

166 + $ % $ # $! S=(s0,s1,..., sn-1) s0 sn-1 # $ " $ $ % $ ( * 0<i<n si # # " * $ % $ $ " # ( si-1 % * " + " % $ $ % & ' $ + ( $ % & ' $ # % % % " & " $ " # + " % $ &! ( $ % & ' # $ $ ( # $! " # " % & ' " % % & ' " + " # ( % $ % &! " " & " $ " % $ " * $ % " " % $ & ( " * ' $ % $ + " # $ $ % " $ stack.h " $ % ( ) $ % * & ' # # # $ " $ & $ #* $ & $ " # & ' $ + " # % & " ( # & ' $ % # $ % $ + ( STACK /* ficheiro: stack.h */ /* Verifica se o stack está vazio; retorna 1 se o stack estiver vazio; retorna 0 caso contrário. */ int STACKempty(void); /* Verifica se o stack está cheio; retorna 1 se o stack estiver cheio; retorna 0 caso contrário */ int STACKfull(void);

167 /*Cria um stack vazio com a capacidade máxima de n elementos. PRÉ: n>0 POS: (STACKempty()==1) && (STACKfull()==0) */ void STACKinit(int n); " % % * # ' % ( $ $ % $ $ " # " % $ & ' $ & ' % ( ) * # * # $ % $ * % % " $ % ' * ( * " & ' " " " & ' $ # $ * " % $ " & ' % ' " $ % ( * & ' % " $ " # " " % $ & $ & ' ( /*Retira e retorna o último item carregado no topo do stack. PRÉ: STACKempty()==0 POS: STACKfull()==0 */ type STACKpop(); /* Devolve o elemento no topo do stack; Não altera o conteúdo do stack. PRÉ: STACKempty()==0 POS: STACK == old STACK; em que STACK representa o estado do stack. */ type STACKtop(); ) * $ * # % % % % % " & " * * # ( ( ' % ( " $ * # % % $ % ' * * # " $ % ( * & ' % " $ " # " " % $ & $ & ' ( /*Carrega o item t no topo do stack. PRÉ: STACKfull()==0

168 POS: (STACKempty() == 0) && (t==stacktop()) && (STACKpop() == old STACK), em que STACK representa o estado do stack. */ void STACKpush(type t); % * " + " % " $ % % $ % & ' ( $ $ % * + * $ " % % & ' ( ( * $ $ % & ' # % " # ( + " $ * # " % % & ' $ + $ " # % #, ( $ * $ $ % ( $ % * " $ " % % ( ( " & $ % * $ % $ $ " & $ + (! $ % * " " $ $ # $ " & ( % $ & $ % * % $ & $ " #% & ' $ % $ " & ' ( % $ %, (, + % $ % " $ " % % % $ Stack[G] - % " * # $ " % G ( ( " &, ( ( ( ( init, IN stack[g] empty, stack[g] {0, 1}

169 ( ( ( ( ( ( ( ( full: stack[g] {0, 1} push, stack[g] x G stack[g, pop, top stack[g] stack[g] stack[g] G $ " # " * $ $ ( % $ $ & ' 0 1 " % # & ' ' $ $ " $ # $ % $ " $ ( " # * & ' " % $ & ' % $ (! " # " & ' $ % % " #% & ' $ $ push $ % $ $ $ " $ % $ $ stack[g] # % G stack[g]. " & % $ $ % # ' ' % % $ % # & ', f: IR IR & ' & ' # $ * * # # " % % $ $ f & ' ( + % % % " & $! " % $ & ( (!, $ ( ( top(push(s,x))=x ( ( " " "! ( ( " ( ( ## 3.5. empty(push(s,x)) = 0; 3.6. full(pop(s)) = 0; n IN, x G s stack[g]

170 ! ( (! " " " $ $ $ # $ % " # % $ & ' # " ( ( % $ %, $ ( ( ( ( ( ( s stack[g] x G pop(s) empty(s)=0; top(s) empty(s)=0; push(s, x) full(s)=0; % " % $ & ' $ & ' % % % $ $ $ " $ * % & ' ( & ' % % f % $ % $ f A % X, A, & ' # A: X {0, 1} # A (x) 1 x A 0 % % ( # & '! " "! " % ( & '! " $ % # % $ $ " $ % ( # * & '! & '! ( & ' % $ " $ % # % $ " " $ % ( & ' ' $ $ % & $ $ % $ " $ ( #! #! " * # % $ &, % %

171 % % % $ % $ " % % " # $ % * & '! & '! % ", ( # % " $ " & ( * " $ " $ $ " ( * $ " ( " # # " % * # % $! " $ $ # ( * # & ' $! " ' & '! " %! " ' $ $ " $ % # % $ " $ % % $ " $ ( $ " $ % $ % " $ % % " $ $ " $ % " & ' * # % # % # $ % ( # " % "! " '

172 $ $ * #* % #% # $ % $ % $ % & '! " $ " " & % ( %! " ' % % #% # $ $ * " % ",! " # $ % " " $ $ " % #% # $ $ * #* (,,,,

173 ,,,,, & # " + % " " # % #% # $ % $ % % # $ % $ & ' #$ * # $ # $ % $ ( ) % * " $ " # % # % $ % % * % % % " $ $ " & " $ ' ' $ " $ $ % " & ' # $ # $ % # % $ % ( $ % & ' $ % $ " " $ $ % " $ $ ( # " $ % * ( # $ *! " # $ # & ' $ " $ $ ( # $ " " & ' $ % $ $ % & " ( $ $ % # " " " $,

174 calc str str res res le avalia escreve no procno op res procop $ % % $ % & ' " % " # % calc " $ & ( # $ % & ' le avalia escreve avalia % % $ % # $ " $ $ $ * % & ' $ % $ & ' & procno procop (! "! " $ & ' $ % $ ( " # % % " $ & ' escreve " $ ' " # printf ( ) " $ " printf $ & ' # ( % ( + % $ % $ * # $ * % * * # ( * # printf res " $ $ & ' $ " & ' #% procop avalia c " * * ( ) % # ' printf printf procop % " " * # $ " #% % $ & res $ ( " #% & ' " $ $ $ $ (

175 calc str str le avalia no op procno procop " $ " $ % & % * % $ ( $ * #* " $ * % $ $ $ % " # " # % $ % $ " $ % $ $ & ' % $ " " # $ " * % # ( " " * #, #include "type.h" #include "stack.h" #include <stdio.h> #include <stdlib.h> #include <ctype.h> #define MAXLEN 20 #define MAX_STACK_SIZE 10 #define ENDCHAR 'q' void le(char *, int); void avalia(char *);

176 void procno(type); void procop(char ); int main() { char str[maxlen]; printf("calculadora para expressões aritméticas em notação sufixa.\n"); printf("características: \n"); printf(" - Operandos: inteiros \n"); printf(" - Operadores: +, - *, / \n\n"); } STACKinit(MAX_STACK_SIZE); for (;;) { le(str, MAXLEN); if(str[0] == ENDCHAR) break; avalia(str); } return 0; void le(char *str, int n) { printf(": "); fgets(str, n, stdin); /* Verificar aqui se str está num formato válido */ } void avalia(char *s) { if(isdigit(s[0])) { type t = (type) atof(s); procno(t);

177 } } else procop(s[0]); void procno(type no) { if (STACKfull()) { fprintf(stderr, "Error: STACK overflow. \n"); exit(1); } else STACKpush(no); } void procop(char op) { type res, o1, o2; if(stackempty()) { fprintf(stderr, "Error: STACK empty. \n"); exit(1); } else o2 =STACKpop(); if(stackempty()) { fprintf(stderr, "Error: STACK empty. \n"); exit(1); } else o1 =STACKpop(); switch (op) { case '+': res = o1 + o2; break; case '-': res = o1 - o2; break; case '*': res = o1 * o2; break; case '/': if(o2) res = o1/o2; else { fprintf(stderr, "Error: divide by zero; finished. \n");

178 } exit(1); } break; default: { fprintf(stderr, "Error: unknown command. \n"); exit(1); } } /* Aqui existem pelo menos dois lugares vazios no stack */ STACKpush(res); printf(printfstring, res); printf("\n"); $ % # & ' $ ( printfstring printf % $ " ' $ $ % ( * type type.h % $ $ % " $, typedef int type; #define printfstring "%d" # % # $ % $ $ type.h " % # % $ $ " # & ' $ % $ * " * % # # " # ( " % $ * $ % # & # " #, $ #ifndef _TYPE_ #define _TYPE_ typedef int type; #define printfstring "%d" #endif

179 #ifndef #define #endif ' % $ $ % * $ " " % $ ( " " % $ " $ " $ $ % " # $ ( " " % $ " # # $ # % " % % # $ % * ( ) ' * $ $ $ % * % $ <identificador> #ifndef <identificador> % $ % $ $ $ % *, #else #elif #endif ( % % # ' " $ $ " $ * #* $ $ " % $ + % ( + $ * #* ' * $ % % $ # $ " # & ' $ % % % " % & ' $ % #% # $ (! * " & " # & " * " + % " " ( * # $ % " * ( " & ' " * # % $ % $,

180 * % % % " & & $ # $ $ # % " ( " " # $ % # # $ " " $ %, % & % $ $ % $ * & & % & $ % $ " $ " % " $ " $ $ % " $ % $ ( ) $ $ & $ & ' & ' % & $ * #* $ % # % & $ % $ % " $ % ( ) % & & " % % $ $ % $ " " # & ' % $! '.c % stack.c, % $ & $ $ % " $ % $, #include <stdlib.h> #include "type.h" #include "sllist.h" /* Funções que definimos sobre as listas*/ static link pstack = NULL; static int capacity; /* capacidade do stack */ static int actsize; /* tamanho actual do stack */ /* Inicializa um stack, com capacidade para n elementos. PRE: n > = 0 POST: (STACKempty() == 1) && (STACKfull() == 0) */ void STACKinit(int n) { pstack = NULL; capacity = n; actsize = 0;

181 }; /* Retorna 1 se o stack está vazio; retorna 0 caso contrário. */ int STACKempty(void) { return!actsize; /* ou return pstack ==NULL */ }; /* Retorna 1 se o stack estiver cheio; retorna 0, caso contrário. */ int STACKfull(void) { return (actsize == capacity); }; /* Retorna e retira o último elemento inserido no stack. */ /* PRE: STACKempty()==0 */ /* POS: STACKfull()== 0 */ type STACKpop(void) { type item = lsthead(pstack); lstremovehead(&pstack); actsize--; return item; }; /* Retorna o último elemento inserido no stack; Não altera o estado do stack. PRE: STACKempty()==0 POS: STACK = old STACK; onde STACK representa o estado do stack. */ type STACKtop(void) { return lsthead(pstack); }; /* Carrega um elemento do tipo t, no stack

182 PRE: STACKfull() == 0 POS: (STACKempty() == 0) && (t==stacktop()) && (STACKpop() == old STACK), em que STACK representa o estado do stack. */ void STACKpush(type t) { } ; lstinsert(&pstack, t); actsize++; * " # * static * * # # % # & ' " " * % $ $ * * # % $ % * & ' ( $ " #% $ * *! * * $ $ $ # & ' " # * % * # #% % $ * * # $ % $ static % $ $ $ % # $ ( " #% $ & $ $ % ( static " # * % * " " % $ % $! static $ % $ ' $ $ ( " & ' " % $ % ( " ) % % % " % $ $ " # $ $ " & ' # $ (

183 " # & ' $ " & ' % " $ $ $ ", #include <stdlib.h> #include <stdio.h> #include "type.h" static type *pstack = NULL; static int capacity; static int actsize; /* Inicializa um stack, com capacidade para n elementos. PRE: n > = 0 POST: (STACKempty() == 1) && (STACKfull() == 0) */ void STACKinit(int n) { pstack = (type *) malloc (n*sizeof *pstack); if(!pstack) { fprintf(stderr, "Error in STACKinit: not enough memory\n"); exit(1); } capacity = n; actsize = 0; }; /* Retorna 1 se o stack está vazio; retorna 0 caso contrário. */ int STACKempty(void) { return!actsize; }; /* Retorna 1 se o stack estiver cheio; retorna 0, caso contrário. */ int STACKfull(void) {

184 }; return (actsize == capacity); /* Retorna e retira o último elemento inserido no stack. */ /* PRE: STACKempty()==0 */ /* POS: STACKfull()== 0 */ type STACKpop(void) { return pstack[--actsize]; };, /* Retorna o último elemento inserido no stack; Não altera o estado do stack. ), STACKempty()==0 STACK = old STACK; type STACKtop(void) { return pstack[actsize-1]; } $ STACK " $ $ ( /* Carrega um elemento do tipo t, no stack PRE: STACKfull() == 0 POS: (STACKempty() == 0) && (t==stacktop()) && (STACKpop() == old STACK), em que STACK representa o estado do stack. */ void STACKpush(type t) { pstack[actsize++] = t; } $ $ " # % $ % $ % & " % $ $ $ & " (

185 " ) % % % " % $ $ " # $ $ " & ' # $ ( * " $ " & ' $ % # &, static type *pstack = NULL; static int capacity; static int freespace; /* Número actual de posições desocupadas no STACK */! " # ( +! %! % % " # & ' $ & freespace=3 " " # & ' $ % " & ' ( $ " # & " % $ % ( $ " # & ' " % " # " % # % % $ # # & ' " stack1.c stack2.c % # ( * % " % # " $ " # + % ' " # & $ % ( $ & " # & * # $ $ " ( ) * " #% & ' % pops " $ push % % * ' " # & ' % " * # * ' % * # " % $ $ # " & (

186 # $ * # % " & $ $ $ % ( + " " % $ $ % % $ $ $ $ #! $ " * # " # & ' $ # # $ ( " # & ' $ " # & ' $ # " " # " & pop push " % ( " # & ' $ # " $ $ # ' $ % $ $ ( " % ' " * # malloc $ ' * $ " * # ( NULL " $ % % % " # % #$ $ $ # & ' $ % #% # $ % * # % & '! & ' # ( $ * #* % * $ & '! " & '! ( ) " % in2post ' $ * " % ", > in2post * 3 <enter> * + > in2post 1 * <enter>

187 1 2 * 3 + # $ % * ' & '!! * " % % *!! " ' " % $ * ( # % $ * & ' $ " $ ' " $ # $ " # $ % " %! " ' # % $ $ ( # $ " % $ " $ # $ $ " $ $ " % $ % (! " # % * ' $! " ' 1+2*3 " % " # $ ( % " # & % # % " $ % ( %! " # " # " % " # $ % $ " (! " #, $ $ #, $ ) %, ) $ $ $ % $ " $ " " $ " % $! " ' # % $ $ ( ) $ $ # $! " ' " $ $ ' " $ $ % # % $ $ ( $ % " $ % # % $ % ( $ $ " " $ $ # " % $ " $ ( $ % " $ % " " % $ % % " % $ % $ " $ % (! " # % + " % $ % $ * % " & ' " $ # $ " $ (

188 + $ $ % * " $ % # % $ % + " $ " $ (! " #, $ ) %, ) $ + % # % $ % # % ( $ % % #$ * % # % $ % ( " % $ % # * * $ $ % " $ ( $ % $ $! " ' # % $ $ % # % $ $ " $ * # $! % ( #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "type.h" #include "stack.h" #define N 10 void procop(char); int precedence(char ); int main( int n, char **argv) { int i; STACKinit(N);

189 } for(i=1; i < n ; i++) if (isdigit(*argv[i])) printf("%s", argv[i]); else procop(*argv[i]); while (!STACKempty()) printf("%c", STACKpop()); return 0; void procop(char opt) { if (STACKempty()) { STACKpush(opt); return; } if (precedence(opt) > precedence(stacktop())) { if (!STACKfull()) STACKpush(opt); else { fprintf(stderr, "ERROR: stack overflow."); exit(1); } } else { while(!stackempty() && (precedence(opt) <= precedence (STACKtop()))) printf("%c", STACKpop()); STACKpush(opt); } } int precedence(char c) { static enum precs {addsub = 1, mux = 10}; switch(c) { case '+':

190 } } case '-': return addsub; case '*': case '/': case '%': return mux; default: fprintf(stderr, invalid operator ); exit(1); & '! " # $ % $ % $ #! * #, * # % % " $ & '! $ ( & ' # #! #$ $ $ " # ' $ " # & ' $ $ " & " * $ % # $ # * " " # " & * % ( + $ " % $ % $ $ $! " #,! " ' & '! notação sufixa ab*c-de*+fg/- a*b-c+d*e-f/g é equivalente à expressão em $ $ #, $, a * b - c + d * e - f / g ) % * estados do - stack: + + * - $, * (cada linha corresponde a um estado do stack) - / a b * c - d e * + f g / -

191 # & ' % " " % ' " % " $ % % " $ # %! ' $ % $ "! " % " $! $ %! % % (! " # % $ * $ % & ' " " % # *, " % " * #! " & '! ( " % % $ "! " ' " & '! $ " * # " & ' $ $ # $ % #% # $ $ * #* ( $ % # $ # & $ " $ " # & ' $ +, % % $ % in2post calc $ " " $ % " " $ char ( " # & ' $ + % ' " $ % ( % " $ " " # & ' $ + ( % # % " & ' % % ( " % $ # $ " # " & ( ( $ % &! + " # " $ ( $ " # & ' $ # # $ % # " " % $ & (

192 STACKcount(void); /* retorna o nº de elementos no stack; */ STACKchangetop(type t); /* substitui o topo do stack por t; */ STACKwipeout(void); /* remove todos os elementos do stack; */ ( " # + % $ " % $ # # $ " " ( ( + * #* + # % & $ % * ( ( " # % #% # $ " & '! " " & % # $ $ * ' ( $ $ $ $ + - * /! % $ * $ $ " ( # % $ " $ (! " # $ # & ', >calc 5! 2 3 * 4 % ( % * & ' * " % * % % *!! " ' % ' % % ( & ' "! ", ( ( ( (! ( $ " in2post " " %! " % " (

193 13. O tipo de dados abstracto fila de espera $! " % $ " # ( " # " # % $ $ ( % " $ $ " ( % $ $ $ # % $ $ $ $ & % # ' " $ * $ % $ % " # " % ( * $ " ' # $ % $ % #! ' % # % * $ % " $ ' & $ $ " # * ( ) & % $ % % ' % % ( ( " * $ $ % " $ " # + # $ " " " " $ $ $ % $ # ( % $ " # # * " # $ " ( # # $ $ $ & ' $ # $ $ # $ & ' $ # $ % ( + $ # F=(f0, f1,..., fn-1) f0 # $ # $ ( # fn-1 fi+1 fi 0<= i < n-1 & ' " put enqueue & " ( get ( dequeue)

194 " " " % % " # " $ $ $ %, /* Ficheiro: queue.h */ #include "type.h" /* Inicializa uma fila FIFO, com capacidade para n elementos. PRE: n > = 0 POST: (QUEUEempty() == 1) && (QUEUEfull() == 0) */ void QUEUEinit(int n);

195 /* Retorna 1 se a fila está vazia; retorna 0 caso contrário. */ int QUEUEempty(void); /* Retorna 1 se a fila está cheia; retorna 0, caso contrário.*/ int QUEUEfull(void); /* Retorna e retira o primeiro elemento inserido na fila. */ /* PRE: QUEUEempty()==0 */ /* POS: QUEUEfull()== 0 */ type QUEUEget(void); /* Insere um elemento do tipo type, na fila PRE: QUEUEfull() == 0 POS: QUEUEempty() == 0 */ void QUEUEput(type t); " # $ " $ # # $ $ $ # " $ (

196 " & put get " " % & $ * # $ # & % & * " plast " # $ # ( /* ficheiro: queue1.c */ #include "sllist.h" #include "type.h" #include <stdlib.h> #include <stdio.h> static link pqueue; static link plast; static int capacity; static int actsize; /* Descrição: Inicializa uma fila FIFO, com capacidade para n elementos Parâmetros: n - inteiro positivo; indica o número max de elementos da fila. Pré-condição: n > 0; Pós-condição: (QUEUEempty() == 1) && (QUEUEfull() == 0); */ void QUEUEinit(int n) { capacity = n; actsize = 0; plast=pqueue = NULL; } /* Retorna 1 se a fila está vazia; retorna 0 caso contrário. */ int QUEUEempty(void) { return!actsize; }

197 /* Retorna 1 se a fila está cheia; retorna 0, caso contrário.*/ int QUEUEfull(void) { return actsize==capacity; } /* Retorna e retira o primeiro elemento inserido na fila. */ /* PRE: QUEUEempty()==0 */ /* POS: QUEUEfull()== 0 */ type QUEUEget(void) { type tmp = lsthead(pqueue); lstremovehead(&pqueue); actsize--; return tmp; } /* Insere um elemento do tipo type, na fila PRE: QUEUEfull() == 0 POS: QUEUEempty() == 0 */ void QUEUEput(type t) { link nn = lstnnode(t); actsize++; if(queueempty()) { pqueue = plast = nn; } else { plast -> next = nn; plast = nn; } }

198 # ( lstremovefirst % # % pqueue NULL ' * # # " * # " # # $ ( " & $ " " % get put $ %, " % $ # out " " & ' $ " * # $ # in ( # % % " & % $ # % % " % $ $ " # ( % * # # # $ % in % $ % ( # # $! $ " out % ( ) $ %! % $ # $ ' % # $ out ( % % % # ( * % # * % " $ % * * # % $ % $ % # $ # ( actsize, " $ " " $ % " in out * % & ( # $ " # # $ " % $ * & " % % "! " # ' $ $ % # $ $ " # ( $ % in out " * % # * % ( % $ & ' $ # * * % "! " # ( in==out

199 $ # * # % * " & ' " " # ( # % " # n+1 # ' $ # * in==out (! " #, % # # * n " " "

200 " /* Ficheiro: queue2.c */ #include <stdio.h> #include <stdlib.h> #include "type.h" static type* queuep; static int capacity; /* capacidade máxima da fila */ static int capp1; /* capp1 = capacity + 1 */ static int in; /* índice da posição disponível para inserção, no fim da fila */ static int out; /* índice do próximo elemento a sair da fila */ /* Função auxiliar; visível apenas neste ficheiro. Dado um índice, calcula o índice seguinte. Esta função só deverá ser chamada após QUEUEinit */ static int nextindex(int i) { return (i+1) % capp1; }

201 /* Inicializa uma fila FIFO, com capacidade para n elementos. PRE: n > 0 POST: (QUEUEempty() == 1) && (QUEUEfull() == 0) */ void QUEUEinit(int n) { capacity = n; capp1 = capacity + 1; in = out = 0; queuep = (type *) malloc (capp1 * sizeof *queuep); if(!queuep) { fprintf(stderr, "Error in QUEUEinit: not enough mem for queue allocation"); exit(1); } } /* Retorna 1 se a fila está vazia; retorna 0 caso contrário. */ int QUEUEempty(void) { return in==out; } /* Retorna 1 se a fila está cheia; retorna 0, caso contrário. Quando a fila está cheia, se inseríssemos outro elemento ficaríamos com a ilusão de que a fila estaria vazia */ int QUEUEfull(void) { return nextindex(in) == out; } /* Retorna e retira o primeiro elemento inserido na fila. */ /* PRE: QUEUEempty()==0 */ /* POS: QUEUEfull()== 0 */ type QUEUEget(void) { type tmp = queuep[out] ;

202 } out = nextindex(out); return tmp; /* Insere um elemento do tipo type, na fila PRE: QUEUEfull() == 0 POS: QUEUEempty() == 0 */ void QUEUEput(type t) { queuep[in]=t ; in = nextindex(in); } ( % # % " & ' # $ " % ( " % $ # $ " # " & ( ( " # + # $ " $ ( $ " " & % %! % " % ( $ * % & ' # % *, ( % $ $ # ( ptr prt out

203 14. As filas revisitadas " $ $ $ % " # % % " " # % # " ( # " # %, " " ( + " $ $ % $ " # " # % " * #, " # * # # % # * " ( # ' ' % " # % $ & ' " * (! " # " # % # *, * $ #! # % " #$ $ ( $ # " #$ $ $ $ " ( + % # # (

204 $ % % # ' $ " # % $ $ " # + ' $ " $ $ % # # ( * $ # #! " # $ " $ # $ $ # # # % " $ $ ( # # $ $ #$ $ " % " " % $ # " & ' ( " # &! % " & % " % ( # & ' $ $ % $ " $ % $ + ( % $ # & ' $ % # $ % $ $ $ # * # % ( # $ " #% & % # # $ " % " & $ $ # & ' $ % & ( ) $ " % $ & # " % $ + ( /* Ficheiro: rq.h interface fila aleatória (Random queue) */ #include "type.h" /* Inicializa uma fila aleatória, com capacidade para n elementos. PRE: n > 0

205 POS: (RQempty() == 1) && (RQfull() == 0) */ void RQinit(int n); /* Retorna 1 se a fila está vazia; retorna 0 caso contrário. */ int RQempty(void); /* Retorna 1 se a fila está cheia; retorna 0, caso contrário. */ int RQfull(void); /* Retorna e retira aleatoriamente um elemento da fila. Todos os elementos têm probabilidades iguais de saírem. PRE: RQempty()==0 POS: RQfull()== 0 */ type RQget(void); /* Insere um elemento do tipo type, na fila PRE: RQfull() == 0 POS: (RQempty() == 0) */ void RQput(type t); + * " # & " * " # & ' $ " # $ " & $ # % " " % ( % # $ " # & '! ( " & ' $ % $ % * # $ # ( # $ $ % $ * RQput(type t) t " & ' $ # % & ' $ % # RQget() # $ # % # $ " $ $ $ $ # $ $ $ (

206 /* Ficheiro: rq.c fila aleatória (Random queue) */ #include <stdlib.h> #include <stdio.h> #include "rq.h" static type *rq = NULL; static int capacity; static int actsize; /* Inicializa uma fila aleatória, com capacidade para n elementos. PRE: n > 0 POS: (RQempty() == 1) && (RQfull() == 0) */ void RQinit(int n) { rq = (type *) malloc (n*sizeof *rq); if(!rq) { fprintf(stderr, "Error in RQinit: not enough memory\n"); exit(1); } capacity = n; actsize = 0; }; /* Retorna 1 se a fila está vazia; retorna 0 caso contrário. */ int RQempty(void) { return!actsize; }; /* Retorna 1 se a fila está cheia; retorna 0, caso contrário. */ int RQfull(void) { return (actsize == capacity);

207 }; /* Retorna e retira aleatoriamente um elemento da fila. Todos os elementos têm probabilidades iguais de saírem. PRE: RQempty()==0 POS: RQfull()== 0 */ type RQget(void) { int r = rand() % actsize; /* Número aleatório entre 0 e actsize -1 */ type tmp = rq[r]; rq[r] = rq[--actsize]; return tmp; } /* Insere um elemento do tipo type, na fila PRE: RQfull() == 0 POS: (RQempty() == 0) */ void RQput(type t) { rq[actsize++] = t; }! & " $ % $ # % " # % $ & ', * #! ( $ $ $ " " # % $ & ' $ $ ( # % " $ $ ' $ # & * #* # " % # % # ' $ " % " $ " * ' $ # # $ $ & ' $ " % " & $ $ $ % " ' $ $ $ (

208 # " # " # # $ " $ # " " $ $ " # # $ " % # % * " $ $ $ # ( ) % & ' $ # % " $ $ " & ' $ $ # ' % % $ " % $ % " $ % % " $ & ( % " % % * ( # # % & ' $ % " " % * $ " $ $ " #% & ' (! " # % # % & ' $ % & ' # % " " * % # $ $ ( + " $ $ $ % * $ " #% & ' % * " $ # $ % " ( $ $! # & ' $ $ % * # " # * # $ % *!!!! ( # & ' $ $ * " # * # $ % *!! '! ( % $ # % " $ $ " % $ $ % $ # (, /* Ficheiro: pqueue.h */ #include "type.h" typedef struct priority_queue *PQ; /* Inicializa uma fila com prioridades, com capacidade para n elementos. PRE: n > 0 POS: (PQempty() == 1) && (PQfull() == 0) */ PQinit(int n);

209 /* Retorna 1 se a fila está vazia; retorna 0 caso contrário. */ int PQempty(void); /* Retorna 1 se a fila está cheia; retorna 0, caso contrário. */ int PQfull(void); /* Insere um elemento do tipo type, na fila pq PRE: PQfull() == 0 POS: PQempty() == 0 */ void PQput(type t); /* Retorna e retira o elemento da fila com a maior chave PRE: PQempty() ==0 POS: PQfull()== 0 */ type PQdeletemax(void); # $ " & " & " % # ', /* Altera a prioridade do elemento t da fila; se t existir, deixa a fila inalterada caso contrário. PRE: PQempty() ==0 */ void PQchangePriority(type t); /* Remove o elemento t da fila; se t existir, deixa a fila inalterada caso contrário. PRE: PQempty() ==0 */ type PQdelete(type t); /* Devolve o elemento com maior chave sem o remover. PRE: PQempty() == 0

210 POS: não altera o estado da fila */ type PQmax(void); /* Troca o elemento com maior chave com o argumento t. PRE: PQempty() == 0 */ PQswapmax(type t); " % ' " " % # " # & ' ( * " # & $! $ " $ ( + " $ * % " # # # $ " " % " " # # % " $ $ $ % $ $ $ % ( & ' % % $ " # * # & % $ % #! % % # % # # $ $ # $ $ $ ( " " # & ' " $ # $ $, /* Ficheiro: pqueue.c */ #include pqueue.c" #define less(a,b) (Key(A) < Key(B)) static int ta; /* tamanho actual */ static int cap; /* capacidade */ static type *elems; /* array de elementos */

211 /* Retira e retorna o elemento da fila com a maior chave PRE: PQempty() ==0 POS: PQfull()== 0 */ type PQdeletemax(void) { int I, mx = 0; type t; for (i=1; i< ta; i++) if (less(elems[mx], elems[i]) mx = i; t = elems[mx]; elems[mx] = elems[--ta]; return t; " # & ' $ & $! $ %! % % ( " # & ' $ " # % # $ % " $ # " # " ( " # $ " % * # " %! " " " % # $ # ( ' $ % # % " # & " & $ & ' " & $ & ' % " % ( % " # & " & % $ % " $! % % ( # $ # $ % * ( " # # " $ * % % " % # $ # $ $ ( $ $ # $ $ " $ " # + $ * ( " # " $ " # $ $ $ $,

212 ( & ' & ' $ # $ $ $ " # & ' $ * ( ( & ' & ' % $ # $ " # & ' * $ # # $ ( # $ # $ " " $ " # $ % $ $ $, ( & ' & ' " % " $ " # & ' * $ # # $ ( ( " % " * ' % " $ % % " # & ' * ( + " $ * " $ " + " & & " % " $ # $ $ ( + % $ ( $ & ' $ % " # & ' $ + $! $ %! % % ( ( % # % " & ' # $ " % " $ $ % & ' $! ( " % $ # $ " # " & (

213 ( + " # + $ ( " # & ' ( % # % " " % $ & $ % $ & ' ( ( $ + $ " # + % ( ( " # & $ % $ + # # $ # # $ ( % # % " " % $ & $ % $ & ' ( ( % * % # $ + # # #, $ # $ & ' $ # $ % " $ % & ' # $ $ # * # ( " # & $ % $ + # % " $ $ $ $ " & ' $ & ' # $ " % ( # % " #! $ $ " % " % $ & ' $ & ' " " ( ( " # & $ % $ + # % " $ $ $ # # $ ( % * % $ % " * # ( % # % " " % $ & $ % $ & ' ( ( " $ $ # $ # % " $ $ " + % % # $ " " $ $ % " # % # # ( # % % #$ $ $ " # $ # $ " % * ( $ " # #

214 # $ " & $ %! % " % ( $ " # & $ %, /* Inicializa uma fila generalizada (GC generalized queue), com capacidade para n elementos. PRE: n > 0 POS: (GQempty() == 1) && (GQfull() == 0) */ void GQinit(int n); /* Retorna 1 se a fila está vazia; retorna 0 caso contrário. */ int GQempty(void); /* Retorna 1 se a fila está cheia; retorna 0, caso contrário. */ int GQfull(void); /* Insere um elemento do tipo type, na fila PRE: GQfull() == 0 POS: (GQempty() == 0) */ void GQenqueue(type t); /* Retira o elemento da fila inserido mais recentemente (o último da fila) e retorna-o. PRE: GQempty()==0 POS: GQfull()== 0 */ type GQlast(void); /* Retira o elemento mais antigo na fila (o primeiro da fila) e retorna-o. PRE: GQempty()==0 POS: GQfull()== 0 */ type GQfirst(void);

215 15. Implementação em C de ADTs com múltiplas instâncias " # & $ $ " $ $ * $ $ $ " ( % % % # $! " # $ * #* " " * #! " " # & " % " ' "! % $ % % % $ + ( % " $ # " # & ' % $! " # % % $ ( # $ "! " # * $ * #* " % #% # $ % % #$ $ " $ " # " $ % & " $ " " " # & ' % #% # $ % $ " ( % $ $ * #* #, /* interface */

216 typedef struct { float x, y; } point; double dist(point, point); /* código cliente */ int main() { point A, B; A.x=1.0; A.y=1.0; B.x=4.0; B.y=2.0; printf("distância: %f \n", dist(a,b)); return 0; }; /*implementação */ double dist(point p1, point p2) { }; float dx= p2.x-p1.x; float dy= p2.y-p1.y; return sqrt(dx*dx+dy*dy); ) $ " # + " # & $ " " ' " $ $ " # " # & ' " % # % " ' " $ $ % $ + " ( " # " # & ' $ # $ " & ' $ " # " " * # $ + $ % $ $ " & ' ( % $ + " " $ % $ % $ $, /* ficheiro: point.h */

217 #ifndef _POINT_ #define _POINT_ #endif typedef struct point *Point; Point POINTinit(float, float); float POINTx(Point); float POINTy(Point); double POINTdistance(Point, Point); $ % * # " & ' $ + " ( # $ " " % ' " * # $ " $ " # ' " $ % $ $ % % $ $ " # ( # $ $ " & " " * # ( % # ' % $ % " $ " # " ' % $ $ * # % " $ ( " " " $ % $ $ % " # ( " # & ' " $ $ $ ", /* ficheiro: point.c */ #include <stdio.h>

218 #include <math.h> #include "point.h" struct point { float x, y; }; Point POINTinit(float x, float y){ Point p=(point) malloc(sizeof *p); if (!p) { fprintf(stderr, "No more memory."); exit(1); } p->x=x; p->y=y; return p; }; float POINTx(Point p) { return p->x; }; float POINTy(Point p) { return p->y; }; double POINTdistance(Point p1, Point p2){ float dx= (p1->x)-(p2->x); float dy= (p1->y)-(p2->y); return sqrt(dx*dx+dy*dy); } " % # % %, #include <stdio.h> #include "point.h"

219 /* código cliente */ int main() { } Point A, B; A=POINTinit(1.0,1.0); B=POINTinit(4.0,3.0); printf("distância: %f \n", POINTdistance(A,B)); return 0; " $ " # & " % # # # * $ $ % " # ( # + malloc $ " # " & ' " # & ' $ (! " # " & ' " $ " # $ " # %, void POINTfree( Point p) { } free(p); ' # & ' $ " # " % # % " $ % " * $ # % $ (! " # & $ ", Point A=POINTinit(1.0,1.0); Point B=POINTinit(4.0,3.0); B=A; " $ $ & $ * $ % # " $ " B " & ' ( $ * # $ % # * $ B=A " B %, Point A=POINTinit(1.0,1.0);

220 Point B=POINTinit(4.0,3.0); Pointfree(B); B=A; # & ' $ + * % % " + % # " # % " % $ $ % * % & ' ( # * * ' $ % % & $ + % # " # % * $ % " $ % # $ % % $ + " # (! " # " % $ + # $ " " # " # % $! $ * " # & " * %! % % ( /* ficheiro: queue.h */ #ifndef _QUEUE_ #define _QUEUE_ #include "qtype.h" typedef struct point *Q; /* Inicializa uma fila FIFO q, com capacidade para n elementos. PRE: n > = 0 POS: (Qempty(q) == 1) && (Qfull(a) == 0) */ Q Qinit(int n); /* Liberta o espaço de memória reservado para q */ void Qfree(Q q)

221 /* Retorna 1 se a fila q está vazia; retorna 0 caso contrário. */ int Qempty(Q q); /* Retorna 1 se a fila q está cheia; retorna 0, caso contrário.*/ int Qfull(Q q); /* Retorna e retira o primeiro elemento inserido na fila q. */ /* PRE: Qempty(q)==0 */ /* POS: Qfull(q)== 0 */ qtype Qget(Q q); /* Retorna, sem retirar o elemento inserido na fila q à mais tempo. */ /* PRE: Qempty(q)==0 */ /* POS: q = old q */ qtype Qfront(Q q); #endif /* Insere um elemento t do tipo qtype, na fila q PRE: Qfull(q) == 0 POS: (Qempty(q) == 0) */ void Qput(Q q, qtype t); % & ' * # # $ " " % $ % & ' % $ & $ & ( & $ & " $ % $ % ( $ % $ $ $ " $ ' " $ $ % $ $ ( # $ $ $ %

222 $ # $ $ $ " " % $ % ( & ' $ & " $ $ $ $ $ % # " $ $ (! " # $ " $ & $ & " # $ " % * ' $ % & ( $ * & % # % $ $ ( $ & ' % # ' " $ " $ " % & ' n/d $ n d 0 ' ( % % " & ' $ % # ' " $ % ( % $ % % $ % * ' ( # " $ "! $ " # % %, $ % % = + = ' (! " # # ( ( ( $ " & ' $ % # " $ % % " " $ " $! % ", % % = = = = + = + " $ % #% # $ $,

223 % # " $ $ + $! " ' $ % & ' % $ " $ % % % " $ % #% # $ "! & ' % & ' # $ ( "! & ' $ " $ &, + = = + % % $ & %, & $ $ " # & $ & * # % #% # $ " $ " % #% # * # % " * ' $ " % #% # * # ( # $ " " " # % " $ % ( # # * $ $ & $ & $ " $ (

224 " % # " " # " % $ % %, #include <stdio.h> #include <stdlib.h> #include "queue.h" #define ORD 10 int main(int c, char**args) { int signal=1; double r, y, ratio, error; long num, den, a; double x, epsilon=0; Q nk, dk; if (c < 2) { fprintf(stderr, USAGE: f2f <float> [<epsilon>] ); exit(0); } nk = Qinit(ORD); dk = Qinit(ORD) ; Qput(nk, 1); Qput(dk, 0); x = atof(args[1]); epsilon = atof(args[2]); if (x <0) { x = -x; signal = -1; } a = (long) x; Qput(nk, a) Qput(dk, 1); r = x - a;

225 } if (r) y = 1.0 / r; else { printf( %ld\n, a*signal); Qfree(nk); Qfree(dk); return 1; } for(;;) { a = (long) y; num = Qget(nk) + a * Qfront(nk); /* n[k] = n[k-2] + a * n[k-1] */ den = Qget(dk) + a * Qfront(dk); /* d[k] = d[k-2] + a * d[k-1] */ ratio = (double) num / double (den); error = fabs(x - ratio); if (error <= epsilon) { printf( %ld/%ld \n, num*signal, den); break; } Qput(nk, num); Qput(dk, den); r = y - a; /* Aqui r!= 0; caso contrário o ciclo teria sido interrompido no break anterior. */ y = 1.0 / r; } Qfree(nk); Qfree(dk); return 0;! " # " # $ # & ' $ " ( > f2f <return>

226 1/3 ' # $ $ % * ' " $ # $ ( " $ * #! % * " $ % * ' ( ( ( $ " # & ' $ + % & ' " % " # " # % ( ( ( + % # & $ +, ( ( ( & ' " " * % & ' % $ $ ( ( ( & ' % * % ' $ " & ' $ $ $ ( ( ( & ' # " & * $ " $

227 ( ( ( & ' % # % & ' " " % & ' % # $ ( ( ( " # & $ % # $ ( ( ( % * " # & $ % # $ % " % & ' # $ ( ( + % " # & ' " * # " + % " #! " # " # % ( $ " " &, % $ # " #% & ' ( ( # % $ " # & $ $ " + % $ % $ % ( $ % % # ' # " " % (

228 16. O tipo de dados abstracto polinómio # & ' $ + % " " # " # % " % # $ $ " # % # % % % # (! " # " % # $ $ " # % % " #! % & " " # % ( # & ' $ +! % " #$ $ % % $ " # " #* " & ' " ( # % * % " #$ $ % % % $ " ( % " # + " " ( * # " % # * $ " # & ' $ + " " & ' $ " # ( + " $ * % " # $ % $ $ $, * * # % %! " (! " # $ " #, ( ) = ( ) = + +

229 $ " # #! " $ $ ( + $ " # ( ) = = ( ) = = ' ( ) + = = + ( ) = = = " " # % % $ #! " %, ( ) = ( ) = + + ( ) = + # " #% " # " $ # # $ " " $ $ $ *, + + ( ) = ( )( + ) = + + $ * % $ * #* # % $ " # " #% & ' $ " # (

230 $ $ * #* + " # " % #% # * # $ " # " $ $ % " & # % % $ & ' P(x) x # " #% & ' $ " # ( " # * " $ % $ + " # % "! % $ $ % & ' % " # ( # & $ % " + " #, %, " # ( typedef struct poly *POLY; float POLYeval(POLY, float); POLY POLYadd(POLY, POLY); POLY POLYmult(POLY, POLY); void POLYprint(POLY); void POLYfree(POLY); & % " $ % * " %, #include "poly.h" void f(poly a, POLY b, POLY c) { POLY tmp, e; tmp = POLYmult(a, b); e = POLYadd(tmp, c); POLYfree(tmp); POLYprint(e); POLYfree(e); }

231 $ % $ % % $ $ $ " # & $ % $ + " # " & ' $ # ( + % " $ # % % " $ % $ % # $ % % $ " # " # & ' $ & " % # " # ( " # & ' $ + " # $ % $ % $ " # $ $ " % $ " $ " # " % % % $ " # ( % % $ " # ' $ $ " $ % % $! " (! " # % $ " # ' $ $ % = " & % # ' $ %, $ % $, # $, % %! ", ( ) % $ % & ' $ % $ $ % * " $ $, /* ficheiro: poly1.c */ #include "poly.h" struct poly{

232 }; int degree; float *coefs; " # & ' # % #% # * # $ POLYeval(POLY p, float x) " # p " x $ ( # $ # % # % " # % #% # " $ $ $ " * # $ " & ( * & ',!!!! (((!!!! " #, = , float POLYeval(POLY p, float x) { int i; float re = p->coefs[p->degree]; for(i=(p->degree)-1; i >= 0; i--) re = re*x + p->coefs[i]; return re; }! % & ' $ & ' * $ # $ " %, +

233 /* PRE: n >=0 */ /* POS: Instância de polinómio cujo grau é n e todos os coeficientes são zero */ static POLY POLYnew(int n) { POLY re = (POLY) malloc(sizeof *re); if(!re) { fprintf(stderr, "Insuficient mem in POLY new \n"); exit(1); } re->degree = n; re->coefs = (float *) calloc(n+1, sizeof(float)); if(!re->coefs) { fprintf(stderr, "Insuficient mem in POLY new \n"); exit(1); } return re; } /* Liberta a memória usada pelo polinómio p */ void POLYfree(POLY p){ free(p->coefs); free(p); } /* Multiplicação dos polinómios p e q */ POLY POLYmult(POLY p, POLY q) { int i, j;

234 POLY re = POLYnew(p->degree + q->degree); for(i=0; i<=p->degree; i++) for(j=0; j<=q->degree; j++) re->coefs[i+j] += p->coefs[i]*q->coefs[j]; return re; }; /* Adição dos polinómios p e q. */ POLY POLYadd(POLY p, POLY q) { int i; POLY re= POLYnew(max(p->degree, q->degree)); for(i=0; i <= p->degree; i++) re -> coefs[i] = p->coefs[i]; for(i=0; i <= q->degree; i++) re -> coefs[i] += q->coefs[i]; return re; } " # & ' $ & ' POLYprint $! $ %! % % ( " # & ' $ + " # $ * " $ $ " $ & $ $ % # $ $ % % % # # * $ ( ( $ $ $ $ " # ( " # ( ) = + ( ) = + + +

235 '! " # $ % ( $ $ " # # * $! " % " # & ' $ # # $ $ # * " " $ ( " # & ' $ # " $ " % " $ % $ $ # " $ " # (! " # " # A(x) % " $ " $ % " % $ $ # % $ " # % %! " $ % # & ' "! ( $ $! " # * $ % & $ # $ $ $ " $ $ % % $! " ( # % % % # ' ' % $ $ ( " % " & * % $ '! * # # * # " * # * ' % " ( " $ " # + " # % $ & $ " * " # # $ % # # & ' % $ ( # % $ $ * #* " # # $ $ $ $ % $ $ % # $ % $ ( "type.h" type % *, /* ficheiro type.h */ typedef struct { int expo; float coef;} type;

236 % $ " # & ' poly2.c " $ % $, #include "poly.h" #include "sllist.h" #include "type.h" struct poly { int degree; /* Não é absolutamente necessário */ link head, last; }; /* PRE: n >=0 */ /* POS: Instância de polinómio */ static POLY POLYnew(int n) { POLY re = (POLY) malloc(sizeof *re); if(!re) { fprintf(stderr, "Insuficient mem in POLY new \n"); exit(1); } re->degree = n; re->head=null; re->last=null; return re; } /* PRE:!p */ void POLYfree(POLY p){ lstremove(&(p->head)); free(p); }

237 /* PRE: p!= NULL */ float POLYeval(POLY p, float x) { } int i; link l = p->head; float re = l->item.coef; l = l -> next; for(i=(p->degree)-1; i >= 0; i--) return re; if(l->item.expo == i) { } else re *= x; re = re*x + l->item.coef; l = l -> next; $ " # " $ " # $ $ % $ %, & " % " # " % $ $ $ " # ( " % % $ " # % & $ " # ' % & $ " % * # ( ( ) = ( ) = + ( ) = ( ) + ( )

238 )! " % % * " # # $ % $ % % ' # ( * & " "! " # (! " #, ) % # $ " # *! " $ % # $ p " # ' " $ % % % # $ " # # $ q p * & " "! $ p ( % # $ q ' # $ (! " #,

239 $ " # $ " $ ' % % $ " # # $ ( " # $ " % $ " $ " # $ %,,!p &&!q POLY POLYadd(POLY p, POLY q) { float sum; POLY re; link ph = p->head; link qh = q->head; re = POLYnew(max(p->degree, q->degree)); while (ph && qh) { if(ph->item.expo == qh->item.expo) { sum = ph->item.coef + qh->item.coef; if(sum) POLYappend(re, ph->item.expo, sum); ph = ph -> next; qh = qh -> next; } else if(ph->item.expo < qh->item.expo) { POLYappend(re, qh->item.expo, qh->item.coef); qh = qh -> next; } else { POLYappend(re, ph->item.expo, ph->item.coef); ph = ph -> next; } } for(; ph; ph=ph->next) POLYappend(re, ph->item.expo, ph->item.coef); for(; qh; qh=qh->next) POLYappend(re, qh->item.expo, qh->item.coef); return re; }

240 /* Acrescenta um novo termo à representação do polinómio p; */ /* PRE: (c!=0) && (p!= NULL ) && ( p->last==null ( p->last!=null && e < p->last->item.expo ))*/ static void POLYappend(POLY p, int e, float c) { type t; link nn; t.coef = c; t.expo = e; nn = lstnnode(t); if(p->head==null) p->head = nn; else p->last->next = nn; p->last = nn; } " # & ' $ & $! $ %! % % ( ( $ + " # " # & ' $ # # $ ( " % " #, (a) A(x)=1 (b) B(x)=1-x 2 (c) C(x)=x 20 (d) D(x)=x 16 +8x 2 +1 (e) A(x)+B(x) (f) A(x)+B(x)+C(x)+D(x)

241 ( $ + " # " # & ' $ # # $ ( " # &, % #% # * # $ " # " float POLYeval(POLY p, float x) "! ( ' % " & $ % ( # $ % # $ " # POLY POLYfromUser(void) " $ " " # #$ ( % " # $ " # " ( void POLYshow(POLY p) $ & "! " # $ " # ( ( $ $ $ " # & ' $ # # $ " * ' $ & ' POLY POLYmult(POLY,POLY) # $ $ # " #% & ' $ " # ( $ $ % " #! $ $ " % $ & ' $ * #* $

242 17. O ADT matriz esparsa $ $ $ % " #% & ( * $ ", % " $ " & ' # $ %, int mi[linhas][colunas]; * $ % $ " %, int **ppi; ppi=malloc2d(linhas, Colunas); % % # $ # ppi[i][j] ( i % # j % * $ mi[i][j] * % " $ $ $! $ " # # ' ' # $ # " ' $ $ ( " $ % " ( $ $ $ % % " " " $ " $ & $ $ % $ * # $ (

243 "! % & $ + " * # $ " # & ' " % #* " # ( $ % $ % * $ " # $ & " $ % $ + " ( $ $ # " " " # & ' " # " # % ( /* ficheiro matrix.h */ typedef struct matrix* M; /* Liberta o espaço ocupado pela matriz */ void Mfree(M); /* Calcula a transposta da matriz */ M Mtranspose(M); /* Calcula a soma das matrizes a e b */ M Madd(M a, M b); /* Calcula a multiplicação das matrizes a e b. */ M Mmult(M a, M b); $ # $ " $ % % $ " " # " " $ " $ " $ " # ( <linha, coluna, valor> (

244 ! " # " ( (! $ #,! $ #, " $ " $ " # " # " # & ' $ $ + " " $ $ $ ", /* ficheiro matrix1.c */ #include "matrix.h" #include "type.h" typedef struct{ int row, col; type value; } triple; struct matrix { int norows, nocols, actsize; triple *triples; };

245 /* inicializa uma matriz PRE: r >0 && c >0 && s > 0 */ static M Minit(int r, int c, int s) { M m = (M) malloc (sizeof *m); if (!m) { fprintf(stderr, "Minit exception: Not enough mem. for another matrix.\n"); exit(1); } m -> triples = (triple *) malloc(s*sizeof(triple)); if (! m->triples) { fprintf(stderr, "Minit exception: Not enough mem. for triples. \n"); exit(1); } m->actsize = s; m->norows = r; m->nocols = c; return m; } void Mfree(M m) { free(m->triples); free(m); }! " # $% A nxm A & mxn' ( " ) # T at[i][j] a[j][i] a[j][i] " "* j +"! i A', - ". 1 / : ; 0 = 1 / :

246 !!"! ) + +" # + $! A! ". m == ' +"! A for(j=0; j<n; j++) n == ' "* A for(i=0; i<m; i++) at[i][j]=a[j][i];!!" )! # + $! )! + "+. /* Versão 1: Sem preocupações de ordenação dos elementos da matriz transposta */ /* PRE: m->actsize > 0 */ Mtranspose(M m) { }; int i; M t = Minit(m->nocols, m->norows, m->actsize); for (i=0; i < m->actsize; i++) { }; return t; " - ". t -> triples[i].row = m -> triples[i].col; t -> triples[i].col = m -> triples[i].row; t -> triples[i].value = m -> triples[i].value; =

247 # # # # # # # # # # ) # # # # # # # # # # "* +"! # # # # # # # # # # + ) " + + "* + "* + + +"! ) +" " ) "$! &! ' " # + ', )! +"+!"! + + ) ) +"+ " $" ' $!

248 + $!.! "* ) +"! $"# + + "! - + +"! $" '!% +$! elcol' - ". elcol[0]=2 elcol[1]=1 elcol[2]=0 elcol[3]=2 "! +! " "* # "* "* ' " "* # t # + t->triples[0] # " "* # + elcol[0] # t->triples[2]' $! ++# " "* + elcol[0]+elcol[1] # t->triples[3]' & $! + spos' ( + $! "! )! + + Mtranspose. /* Versão 2: A matriz transposta retornada pela função tem os seus elementos ordenados por valores crescentes de linhas e dentro das linhas por valores crescentes de colunas */ /* PRE: m->actsize > 0 */ M Mtranspose(M m) { int i, j; M t = Minit(m->nocols, m->norows, m->actsize); int *elscol = callocd (m->nocols, sizeof(int));

249 int *spos = callocd (m->nocols, sizeof(int)); for(i=0; i < m->actsize; i++) elscol[m->triples[i].col]++; for (i=1; i < m->nocols; i++) spos[i] = spos[i-1] + elscol[i-1]; }; for (i=0; i < m->actsize; i++) { j = spos[ m->triples[i].col]++; t -> triples[j].row = m -> triples[i].col; t -> triples[j].col = m -> triples[i].row; t -> triples[j].value = m -> triples[i].value; }; free(elscol); free(spos); return t;! )! )!! " "+ ) callocd '! )!" # "! calloc <stdlib> +" ' /* Calcula a matriz a+b */ /* PRE: (a->nocols == b->nocols) && (b->norows == b->norows) */ M Madd(M a, M b) { int i=0, j=0, n=0, sum=0; int maxsize = max(a->actsize+ b->actsize, a->norows*a->nocols); M c = Minit(a->norows, a->nocols, maxsize); /* Neste momento, podemos dizer que no max, a matriz c = a+b, tera' um no de elementos igual a max( a->actsize + b->actsize, a->linhas*a->colunas); Posteriormente actualizaremos o actsize de c */ while( (i < a->actsize) && (j < b->actsize)) { if (a->triples[i].row < b->triples[j].row) c->triples[n++] = a->triples[i++]; else if (a->triples[i].row > b->triples[j].row)

250 } c->triples[n++] = b->triples[j++]; else { /* a->triple[i].row == b->triples[j].row */ if (a->triples[i].col < b->triples[j].col) c->triples[n++] = a->triples[i++]; else if (a->triples[i].col > b->triples[j].col) c->triples[n++] = b->triples[j++]; else { sum = a->triples[i].value + b->triples[j].value; if (sum) { c->triples[n].value = sum; c->triples[n].row = a->triples[i].row; c->triples[n].col = a->triples[i].col; n++; } i++; j++; } } } for( ; i < a->actsize; i++) c->triples[n++] = a->triples[i]; for( ; j < b->actsize; j++) c->triples[n++] = b->triples[j]; c->actsize = n; return c; - "! " ' " $!.

251 "*! " #! " " ) +!! "! + $!! " + "*# +"! " " + ' ) " ) &! )!"! &! " + " ', " #! $!! " &!! # )! '! " ) '

252 " - " + " #!"!!!!!+ + " ' - ".! +!! $! ) " )!" #! +! +! "! +" + '

253 $! + " ) + ) + + s0, s1, s2, s3' # +!"+! +" )!! ' ( " + - "* +"! ' ( " s0, s1, s2 e s3! " ++!" " "$ ', " # + " + " ++!" '! +! "*!! +! +"! ' ( " "* i " +"! i' )#! $!! + l "*# c +"! n " )!" + max(l,c)+n '! " #! " $! + $! )! +. (! $! $+., next - " "* rigth +"! i down i'!!#! $! + $! )! +.

254 (. "* " )!" row % +"! " )!" col " " )!" " % value % rigth! - "* row % down! - +"! col' ( down right! " ' " + +!" +! +!! + '!! + # +! ', "! #!!!"! )!!) union)! +"! ++ + ' # " # + +" +* matrix2.c # " $! )# $!. /* ficheiro matrix2.c */ #include "matrix.h" #include "type.h" typedef struct node* link; typedef struct{

255 } triple; int row, col; type value; struct node{ link down, right; union { triple data; /* Para os nós de dados */ link next; /* Para os nós sentinela */ } u; }; struct matrix { }; int norows, nocols; int actsize; link head; $! "! ) #!! MfromUser!" % + +!!! ' )!!"! "!!!! & '! ) +!!" "* +"! " # " $! )!" ' "! & # ) + " " + " ++!"! "$ '

256 ! ) "! + - " $!!! +! '! ) +!# " " "* "* '! + " )!" " +! $! ' ( "$ - ' $! - %!! + $! " "* # +"! '

257 +! "$ &! - # + #,! $! "+" ) " " + "* + +"! ) $! " ' ' -$ $! " & + $!. typedef struct { link next; link lastdown; link lastright; } links ; struct node{ link down, right; union { triple data;

258 links connection; } u; }; ( + $! ) MfromUser $!.! + +! "$ & M MfromUser(void) { /* */ m = Minit(l,c); row = m->head; for(i=0; i < l; i ++) { col = m->head; for(j=0; j< c; j++) { } printf("(%d, %d): ", i, j); scanf(printfstring, &t); if(t) { /*... */ pn = Mnnode(); pn->u.data.value = t; pn->u.data.row = i; pn->u.data.col = j; row->u.connection.lastright -> right = pn; row->u.connection.lastright = pn; col->u.connection.lastdown -> down = pn; col->u.connection.lastdown = pn; } +* "* #!! - "! $! '

259 ( + $ " ' " % # #! + +"!! "* +*% " ++!" " "* ' (!+ +"! ' Mprint $! " ) "! )! Mprint " )!"! ' ( " ) "* "* ' void Mprint(M m) { link row = m ->head; link i = row; do { i = i->right; if (i == row) { i=i->u.connection.next; row=i; } else{

260 printf("(%d, %d ): ", i->u.data.row, i->u.data.col); printf(printfstring, i->u.data.value); printf("\n"); } } while( i!= m->head ); };! & ", " # +"!! ) ' ' $!! + )!! +! " ' + + $! " '!!!+ &! ' '! " ) $"!!! + " - $" +" ' +" $!! &.

261 '! )! +"!! +" '! )!!! + $! '! )! " $! $! '! )! +) $! "! ) "! ) + ' ' +! $ +"!!"! & +" + +). + + ' " )! " ' " $!! &.!!" "! M MfromUser(void) %! + '! +) " void Mprint(M m) + '! " " " type Mvalue(int i,int j) + # ' ' +! ) # + #!"! M Mtranspose (M m) +!-"!" ) ' ' "! "* +"+!"! "+# + ' ) - "* +"+!" "* +"! ' (! $ + $! +.

262 load <nome $ de ficheiro>! "* +"+!" $ +* ++ ' save <nome de ficheiro> +* ++ "* +"+!" - ' <l> "+ <c> <v> " # "* +"! "* +"+!" <v> <l> <c> ' l <i> + "!" - "* <i> c <j> + "!" - +"! <j> clear + +!" "! "* + quit - +! ) $! - +!! + $ "* +"+!" '

263 18. Primeiras noções sobre árvores )! + )! *! "! " ' " - "!" "! ++ "! $ " $+! # # # + '! ' ( +!! + ) " + +! "! $! ' $ "# $+# + $$!! )# ) '! + )!!$!! " +!.! # # + " +# + ' +! # +* ) $ +!. $! % +* +!! )#! # ' +! ) + "$ $ ) +* ' - & "$ +#! $ " - &! "$!$ "# ) +! ', - "# - ) "

264 +"!!""+ ) + + " ', " #! + + "$ ', - "# - +! )!+ $! '!! -"+! + ++ ) + ) ' +!" "! "! & ) '! + +!" $! # " #! $! +" + ) )! + +! "$ ' "! ++! # #! +! ) +! +! ) +#! +! ' ( +! $! ) '! #! + *! " + +! ) "$ + ' ! + *!"! ' +! - " # # # # # # # # ' - '! $! $!. "

265 + '! % + ' +!! +"*! '! + #!"!!! % + " - " '!" $ +! + + '! ++!" #!" +! "#! +!! ++!" ' - ". # -+ # -+! + #! '! n - i! i + n i + * n '

266 ( + - n # ) +* "*!!+ n' "* n ) ) ' ( "*! +* $! ' ( $!! " - $! ' "* % "*! " + "! "* ) +* ) " '! +!+ + ) '! +!+ ) ) $+!!+ *! + "! " ' (! $+! ) *!" "*! #!" $! ' +!!!+ # ) # )! M'! - # "* ' $! $!! ' ' #! - ) ++!" + '

267 ! #! +. - # # "*# + -+ "* '! "* + ) # +* %"* "*! "* ' %!! "*!! "* ' #!! "* ) - '! #! "* +!! M! "* ) - ' (! +!! -"+ "$ +!!! #! + % '! + # "! & +! ',! "#!! & +! +!!" '! -!! ) +!. "$! #! ) +*! %!! % '

268 $! ++! " ) ' - " + ) # +"! " &!! ' ) + - ' " " )!! + " # +! ) $!! +"! " +" + ) # "*! "* # + - ' ) - & ', ) + " )!! + " '

269 % +*!! +* # -+!" " ' + "! +*! " " +! - " ' "! "! + "$ &! + + '! ) " ', - "# $! ) +* # "$ ) + " ' +! ) # + - " ' " &! + " +!!! + "$ &! links)' (!" links + - '

270 +! ) ++!".! " ). ( + + $!"! + $!!!. typedef struct node *link; struct node { }; type item; link left, right; )! " ) + &! ', "$! ! + link!! node #!! '

271 ) +! M.! - M!! "$!! +! ) " M'! + +* % " ' "! +!! '! +* "$!! +! ' ) +!!!"! "*! M + M "* '! +!!"! # links!! " "$! $! links "* ' $ #! + - " " + $!.

272 ) " ) +"! + + "$ &! '! " "$!!+ #!! -! ) ',!!! # +!!! # "* link n! $"#! link! n ) # $" ',! $! - # " # $! ' ) "*%! % )! % % ) " ) + ) '

273 +! )! "$! +! ) ' +! +* % " ) ',! )!! # #!! ) ' ' $! )! '! "*# - ' " ) + " "$ ' +!! ' "! ) "*! ) '

274 ' *! " $! +! +# % # % # % # % % #! + "! '

275 19. Árvores binárias!! &!" ) # + "! & " # # "! & #! +! ' + "!! +"+% $!.!! #! +! + ' " " "$! ". +! $!! link # +. void lsttraverse(link l, void (*visit) (link)) { if (!l) return; visit(l); lsttraverse(l -> next, visit); } visit!! )! + ' +! ) lsttraverse + # + +! ' " $! +! link ' + +! + '

276 , " # "! # " # "!. ' '! %!! % # ' # +! - ) $"%- +.preorder traversal! %! #! % # ' ' # +! - ' inorder traversal '! %! # ' ' # +!! - postorder traversal + ) " # + $!. void ttraverse( link l, void (*visit) (link)) { if (!l) return; visit(l); ttraverse(t->left, visit); visit(l); ttraverse(t->right, visit); visit(l); }; # +. typedef struct node *link; struct node { type item; link left, right;

277 }; ( +! -! - ) "* $ visit(l) - & + visit(l) ' $!" # +! % infixo + - ) $ ' +!! - %. + +!! + +*! & $!. prefixo ttraverse(r) visit(r) ttraverse(a) visit(a) ttraverse(c) visit(c) ttraverse(e) visit(e) ttraverse(null) ttraverse(null) ttraverse(f)

Estruturas de Dados. Alguns dados não costumam ser tão simples assim... Podem ser compostos por vários dados distintos

Estruturas de Dados. Alguns dados não costumam ser tão simples assim... Podem ser compostos por vários dados distintos Estruturas de Dados Alguns dados não costumam ser tão simples assim... Podem ser compostos por vários dados distintos Estruturas de Dados Programação de Computadores 1 de 26 Tipos Estruturados de Dados

Leia mais

Programação Engenharia Informática (11543) 1º ano, 1º semestre Tecnologias e Sistemas de Informação (6619) 1º ano, 1º semestre

Programação Engenharia Informática (11543) 1º ano, 1º semestre Tecnologias e Sistemas de Informação (6619) 1º ano, 1º semestre Programação Engenharia Informática (11543) 1º ano, 1º semestre Tecnologias e Sistemas de Informação (6619) 1º ano, 1º semestre Cap. 02 Fundamentos de Linguagens Sumário : Linguagem, alfabeto e gramática

Leia mais

Tipo de Dados em Linguagem C

Tipo de Dados em Linguagem C Tipo de Dados em Linguagem C Principais tipos de dados em C int : tipo de dados inteiros (exemplo: 1, -3, 100, -9, 18, etc.) float : tipo de dados reais (exemplo: 1.33, 3.14, 2.00, -9.0, 1.8, etc.) Ocupa

Leia mais

Fundamentos de Programação

Fundamentos de Programação Fundamentos de Programação CP41F Conversão de tipos. Alocação dinâmica de memória. Recursão. Aula 16 Prof. Daniel Cavalcanti Jeronymo Universidade Tecnológica Federal do Paraná (UTFPR) Engenharia de Computação

Leia mais

Curso C: Funções e Macros

Curso C: Funções e Macros Universidade de Brasília Departamento de Ciência da Computação Curso C: Funções e Macros Prof. Ricardo Pezzuol Jacobi rjacobi@cic.unb.br Funções Fun es s o blocos de c digo que podem ser nomeados e chamados

Leia mais

!!" "!#! " $ %"&!!$$# &! "! $$ & $ '!$# $' & &# & #$ & &' &$$ $' ' (" ' &!&& & ' & " $' $$ " $' $ "# )! * && ' $ " &+ $! "+ $$ $$ $! ' "$# $$ &#, -. /0 -,,.0 10, 02, 3,3,. /0-3,2 1/ - 3 3 3 / 00//, - /

Leia mais

Programação Estruturada I

Programação Estruturada I Programação Estruturada I Introdução a Linguagem C Prof. Thiago Caproni Tavares 1 Prof. Mateus dos Santos 2 1 thiago.tavares@ifsuldeminas.edu.br 2 mateus.santos@ifsuldeminas.edu.br Última Atualização:

Leia mais

Tabela ASCII de caracteres de controle

Tabela ASCII de caracteres de controle Caracteres Estruturas de Dados Aula 6: Cadeias de Caracteres 31/03/2010 Caracteres são representados internamente por códigos numéricos Tipo char (inteiro pequeno ) 1 byte (8 bits) 256 caracteres possíveis

Leia mais

Linguagem de Programação C

Linguagem de Programação C ICMC USP Linguagem de Programação C Aula: Funções em C Prof Alneu de Andrade Lopes MODULARIZAÇÃO Um problema complexo é melhor abordado se for dividido primeiramente em vários subproblemas MODULARIZAÇÃO

Leia mais

Algoritmos e Programação

Algoritmos e Programação Universidade Federal do Vale do São Francisco Curso de Engenharia da Produção / Elétrica Algoritmos e Programação Parte 05 Prof. Jorge Cavalcanti jorge.cavalcanti@univasf.edu.br www.univasf.edu.br/~jorge.cavalcanti

Leia mais

Introdução a Programação. Ponteiros e Strings, Alocação Dinâmica

Introdução a Programação. Ponteiros e Strings, Alocação Dinâmica Introdução a Programação Ponteiros e Strings, Alocação Dinâmica Tópicos da Aula Hoje aprenderemos a relação entre ponteiros e strings Ponteiros para strings X Vetores de Caracteres Vetores de ponteiros

Leia mais

INF 1007 Programação II

INF 1007 Programação II INF 1007 Programação II Aula 08 Busca em Vetor Edirlei Soares de Lima Busca em Vetor Problema: Entrada: vetor v com n elementos; elemento d a procurar; Saída: m se o elemento procurado

Leia mais

Mar 13, 2009 Roteiro Entrada & Saída Contêineres Algoritmos Exemplos Leitura simples #include // cin, cout, endl int a; float b; cin >> a >> b; if (cin) cout

Leia mais

INSTITUTO FEDERAL DE EDUCAÇÃO, CIÊNCIA E TECNOLOGIA RIO GRANDE DO NORTE

INSTITUTO FEDERAL DE EDUCAÇÃO, CIÊNCIA E TECNOLOGIA RIO GRANDE DO NORTE INSTITUTO FEDERAL DE EDUCAÇÃO, CIÊNCIA E TECNOLOGIA RIO GRANDE DO NORTE Algoritmos ANSI C - Gerenciamento de Memória Copyright 2014 IFRN Agenda Introdução Alocação dinâmica Funções malloc free calloc realloc

Leia mais

Variáveis e Comandos de Atribuição

Variáveis e Comandos de Atribuição BCC 201 - Introdução à Programação Variáveis e Comandos de Atribuição Guillermo Cámara-Chávez UFOP 1/47 Estrutura Básica de um programa C I < d i r e t i v a s do pré p r o c e s s a d o r > < d e c l

Leia mais

12345678797255445677655672542776742526 7!"#7# "$ %7& 7!"#7' "($ % )"(*+77"& " 7 ""$ 7!"#7# "$ %7.!,& 7!"#7' "($ % " "(*+7+7,- "& 1/7,77"07!"77",7%1223&07"," 77',7%1224& 123456787973553676656426747376253743733653762

Leia mais

Enunciados de exercícios seleccionados de testes e exames P2 / EDa

Enunciados de exercícios seleccionados de testes e exames P2 / EDa Enunciados de exercícios seleccionados de testes e exames P2 / EDa 1. Qual o resultado apresentado pelo seguinte troço de código. Justifique. double d[] = { 5.4, 3.2, 1.0 ; double *pd = d[1]; ++pd; printf(

Leia mais

Programando em C++ Histórico da Linguagem C

Programando em C++ Histórico da Linguagem C Programando em C++ Joaquim Quinteiro Uchôa joukim@comp.ufla.br DCC-UFLA, 2002 Programando em C++ p.1/38 Histórico da Linguagem C Linguagem C: 1972 - Laboratório Bells, por Dennis Ritchie, a partir da linguagem

Leia mais

Estrutura de Dados. Prof. Gustavo Willam Pereira. Créditos: Profa. Juliana Pinheiro Campos

Estrutura de Dados. Prof. Gustavo Willam Pereira. Créditos: Profa. Juliana Pinheiro Campos Estrutura de Dados Prof. Gustavo Willam Pereira Créditos: Profa. Juliana Pinheiro Campos ESTRUTURAS DE DADOS Ementa Introdução à Linguagem C. Recursividade. Alocação dinâmica de memória. Conceito de tipos

Leia mais

Ponteiros e Tabelas. K&R: Capitulo 5 IAED, 2012/2013

Ponteiros e Tabelas. K&R: Capitulo 5 IAED, 2012/2013 Ponteiros e Tabelas K&R: Capitulo 5 Ponteiros e Tabelas Ponteiros e endereços Ponteiros e argumentos de funções Ponteiros e tabelas Alocação dinâmica de memória Aritmética de ponteiros Tabelas de ponteiros

Leia mais

Ponteiros e Tabelas. K&R: Capitulo 5 IAED, 2012/2013

Ponteiros e Tabelas. K&R: Capitulo 5 IAED, 2012/2013 Ponteiros e Tabelas K&R: Capitulo 5 Ponteiros e Tabelas Ponteiros e endereços Ponteiros e argumentos de funções Ponteiros e tabelas Alocação dinâmica de memória Aritmética de ponteiros Tabelas de ponteiros

Leia mais

Linguagem C. Programação Estruturada. Fundamentos da Linguagem. Prof. Luis Nícolas de Amorim Trigo nicolas.trigo@ifsertao-pe.edu.

Linguagem C. Programação Estruturada. Fundamentos da Linguagem. Prof. Luis Nícolas de Amorim Trigo nicolas.trigo@ifsertao-pe.edu. Programação Estruturada Linguagem C Fundamentos da Linguagem Prof. Luis Nícolas de Amorim Trigo nicolas.trigo@ifsertao-pe.edu.br Sumário Estrutura Básica Bibliotecas Básicas Tipos de Dados Básicos Variáveis/Declaração

Leia mais

Linguagem C Tipos de Dados. void; escalares; sizeof Vectores; strings em C Estruturas Introdução ao pré-processador

Linguagem C Tipos de Dados. void; escalares; sizeof Vectores; strings em C Estruturas Introdução ao pré-processador Linguagem C Tipos de Dados void; escalares; sizeof Vectores; strings em C Estruturas Introdução ao pré-processador Funções void void pode ser usado em lugar de um tipo, para indicar a ausência de valor

Leia mais

UNIVERSIDADE FEDERAL DO ESPÍRITO SANTO CENTRO UNIVERSITÁRIO NORTE DO ESPÍRITO SANTO

UNIVERSIDADE FEDERAL DO ESPÍRITO SANTO CENTRO UNIVERSITÁRIO NORTE DO ESPÍRITO SANTO Curso: Engenharia de Computação e Ciência da Computação Data: 10/09/2013 Disciplina: Programação Estruturada Valor: 3,0 pontos Professor: Henrique Monteiro Cristovão Nota: Aluno: Prova resolvida 4ª Prova

Leia mais

Básico: estrutura de programa, sintaxe Interface com linha de comando

Básico: estrutura de programa, sintaxe Interface com linha de comando Programação em C Sintaxe Básico: estrutura de programa, sintaxe Interface com linha de comando Preprocessamento e compilação Makefiles Ponteiros e estruturas Bibliotecas, ficheiros include e funções Referências

Leia mais

Tipos de Dados, Tipos Abstratos de Dados Estruturas de Dados

Tipos de Dados, Tipos Abstratos de Dados Estruturas de Dados Tipos de Dados, Tipos Abstratos de Dados Estruturas de Dados Tipo de dados, tipo abstrato de dados, estruturas de dados Termos parecidos, mas com significados diferentes Tipo de dado Em linguagens de programação

Leia mais

INF 1620 P1-10/04/02 Questão 1 Nome:

INF 1620 P1-10/04/02 Questão 1 Nome: INF 1620 P1-10/04/02 Questão 1 Considere uma disciplina que adota o seguinte critério de aprovação: os alunos fazem duas provas (P1 e P2) iniciais; se a média nessas duas provas for maior ou igual a 5.0,

Leia mais

Linguagem C: variáveis, operadores, entrada/saída. Prof. Críston Algoritmos e Programação

Linguagem C: variáveis, operadores, entrada/saída. Prof. Críston Algoritmos e Programação Linguagem C: variáveis, operadores, entrada/saída Prof. Críston Algoritmos e Programação Linguagem C Linguagem de uso geral (qualquer tipo de aplicação) Uma das linguagens mais utilizadas Foi utilizada

Leia mais

INF 1620 P1-04/10/03 Questão 1 Nome:

INF 1620 P1-04/10/03 Questão 1 Nome: INF 1620 P1-04/10/03 Questão 1 a) Implemente uma função para calcular as raízes de uma equação do segundo grau do tipo ax 2 +bx+c=0. O protótipo dessa função deve ser: void raizes (float a, float b, float

Leia mais

LINGUAGEM C. Estrutura básica de um programa

LINGUAGEM C. Estrutura básica de um programa LINGUAGEM C Estrutura básica de um programa Um programa em linguagem C é constituído por uma sequência de funções (módulos) que em conjunto irão permitir resolver o problema proposto. Estas funções contêm

Leia mais

Algoritmos Eficientes de Ordenação

Algoritmos Eficientes de Ordenação AED 2002/2003 p.1/22 Algoritmos Eficientes de Ordenação Quick Sort Merge Sort Heap Sort Utilizar informação das chaves: Counting Sort Radix Sort AED 2002/2003 p.2/22 Quick Sort int partition(item a[],

Leia mais

Introdução à Programação

Introdução à Programação Aula Teórica 5: ciclos e funções Getchar e putchar Escrever e ler caracteres A função getchar da biblioteca stdio.h permite de receber exatamente um (1) carácter da o "teclado"ou stdin Definição: int getchar(void)

Leia mais

Linguagem de Programação I

Linguagem de Programação I Linguagem de Programação I Curso de Sistemas de Informação Karla Donato Fook karladf@ifma.edu.br DESU / DAI 2016 Linguagem de Programação C 2 1 Linguagem de Programação C Os programas em C consistem em

Leia mais

ITENS FUNDAMENTAIS. Profª Angélica da Silva Nunes

ITENS FUNDAMENTAIS. Profª Angélica da Silva Nunes ITENS FUNDAMENTAIS Profª Angélica da Silva Nunes CONCEITOS BÁSICOS Hardware - é a parte física do computador, tais como: teclado, monitor de vídeo, etc. Software - são os programas e aplicativos que permitem

Leia mais

2 a LISTA DE EXERCÍCIOS DE LINGUAGEM C

2 a LISTA DE EXERCÍCIOS DE LINGUAGEM C 2 a LISTA DE EXERCÍCIOS DE LINGUAGEM C 1. Fazer um programa ler um vetor de inteiros e positivos e imprimir quantas vezes aparece o número 1, 3 e 4, nesta ordem. O vetor terá no máximo 100 posições. Sair

Leia mais

Programação de Computadores II Lista de Exercícios 03

Programação de Computadores II Lista de Exercícios 03 Programação de Computadores II Lista de Exercícios 03 Karina Mochetti 1. Qual a diferença ao declaramos uma string como char *str ou como char str[100]. Explique em detalhes. 2. Ao passar uma variável

Leia mais

Curso de C. Memória Dinâmica 17/05/2010 16:33 1

Curso de C. Memória Dinâmica 17/05/2010 16:33 1 Curso de C Memória Dinâmica 17/05/2010 16:33 1 Memória Dinâmica Curso C - IC/UNICAMP Roteiro: Memória dinâmica Vetores dinâmicos Listas ligadas 17/05/2010 16:33 @Arnaldo V. Moura, Daniel F. Ferber 2 Conceitos:

Leia mais

Computadores Digitais 2. Prof. Rodrigo de Souza Couto

Computadores Digitais 2. Prof. Rodrigo de Souza Couto Computadores Digitais 2 Linguagens de Programação DEL-Poli/UFRJ Prof. Miguel Campista Aula de Hoje Cadeias de caracteres (strings) Caracteres Definição e manipulação de strings Vetor de strings Parâmetros

Leia mais

PIP/CA - Programa Interdisciplinar de Pós-Graduação em Computação Aplicada da UNISINOS ALGORITMOS & ESTRUTURAS DE DADOS

PIP/CA - Programa Interdisciplinar de Pós-Graduação em Computação Aplicada da UNISINOS ALGORITMOS & ESTRUTURAS DE DADOS PIP/CA - Programa Interdisciplinar de Pós-Graduação em Computação Aplicada da UNISINOS Disciplina de Nivelamento - 2000/1: ALGORITMOS & ESTRUTURAS DE DADOS Professor Responsável: Prof. Fernando Santos

Leia mais

Estruturas de dados compostas

Estruturas de dados compostas 1 Estruturas de dados compostas Vimos estruturas lineares simples : Vetores, listas ligadas, strings Consideramos agora estruturas compostas : Vetores de vetores (em particular, matrizes), vetores de listas

Leia mais

1/34 GESTÃO DINÂMICA DE MEMÓRIA

1/34 GESTÃO DINÂMICA DE MEMÓRIA 1/34 GESTÃO DINÂMICA DE MEMÓRIA Memória Estática 2/34 Memória Estática Exemplo #include main() { int V[300], N; do{ printf ( N =? ); scanf ( %d, &N); while ((N < 0) (N > 300); for (i = 0; i

Leia mais

13. ALOCAÇÃO DINÂMICA DE MEMÓRIA

13. ALOCAÇÃO DINÂMICA DE MEMÓRIA 787878787878787878787878787878787878787878787878787878 13. ALOCAÇÃO DINÂMICA DE MEMÓRIA Sempre é necessário declarar o número de elementos do array. Mas e se ele for desconhecido? E se ele variar? Pode

Leia mais

Ponteiros - Parte I. Ponteiros, Ponteiros e Vetores, Algoritmo Bubble Sort, Alocação Dinâmica de Memória

Ponteiros - Parte I. Ponteiros, Ponteiros e Vetores, Algoritmo Bubble Sort, Alocação Dinâmica de Memória Ponteiros - Parte I Ponteiros, Ponteiros e Vetores, Algoritmo Bubble Sort, Alocação Dinâmica de Memória Ponteiros Um ponteiro é uma variável que contém um endereço de memória. Esse endereço é normalmente

Leia mais

Ponteiros e Tabelas. K&R: Capítulo 5

Ponteiros e Tabelas. K&R: Capítulo 5 Ponteiros e Tabelas K&R: Capítulo 5 Ponteiros e Tabelas Ponteiros e endereços Ponteiros e argumentos de funções Ponteiros e tabelas Alocação dinâmica de memória Aritmética de ponteiros Tabelas de ponteiros

Leia mais

Linguagem C. TGSI Lógica de Programação / Linguagem C Prof. Marcos Roberto

Linguagem C. TGSI Lógica de Programação / Linguagem C Prof. Marcos Roberto Linguagem C O C nasceu na década de 70. Seu inventor, Dennis Ritchie, implementou-o pela primeira vez usando um DEC PDP-11 rodando o sistema operacional UNIX. O C é derivado de uma outra linguagem: o B,

Leia mais

Métodos Computacionais. Tipos Estruturados

Métodos Computacionais. Tipos Estruturados Métodos Computacionais Tipos Estruturados Tipos Estruturados C oferece tipos primitivos que servem para representar valores simples Reais (float, double), inteiros (int), caracter (char) C oferece também

Leia mais

Listas (Parte 2) Túlio Toffolo tulio@toffolo.com.br www.toffolo.com.br. BCC202 Aula 10 Algoritmos e Estruturas de Dados I

Listas (Parte 2) Túlio Toffolo tulio@toffolo.com.br www.toffolo.com.br. BCC202 Aula 10 Algoritmos e Estruturas de Dados I Listas (Parte 2) Túlio Toffolo tulio@toffolo.com.br www.toffolo.com.br BCC202 Aula 10 Algoritmos e Estruturas de Dados I Listas Encadeadas Características: Tamanho da lista não é pré-definido Cada elemento

Leia mais

Linguagem C. Ponteiros. Alex Vidigal Bastos.

Linguagem C. Ponteiros. Alex Vidigal Bastos. Linguagem C Ponteiros Alex Vidigal Bastos alexvbh@gmail.com Ponteiros Ponteiros são variáveis que contém endereços. Estas variáveis apontam para algum determinado endereço da memória. Em geral, o ponteiro

Leia mais

Programação II. Vetores e Alocação Dinâmica. Bruno Feijó Dept. de Informática, PUC-Rio

Programação II. Vetores e Alocação Dinâmica. Bruno Feijó Dept. de Informática, PUC-Rio Programação II Vetores e Alocação Dinâmica Bruno Feijó Dept. de Informática, PUC-Rio Vetores (arrays) Vetor: estrutura de dados definindo um conjunto enumerável Exemplo: v = vetor de inteiros com 10 elementos

Leia mais

Introdução a Computação

Introdução a Computação Introdução a Computação Aula 02 Introdução a Linguagem C Edirlei Soares de Lima Lógica de Programação Lógica de Programação é a técnica de criar sequências lógicas de ações para

Leia mais

INF 1007 Programação II

INF 1007 Programação II INF 1007 Programação II Aula 05 Cadeias de Caracteres Edirlei Soares de Lima Caracteres Caracteres são representados através de códigos numéricos. Tabela de códigos: Define correspondência

Leia mais

Alguns Exercícios de Programação de em Linguagem C

Alguns Exercícios de Programação de em Linguagem C Alguns Exercícios de Programação de em Linguagem C Nelma Moreira Departamento de Ciência de Computadores Faculdade de Ciências, Universidade do Porto email: nam@ncc.up.pt 1997 1 Execução de algumas instruções

Leia mais

Computação 2. Aula Profª. Fabiany Listas Duplamente Encadeadas

Computação 2. Aula Profª. Fabiany Listas Duplamente Encadeadas Computação 2 Aula 10.1 Listas Duplamente Encadeadas Profª. Fabiany fabianyl@utfpr.edu.br ListaEncadeada.h #ifndef _LISTAENCADEADA_H_ #define _LISTAENCADEADA_H_ #include #include #include

Leia mais

Introdução à Ciência da Computação I. Alocação Dinâmica. Prof. Claudio Fabiano Motta Toledo

Introdução à Ciência da Computação I. Alocação Dinâmica. Prof. Claudio Fabiano Motta Toledo Introdução à Ciência da Computação I Alocação Dinâmica Prof. Claudio Fabiano Motta Toledo Sumário Funções para alocação de memória Ponteiros para ponteiros 8/12/16 2 Funções para alocação de memória malloc(),

Leia mais

PROGRAMAÇÃO FUNÇÕES NA LINGUAGEM C

PROGRAMAÇÃO FUNÇÕES NA LINGUAGEM C PROGRAMAÇÃO FUNÇÕES NA LINGUAGEM C 1 Enunciado: a)implementar a função maior que devolve o maior de dois números inteiros passados como parâmetro; b)construir um programa em C que determine o maior de

Leia mais

Resumo da última aula. Compiladores. Tipos. Regras semânticas. Expressões de tipos. Análise Semântica e checagem de tipos.

Resumo da última aula. Compiladores. Tipos. Regras semânticas. Expressões de tipos. Análise Semântica e checagem de tipos. Resumo da última aula Compiladores Análise semântica Verificação de tipos 1 Implementação: Esquemas S-atribuídos: Mecanismo bottom-up direto Esquemas L-atribuídos: Mecanismo top-down: Necessita gramática

Leia mais

/*(Atenção: Em se tratando de uma lista estaticamente alocada, temos utilizado a estratégia de passa o tamanho máximo do vetor.)*/

/*(Atenção: Em se tratando de uma lista estaticamente alocada, temos utilizado a estratégia de passa o tamanho máximo do vetor.)*/ ========================TDA.H #include "info.h" #define TRUE 1 #define FALSE 0 #define INI_LISTA 1 #define OK 1; #define NOK -1; typedef struct nolista{ info dados; struct nolista *prox; struct nolista

Leia mais

Algoritmo e Técnica de Programação - Linguagem C

Algoritmo e Técnica de Programação - Linguagem C Algoritmo e Técnica de Programação Linguagem C Gilbran Silva de Andrade 5 de junho de 2008 Introdução A liguagem C foi inventada e implementada por Dennis Ritchie em um DEC PDP-11 que utilizava o sistema

Leia mais

MC102 Algoritmos e programação de computadores Aula 3: Variáveis

MC102 Algoritmos e programação de computadores Aula 3: Variáveis MC102 Algoritmos e programação de computadores Aula 3: Variáveis Variáveis Variáveis são locais onde armazenamos valores na memória. Toda variável é caracterizada por um nome, que a identifica em um programa,

Leia mais

Convertendo Algoritmos para a Linguagem C

Convertendo Algoritmos para a Linguagem C onvertendo Algoritmos para a Linguagem Notas de Aula Prof. Francisco Rapchan www.geocities.com/chicorapchan O objetivo deste texto é mostrar alguns programas em, dando uma breve descrição de seu funcionamento

Leia mais

1. Fazer um programa em C que pergunta um valor em metros e imprime o correspondente em decímetros, centímetros e milímetros.

1. Fazer um programa em C que pergunta um valor em metros e imprime o correspondente em decímetros, centímetros e milímetros. Lista de exercícios: Grupo I - programa seqüênciais simples 1. Fazer um programa em C que pergunta um valor em metros e imprime o correspondente em decímetros, centímetros e milímetros. 2. Fazer um programa

Leia mais

cast poderia ser usado também para transformar um real (float) em inteiro. A sintaxe C (float)i pode ser substituída em C++ por float(i).

cast poderia ser usado também para transformar um real (float) em inteiro. A sintaxe C (float)i pode ser substituída em C++ por float(i). Cast (conversão) Um tipo de dado pode ser convertido momentaneamente em outro tipo com um cast. Em linguagem C a sintaxe usada é formada pelo tipo desejado entre parênteses precedendo a expressão a ser

Leia mais

O que é um apontador em C (type pointer in C)?

O que é um apontador em C (type pointer in C)? O que é um apontador em C (type pointer in C)? Um apontador é uma variável que contém um endereço de outra variável. int x = 10;//variável inteira iniciada com o valor 10 int *px = &x;//variável apontadora

Leia mais

Estruturas (Registros)

Estruturas (Registros) Estruturas (Registros) Agrupa conjunto de tipos de dados distintos sob um único nome string string inteiro inteiro inteiro float float Cadastro Pessoal Nome Endereço Telefone Idade Data de Nascimento Peso

Leia mais

Curso de Programação C em Ambientes Linux Aula 05

Curso de Programação C em Ambientes Linux Aula 05 Curso de Programação C em Ambientes Linux Aula 05 Centro de Engenharias da Mobilidade - UFSC Professores Gian Berkenbrock e Giovani Gracioli http://www.lisha.ufsc.br/c+language+course+resources Conteúdo

Leia mais

Linguagem C. Ricardo Terra. rterrabh@gmail.com. Ricardo Terra (rterrabh@gmail.com) Linguagem C 1 de agosto de 2012 1 / 341

Linguagem C. Ricardo Terra. rterrabh@gmail.com. Ricardo Terra (rterrabh@gmail.com) Linguagem C 1 de agosto de 2012 1 / 341 Linguagem C Ricardo Terra rterrabh@gmail.com Ricardo Terra (rterrabh@gmail.com) Linguagem C 1 de agosto de 2012 1 / 341 Conteúdo 1 Introdução Tópicos Importantes 2 Sintaxe Básica 3 Ponteiros 4 Tópicos

Leia mais

Sintaxe Geral Tipos de Dados. Prof. Angelo Augusto Frozza, M.Sc.

Sintaxe Geral Tipos de Dados. Prof. Angelo Augusto Frozza, M.Sc. Sintaxe Geral Tipos de Dados Comentários Comentários: De linha: // comentário 1 // comentário 2 De bloco: /* linha 1 linha 2 linha n */ De documentação: /** linha1 * linha2 */ Programa Exemplo: ExemploComentario.java

Leia mais

Programação de Computadores II

Programação de Computadores II Programação de Computadores II Aula de Revisão 01 Karina Mochetti 2019.1 Formato da Prova Questões teóricas. Escrever um programa do zero. Dar valores finais de variáveis. Completar um programa. Achar

Leia mais

Introdução à Linguagem C

Introdução à Linguagem C Prof a.dr a.thatyana de Faria Piola Seraphim (ECO) Prof.Dr.Enzo Seraphim (ECO) Universidade Federal de Itajubá thatyana@unifei.edu.br seraphim@unifei.edu.br Introdução - História A linguagem de programação

Leia mais

Estruturas de dados elementares

Estruturas de dados elementares AED 2002/2003 p.1/31 Estruturas de dados elementares Tipos básicos Estruturas Tabelas Listas Amontoados AED 2002/2003 p.2/31 Tipos básicos Inteiros Reais Caracteres Ponteiros short a1; int a2; long a3;

Leia mais

Programação. MEAer. Bertinho Andrade da Costa. Instituto Superior Técnico. Introdução ao Pré-Processador. 2011/2012 1º Semestre

Programação. MEAer. Bertinho Andrade da Costa. Instituto Superior Técnico. Introdução ao Pré-Processador. 2011/2012 1º Semestre Programação MEAer Bertinho Andrade da Costa 2011/2012 1º Semestre Instituto Superior Técnico Introdução ao Pré-Processador Programação 2011/2012 DEEC-IST Introdução ao Pré-Processador 1 Sumário Introdução

Leia mais

Curso C: Ponteiros e Arrays

Curso C: Ponteiros e Arrays Universidade de Brasília Departamento de Ciência da Computação Curso C: Ponteiros e Arrays Prof. Ricardo Pezzuol Jacobi rjacobi@cic.unb.br Ponteiros um ponteiro Ž uma vari vel que contžm o endere o um

Leia mais

Ponteiros & tabelas (cont.) K&R: Capítulo 5

Ponteiros & tabelas (cont.) K&R: Capítulo 5 Ponteiros & tabelas (cont.) K&R: Capítulo 5 Sinopse da aula de hoje Pointers in a nutshell & alocação dinâmica de memória Estruturas, funções e apontadores Estruturas auto-referenciadas Exemplo de aplicação:

Leia mais

Plano de Aula. if(condição) { bloco de comandos; } else { bloco de comandos2; }

Plano de Aula. if(condição) { bloco de comandos; } else { bloco de comandos2; } Instituto Federal de Santa Catarina - Câmpus Chapecó Ensino Médio Integrado em Informática - Módulo IV Unidade Curricular: Programação Estruturada Professora: Lara Popov Zambiasi Bazzi Oberderfer Plano

Leia mais

Exercício. Alocação Dinâmica. Alocação dinâmica de memória. Alocação de memória. Alocação da Memória Principal. Alocação da Memória Principal

Exercício. Alocação Dinâmica. Alocação dinâmica de memória. Alocação de memória. Alocação da Memória Principal. Alocação da Memória Principal Exercício Crie uma função que recebe o número de dias até um determinado evento e calcula e retorna o equivalente em meses, semanas e dias, sem usar vetor ou o conceito de vetor. Considerar que todos os

Leia mais

Linguagens de Programação I

Linguagens de Programação I Linguagens de Programação I Tema # 4 Operadores em C Susana M Iglesias FUNÇÕES ENTRADA-SAÍDA I/O printf(), utilizada para enviar dados ao dispositivo de saída padrão (stdout), scanf(), utilizada para ler

Leia mais

INF 1620 P2-01/11/03 Questão 1 Nome:

INF 1620 P2-01/11/03 Questão 1 Nome: INF 1620 P2-01/11/03 Questão 1 Considere a implementação de uma lista encadeada para armazenar as notas dos alunos de uma turma dada pelo tipo abaixo: struct lista { char nome[81]; int mat; float p1, p2,

Leia mais

Algoritmos de Pesquisa e Ordenação em Vectores

Algoritmos de Pesquisa e Ordenação em Vectores Algoritmos de Pesquisa e Ordenação em Vectores FEUP - MIEEC Programação 2-2008/2009 Pesquisa Sequencial Problema (pesquisa de valor em vector): Verificar se um valor existe no vector e, no caso de existir,

Leia mais

INTRODUÇÃO À LINGUAGEM PASCAL PREFÁCIO

INTRODUÇÃO À LINGUAGEM PASCAL PREFÁCIO INTRODUÇÃO À LINGUAGEM PASCAL CESAR BEZERRA TEIXEIRA,MSC PREFÁCIO A linguagem C foi desenvolvida no início da década de 70 por dois pesquisadores do Bell Laboratories, Brian Kernihgan e Dennis Ritchie,

Leia mais

INSTITUTO SUPERIOR TÉCNICO Algoritmos e Estruturas de Dados

INSTITUTO SUPERIOR TÉCNICO Algoritmos e Estruturas de Dados INSTITUTO SUPERIOR TÉCNICO Algoritmos e Estruturas de Dados Ano Lectivo de 2002/2003 2 o Semestre Repescagem do 2 o Teste (A) 18 de Julho de 2003 Duração: 2h - O teste é sem consulta. - Para cada questão

Leia mais

insfcanceof new public switch transient while byte continue extends for int null

insfcanceof new public switch transient while byte continue extends for int null Palavras -chave de JAV A abstract catch do final implements long private static throw void boolean char double finally import native protected super throws volatile break class float insfcanceof new public

Leia mais

Algoritmos e Estruturas de dados

Algoritmos e Estruturas de dados Algoritmos e Estruturas de dados Listas Encadeadas Prof. Dr. Fábio Rodrigues de la Rocha (Listas Encadeadas) 1 / 21 Definição: Anteriormente estudamos listas encadeadas que foram implementadas como vetores

Leia mais

1 Exercícios com ponteiros

1 Exercícios com ponteiros Computação para Informática Funções e Ponteiros1 EXERCÍCIOS COM PONTEIROS Computação para Informática - Prof. Adriano Joaquim de Oliveira Cruz Aula Prática - Funções e ponteiros O objetivo desta aula prática

Leia mais

Estruturas de Dados Aula 15: Árvores 17/05/2011

Estruturas de Dados Aula 15: Árvores 17/05/2011 Estruturas de Dados Aula 15: Árvores 17/05/2011 Fontes Bibliográficas Livros: Introdução a Estruturas de Dados (Celes, Cerqueira e Rangel): Capítulo 13; Projeto de Algoritmos (Nivio Ziviani): Capítulo

Leia mais

Introdução à Programação com Classes em C++

Introdução à Programação com Classes em C++ 1 FEUP/LEEC/AED/2001-2002 Introdução à Programação com Classes em C++ João Pascoal Faria http://www.fe.up.pt/~jpf FEUP/LEEC/AED/ 2000-2001 Conceito de classe em C++ 2 Classe em sentido lato: tipo de dados

Leia mais

INF 1007 Programação II

INF 1007 Programação II INF 1007 Programação II Aula 06 Tipos Estruturados Edirlei Soares de Lima Dados Compostos Até agora somente utilizamos tipos de dados simples: char, int, float, double. Muitas vezes

Leia mais

Hello World. Linguagem C. Tipos de Dados. Palavras Reservadas. Operadores Aritméticos. Pré e pós incremento e pré e pós decremento

Hello World. Linguagem C. Tipos de Dados. Palavras Reservadas. Operadores Aritméticos. Pré e pós incremento e pré e pós decremento Hello World Linguagem C printf("hello world!\n"); main é a função principal, a execução do programa começa por ela printf é uma função usada para enviar dados para o vídeo Palavras Reservadas auto double

Leia mais

INF1007: Programação 2 9 Tipos Abstratos de Dados. (c) Dept. Informática - PUC-Rio 1

INF1007: Programação 2 9 Tipos Abstratos de Dados. (c) Dept. Informática - PUC-Rio 1 INF1007: Programação 2 9 Tipos Abstratos de Dados (c) Dept. Informática - PUC-Rio 1 Tópicos Módulos e compilação em separado Tipo abstrato de dados Exemplo 1: TAD Ponto Exemplo 2: TAD Círculo Exemplo 3:

Leia mais

ATENÇÃO!!! 12-01-2005 Rui Morgado - TLP 2

ATENÇÃO!!! 12-01-2005 Rui Morgado - TLP 2 Ciclos Exercícios ATENÇÃO!!! Depois de executar o exercício no editor da linguagem de programação C, copie o código para o bloco de notas (dê como nome ao ficheiro o n.º do exercício e o seu nome) e guarde

Leia mais

Operaçõe õ s c om o Strings Intr oduç ão a o Ponte iros o e Funçõe õ s

Operaçõe õ s c om o Strings Intr oduç ão a o Ponte iros o e Funçõe õ s Universidade de São Paulo São Carlos Instituto de Ciências Matemáticas e de Computação Operações com Strings Introdução a Ponteiros e Funções Profa Rosana Braga 1 Strings Strings são seqüências de caracteres

Leia mais

INSTITUTO SUPERIOR TÉCNICO Introdução aos Algoritmos e Estruturas de Dados

INSTITUTO SUPERIOR TÉCNICO Introdução aos Algoritmos e Estruturas de Dados INSTITUTO SUPERIOR TÉCNICO Introdução aos Algoritmos e Estruturas de Dados Ano Lectivo de 2006/2007 2 o Semestre 2 o Teste A - 2 de Julho de 2007 Duração: 2h - O teste é sem consulta. - Para cada questão

Leia mais

Programação 1. Atribuição, operadores aritméticos, entrada de dados. Técnico em Eletrônica Semestre 5 02

Programação 1. Atribuição, operadores aritméticos, entrada de dados. Técnico em Eletrônica Semestre 5 02 Programação 1 Atribuição, operadores aritméticos, entrada de dados Técnico em Eletrônica Semestre 5 02 Armazenando na memória tipo de variável #include #include main() { int ano; Declaração

Leia mais

UNIP - Ciência da Computação e Sistemas de Informação. Estrutura de Dados. AULA 6 Filas

UNIP - Ciência da Computação e Sistemas de Informação. Estrutura de Dados. AULA 6 Filas UNIP - Ciência da Computação e Sistemas de Informação Estrutura de Dados AULA 6 Filas Estrutura de Dados A Estrutura de Dados Fila Fila é uma estrutura de dados usada em programação, que tem regras para

Leia mais

Reinaldo Gomes Alocação Dinâmica

Reinaldo Gomes Alocação Dinâmica Algoritmos e Lógica de Programação Linguagem C Alocação Dinâmica i de Memória Reinaldo Gomes reinaldo@cefet-al.br Alocação Dinâmica Quando declaramos uma variável ou um arranjo, o compilador automaticamente

Leia mais

Programação com Posix Threads

Programação com Posix Threads 9 Programação com Posix Threads Revisão: Data: 11-03-2016 Cap. 9 1/6 Programação multi-threaded com Pthreads 9.1. O que é uma thread? Um processo represente a execução pelo sistema operativo dum programa.

Leia mais

Programação: Estruturas de seleção

Programação: Estruturas de seleção Programação de Computadores I Aula 07 Programação: Estruturas de seleção José Romildo Malaquias Departamento de Computação Universidade Federal de Ouro Preto 2011-1 1/53 Valores booleanos Os valores booleanos

Leia mais

Estrutura Condicional em Java

Estrutura Condicional em Java Estrutura Condicional em Java Linguagem de Programação 1 O Java contém três tipos de instruções de seleção. A instrução if realiza uma ação se uma condição for verdadeira ou pula a ação se a condição for

Leia mais

Algoritmos e Estruturas de Dados

Algoritmos e Estruturas de Dados Introdução aos Algoritmos e Estruturas de Dados 2 o Teste - A Ano lectivo: 2010/2011 2 o Semestre RESOLUÇÃO DO 2 o TESTE Grupo I (2.0 + 2.5 + 2.0 = 6.5 val.) I.a) Considere os tipos enum ocasiao e Presente

Leia mais