53
Programação de Computadores II 8. Bibliotecas e String Raphael M. 2019.1 Raphael M. Aula 08. Bibliotecas e String

Programação de Computadores II - siccciber.com.br · Bibliotecas Biblioteca é uma conjunto de subprogramas utilizados na programação que contém código e dados auxiliares externos

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Programação de Computadores II8.Bibliotecase String

RaphaelM.

2019.1

Raphael M. Aula 08.Bibliotecase Str ing

Bibliotecas

Bibliotecaéumaconjuntodesubprogramasutilizadosnaprogramaçãoquecontémcódigoedadosauxiliaresexternosaoprogramaprincipal,oquepermiteocompartilhamentoeaalteraçãodecódigoedadosdeformamodular.

/* Hello World program * / #include <stdio.h>

i n t main() {p r i n t f ("Hello World.\n"); re turn 0 ;

}

Raphael M. Aula 08.Bibliotecase Str ing

Biblioteca math.h

Definefunçõesmatemáticasutilizandootipodouble.

double cos(double x);double sin(double x);double tan(double x);double exp(double x);double log(double x);doublepow(doublex,doubley);doublesqrt(double x);

double fabs(double x);

Raphael M. Aula 08.Bibliotecase Str ing

Biblioteca math.h

#include <math.h>

i n t main ( ) {double angulo = 1.04716; / / 60 em radianos double coseno, seno, tangente;coseno = cos(angulo): seno = s in(angulo) ; tangente = tan(angulo): re turn 0 ;

}

Raphael M. Aula 08.Bibliotecase Str ing

Biblioteca time.h

Definefunçõesdetempocriandotiposprópriospara isso.

structtm:tm_sec,tm_min,tm_hour,tm_mday,tm_mon,tm_year,tm_wday,tm_yday, tm_isdsttypedeftime_ttime_t time();structtm*localtime(time_t*t);char*asctime(structtmt);

doubledifftime(structtmt1,structtmt2);

Raphael M. Aula 08.Bibliotecase Str ing

Biblioteca time.h

#include <time.h>

i n t main ( ) {cha * s t r ;time_t tempo_inteiro; s t r u c t tm tempo_dividido; tempo_inteiro = t ime( ) ;tempo_dividido = localtime(&tempo_inteiro); s t r = asctime(tempo_dividido);re turn 0 ;

}

Raphael M. Aula 08.Bibliotecase Str ing

Biblioteca limits.h

Definepropriedadesdealgunstipospré-definidosem C.

#defineCHAR_MAX 127#defineUCHAR_MAX 255#defineINT_MIN -2,147,483,648#defineINT_MAX 2,147,483,647#defineUINT_MAX 4,294,967,295

Raphael M. Aula 08.Bibliotecase Str ing

Biblioteca limits.h

#include <limits.h>

i n t main() {unsigned i n t i ; i n t j = INT_MAX;fo r ( i = 0 ; i < UINT_MAX; i++)

j - - ;re turn 0 ;

}

Raphael M. Aula 08.Bibliotecase Str ing

Biblioteca stdio.h

Definerotinasdeentradaesaídapadrãoede arquivos.

intprintf( constchar*format,...);intscanf( constchar*format,... );FILE*fopen(constchar*filename,constchar*mode);intfclose(FILE*stream );

size_tfread(void*ptr,size_tsize,size_tcount,FILE*stream );size_tfwrite( constvoid*ptr,size_tsize,size_tcount,FILE*stream );streamspadrões:stdin,stdout, stderr

Raphael M. Aula 08.Bibliotecase Str ing

Biblioteca stdio.h

#include <stdio.h>

f c d" , f , c , n ) ;

i n t main() {i n t n ; char c ; f l o a t f ;printf("Lendo 3 var iave i s : " ) ;scanf(" d c f " , &n, &c, &f);printf("Escrevendo 3 var iáve i s :re turn 0 ;

}

Raphael M. Aula 08.Bibliotecase Str ing

Biblioteca string.h

Definerotinasparamanipulaçãodestrings,quesão vetoresdechar.

char*strcat(char*dest,constchar*src);intstrcmp(char*str1,char *str2)voidstrcpy(char*dest,constchar*src);size_tstrlen(char *str);

char nome[256];char *nome;

Raphael M. Aula 08.Bibliotecase Str ing

Strings

NãoháotipoStringemC,Stringssãovetoresdecaracteres!Toda string em C termina com um caractere especial, o \0.Stringssãodescritaentreaspasduplas"ecaracteresentreaspassimples ’.

char nome[12] = "Hello World"; char *nome = "Hello World";

Raphael M. Aula 08.Bibliotecase Str ing

Tabela ASCII

Raphael M. Aula 08.Bibliotecase Str ing

Caractere comoInteiro

EmCotipodecadavariávelémaislivre.ComovistonaTabelaASCIItodocaractereénaverdadeumnúmeroda tabela.

#include <stdio.h> i n t main() {

char c = ’ d ’ ; printf("O carac te r é : c \ n " , c ) ;printf("Seu número na tabe la ASCII é : d \ n " , c ) ; printf("O próximo ca rac te r na tabe la é : c \ n " , c+1); re turn 0 ;

}

Raphael M. Aula 08.Bibliotecase Str ing

Caractere ’\n’

Ocaractere’\n’éumcaractereespecialqueindicaquebradelinha.Nasaídapadrãoésempreusadoo’\n’,masemarquivosháumadiferençaentreSO.LinuxeMac:’\n’Win:’\r \n’

Raphael M. Aula 08.Bibliotecase Str ing

Caractere ’\0’

Ocaractere’\0’indicaofimdeumaStringem C.

Umastringden letrasprecisaráden + 1espaçosna memória.Aolerumastringcom"%s",ocompiladoradicionaocaractere’\0’ sozinho.Aoatribuirumastringcomaspas",ocompiladoradicionaocaractere’\0’ sozinho.Paraseusarasfunçõesdestring,éprecisoqueo’\0’estejapresente.

Raphael M. Aula 08.Bibliotecase Str ing

Casting

EmCépossível"traduzir"umavariáveldeumtipoparaoutroaqualquer momento.Issoéchamadodecasting,maséalgoquedeveserfeitocomcuidadojáquetiposdiferentespossuemlimiteseinterpretaçõesdiferentesdeumavariável.

#include <stdio.h> i n t main() {

i n t i = 10; f l o a t f ;f = ( f l o a t ) i ; re turn 0 ;

}

Raphael M. Aula 08.Bibliotecase Str ing

Exemplo 1

#include <stdio.h> i n t main() {

fo r ( i n t i = 0 ; i<128; i++) p r i n t f ( " d -> c \ n " , i , i ) ;

re turn 0 ;}

Raphael M. Aula 08.Bibliotecase Str ing

Exemplo 1: Imprimir a Tabela ASCII

#include <stdio.h> i n t main() {

fo r ( i n t i = 0 ; i<128; i++) p r i n t f ( " d -> c \ n " , i , i ) ;

re turn 0 ;}

Raphael M. Aula 08.Bibliotecase Str ing

Exemplo 2

#include <stdio.h> #include <string.h>

i n t main() {char * s t r 1 , s t r 2 ; scanf ( " s " , s t r 1 ) ;scanf ( " s " , s t r 2 ) ;i f (strcmp ( s t r 1 , s t r 2 ) != 0)

p r i n t f ("XXX\n" ) ;e l se

p r i n t f ("YYY\n " ) ; re turn 0 ;

}

Raphael M. Aula 08.Bibliotecase Str ing

Exemplo 2

#include <stdio.h> #include <string.h>

i n t main() {char * s t r 1 , s t r 2 ; scanf ( " s " , s t r 1 ) ;scanf ( " s " , s t r 2 ) ;i f (strcmp ( s t r 1 , s t r 2 ) != 0)

p r i n t f ("Sao d i fe ren te s \n" ) ;e l se

p r i n t f ("Sao ig u a i s \n " ) ; re turn 0 ;

}

Raphael M. Aula 08.Bibliotecase Str ing

Exemplo 2: Ler e Comparar Strings

#include <stdio.h> #include <string.h>

i n t main() {char * s t r 1 , s t r 2 ; scanf ( " s " , s t r 1 ) ;scanf ( " s " , s t r 2 ) ;i f (strcmp ( s t r 1 , s t r 2 ) != 0)

p r i n t f ("Sao d i fe ren te s \n" ) ;e l se

p r i n t f ("Sao ig u a i s \n " ) ; re turn 0 ;

}

Raphael M. Aula 08.Bibliotecase Str ing

Exemplo 3

#include <stdio.h> #include <string.h>

i n t main() {i n t m, n ; f l o a t f ;scanf ( " d d" , &n, &m);f = ( f l o a t ) m / ( f l o a t ) n ; printf("O resultado e f \ n " , f ) ; re turn 0 ;

}

Raphael M. Aula 08.Bibliotecase Str ing

Exemplo 3: Dividir Dois Inteiros

#include <stdio.h> #include <string.h>

i n t main() {i n t m, n ; f l o a t f ;scanf ( " d d" , &n, &m);f = ( f l o a t ) m / ( f l o a t ) n ; printf("O resultado e f \ n " , f ) ; re turn 0 ;

}

Raphael M. Aula 08.Bibliotecase Str ing

Exercício: O que faz?

x" , c -1 , c+1, ( i n t ) c ) ;

i n t main() {char c ;scanf(" c " , &c);p r i n t f ( " c -> cre turn 0 ;

}

Raphael M. Aula 08.Bibliotecase Str ing

Exercício

Programa que dado um caractere qualquer, imprime os caracteresanterior e posterior a ele na tabela ASCII e o seu número emhexadecimal na tabela.

Exemplos:

b→ ac620→ / 130)→ ( * 29

Raphael M. Aula 08.Bibliotecase Str ing

ProgramaçãodeComputadores II9. Tipo Abstrato de Dados

Raphael M.

2019.1

Raphael M. Aula 09.T i po Abstratode Dados

TipoAbstratode Dados

Tipo Abstrato de Dados (TAD) é um modelo no qual a definição de um conjunto de dados e suas operações é semântica.

Foco nos aspectos essenciais do dado. Abstração de como ele foi implementado.Num bom programa o main() só faz declarações e chamadas para TADs.O TAD é um caixa preta que resolve problemas, fornece dados sem que o usuário precise saber como o problema está sendo resolvido e como os dados estão sendorepresentados.

Raphael M. Aula 09.T i po Abstratode Dados

TipoAbstratode Dados

TiposSão as variáveis que serão utilizadas, normalmente declarada comstruct e typedef.

OperaçõesSão operações que são realizadas nos dados, normalmente sãofunções que ou retornam ou possuem como argumento o tipodefinido.

Raphael M. Aula 09.T i po Abstratode Dados

TipoAbstratode Dados

TiposSão as variáveis que serão utilizadas, normalmente declarada comstruct e typedef.

Estudante: nome, matricula, notaP, notaT

OperaçõesSão operações que são realizadas nos dados, normalmente sãofunções que ou retornam ou possuem como argumento o tipodefinido.

calculaMedia(), defineNome(), validaMatricula()

Raphael M. Aula 09.T i po Abstratode Dados

TipoAbstratode Dados

TiposSão as variáveis que serão utilizadas, normalmente declarada comstruct e typedef.

Estudante: nome, matricula, notaP, notaT Vetor: elementos

OperaçõesSão operações que são realizadas nos dados, normalmente sãofunções que ou retornam ou possuem como argumento o tipodefinido.

calculaMedia(), defineNome(), validaMatricula() soma(), produtoInterno(), produtoVetorial()

Raphael M. Aula 09.T i po Abstratode Dados

TipoAbstratode Dados

TiposSão as variáveis que serão utilizadas, normalmente declarada comstruct e typedef.

Estudante: nome, matricula, notaP, notaT Vetor: elementosPontos: x, y,z

OperaçõesSão operações que são realizadas nos dados, normalmente sãofunções que ou retornam ou possuem como argumento o tipodefinido.

calculaMedia(), defineNome(), validaMatricula() soma(), produtoInterno(), produtoVetorial() saoIguais(), calculaDistancia(), valorX()

Raphael M. Aula 09.T i po Abstratode Dados

Fração

Fracao f ;

Fracao = cr iaFracao(int den, i n t num); i n t porZero (Fracao f ) ;i n t ehNegativa (Fracao f ) ;i n t valorDenominador (Fracao f ) ; i n t valorNumerador (Fracao f ) ; void reduz (Fracao f ) ;Fracao soma (Fracao f 1 , Fracao f 2 ) ; Fracao sub t ra i (Fracao f 1 , Fracao f 2 ) ; Fracao mult ipl ica (Fracao f 1 , Fracao f 2 ) ; Fracao divide (Fracao f 1 , Fracao f 2 ) ;

Raphael M. Aula 09.T i po Abstratode Dados

Fração

typedef s t r u c t fracao { i n t numerador;i n t denominador;

} Fracao;

i n t porZero (Fracao f ) {i f (f.denominador == 0) re turn 1 ;e l se re turn 0 ;

}

Fracao mult ipl ica (Fracao f 1 , Fracao f2 ) { Fracao f ;f.numerador = f1.numerador * f2.numerador; f.denominador = f1.denominador * f2.denominador; re turn f ;

}

Raphael M. Aula 09.T i po Abstratode Dados

Fração

#define NUM 0#define DEN 1typedef i n t Fracao[2];

i n t porZero (Fracao f ) {i f (f[DEN] == 0) re turn 1 ;e l se re turn 0 ;

}

Fracao mult ipl ica (Fracao f 1 , Fracao f2 ) { Fracao f ;f[NUM] = f1[NUM] * f2[NUM];f[DEN] = f1[DEN] * f2[DEN];re turn f ;

}

Raphael M. Aula 09.T i po Abstratode Dados

TipoAbstratode Dados

O usuário não vê a implementação.Não há referência à maneira que os dados são representados ouutilizados.Separação do programa, da especificação e da implementação.

Raphael M. Aula 09.T i po Abstratode Dados

VantagensdoTAD

Mais fácil modificar o código.O código pode ser reutilizado.Mais fácil acharerros.O código podeser compartilhado entre maisdeumprograma.

Raphael M. Aula 09.T i po Abstratode Dados

VantagensdoTAD

Num TAD a implementação deve toda ser abstraída no arquivo principal. Assim, qualquer acesso direto a elementos do TAD é uma violação a essaregra.

#include "fracao.h"

i n t main() {Fracao f1 = criaFracao(10, 3 ) ; Fracao f2 = criaFracao(20, 9 ) ; Fracao f3 = soma ( f 1 , f 2 ) ; re turn 0 ;

}

O arquivo main acima funciona com ambas as implementações de Fração vistas.

Raphael M. Aula 09.T i po Abstratode Dados

Ponto

typedef s t r u c t ponto { i n t x ;i n t y ;

} Ponto;

Ponto definePonto ( i n t x , i n t y ) ;i n t calculaDistancia (Ponto p1, Ponto p2); i n t valorX (Ponto p ) ;i n t valorY (Ponto p ) ;

Raphael M. Aula 09.T i po Abstratode Dados

Circulo

typedef s t r u c t c i rcu lo { Ponto centro ;i n t r a i o ;

} Circulo;

Circulo defineCirculo ( i n t r a i o , Ponto cen t ro ) ; Circulo mudaCentro (Circulo c , Ponto cen t ro ) ; Circulo mudaRaio (Circulo c , i n t r a i o ) ;f l o a t calculaArea (Circulo c ) ; i n t valorRaio (Circulo c ) ; Ponto valorCentro (Circulo c ) ;

Raphael M. Aula 09.T i po Abstratode Dados

Desenho

typedef s t r u c t desenho { Ponto pontos[100]; Circulo c irculos[100]; i n t p ;i n t c ;

} Desenho;

Desenho criaDesenho();Desenho insereCirculo(Desenho d , Circulo c ) ; Desenho removeCirculo(Desenho d , Circulo c ) ; Desenho inserePonto(Desenho d , Ponto p ) ; Desenho removePonto(Desenho d , Ponto p ) ;i n t numeroFormas(Desenho d ) ;

Raphael M. Aula 09.T i po Abstratode Dados

SoftwareemCamadas

Raphael M. Aula 09.T i po Abstratode Dados

Exemplo1: Data

Raphael M. Aula 09.T i po Abstratode Dados

Exemplo1: Data

typedef s t r u c t data { i n t d i a ;i n t mes; i n t ano;

} Data;

Raphael M. Aula 09.T i po Abstratode Dados

Exemplo1: Data

typedef s t r u c t data { i n t d i a ;i n t mes; i n t ano;

} Data;

Data c r iaData( in t d i a , i n t mes, i n t ano); i n t comparaData(Data d1, Data d2);void imprimeData(Data d ) ;Data mudaDia(int d i a , Data d ) ; i n t anoBissexto (Data d ) ;

Raphael M. Aula 09.T i po Abstratode Dados

Exemplo2: Horario

Raphael M. Aula 09.T i po Abstratode Dados

Exemplo2: Horario

typedef s t r u c t horario { i n t hora;i n t minuto; i n t segundo; i n t fuso;

} Horario;

Raphael M. Aula 09.T i po Abstratode Dados

Exemplo2: Horario

typedef s t r u c t horario { i n t hora;i n t minuto; i n t segundo; i n t fuso;

} Horario;

Horario cr iaHorar io( in t hora, i n t min, i n t seg ) ; i n t comparaHorario(Horario h1, Horario h2);void imprimeHorario(Horario h ) ; void horarioDeVerao(Horario *h);

Raphael M. Aula 09.T i po Abstratode Dados

Exemplo3:Conta Bancária

Raphael M. Aula 09.T i po Abstratode Dados

Exemplo3:Conta Bancária

typedef s t r u c t conta { f l o a t sa ldo;f l o a t depositos[100]; f l o a t t ransferencias[100]; char *usuario;i n t senha;

} Conta;

Raphael M. Aula 09.T i po Abstratode Dados

Exemplo3:Conta Bancária

typedef s t r u c t conta { f l o a t sa ldo;f l o a t depositos[100]; f l o a t t ransferencias[100]; char *usuario;i n t senha;

} Conta;

Conta criaConta(char *usuario, i n t senha); void deletaConta(Conta c ) ;void deposi to(f loa t va lo r , Conta c ) ; void saque(f loat va lo r , Conta c ) ;void t r a n s f ( f l o a t va lo r , Conta origem, Conta des t ino ) ; f l o a t saldo(Conta c ) ;

Raphael M. Aula 09.T i po Abstratode Dados

Exercício

Em matemática, função polinomial é uma função que pode ser expressa da forma:

f (x) = anxn + an−1xn−1 +···+ a1x1+a0x0

Projete o TAD para funções polinomiais. Pense em qual seria o tipo de dados e quais operações deveriam ser implementadas.

Raphael M. Aula 09.T i po Abstratode Dados

Exercício: Solução

Projete o TAD para equações polinomiais. Pense em qual seria o tipo de dados e quais funções deveriam ser implementadas.

#define MAX 100

typedef s t r u c t polinomio {i n t coeficientes[MAX];i n t grau;

} Polinomio;

Polinomio criaPolinomio ( i n t grau) ;void insereCoeficiente (Polinomio *p, i n t termo, i n t coe f ) ; Polinomio soma (Polinomio p1, Polinomio p2);Polinomio mult ipl ica (Polinomio p1, Polinomio p2);

Raphael M. Aula 09.T i po Abstratode Dados