COMPUTAÇÃO E PROGRAMAÇÃO

Documentos relacionados
Computação e Programação

COMPUTAÇÃO E PROGRAMAÇÃO

Métodos Formais em Engenharia de Software. VDMToolTutorial

Strings. COM10615-Tópicos Especiais em Programação I edmar.kampke@ufes.br 2014-II

Inglês. Entrelinha 1,5 (Versão única igual à Versão 1) Teste Intermédio de Inglês. Parte III Compreensão do oral. Entrelinha 1,5.

Guião A. Descrição das actividades

Welcome to Lesson A of Story Time for Portuguese

Guião N. Descrição das actividades

GUIÃO Domínio de Referência: CIDADANIA E MULTICULTURALISMO

Slides_Java_1 !"$ % & $ ' ' Output: Run java. Compile javac. Name of program. Must be the same as name of file. Java source code.

Addition of Fields in Line Item Display Report Output for TCode FBL1N/FBL5N

GUIÃO A. What about school? What s it like to be there/here? Have you got any foreign friends? How did you get to know them?

Easy Linux! FUNAMBOL FOR IPBRICK MANUAL. IPortalMais: a «brainware» company Manual

Guião M. Descrição das actividades

Para iniciar um agente SNMP, usamos o comando snmpd. Por padrão, aceita requisições na porta 161 (UDP).

User Guide Manual de Utilizador

Prova Oral de Inglês Duração da Prova: 20 a 25 minutos 2013/ º Momento. 4 (A), are you a health-conscious person?

Para iniciar um agente SNMP, usamos o comando snmpd. Por padrão, aceita requisições na porta 161 (UDP).

Dispositivos de Entrada. Dispositivos de Entrada. Data Glove. Data Glove. Profa. M. Cristina Profa. Rosane março 2006 março 2009

Prova de Seleção Mestrado LINGUA INGLESA 15/02/2016

Lesson 6 Notes. Eu tenho um irmão e uma irmã Talking about your job. Language Notes

Serviços: API REST. URL - Recurso

Inglês. Guião. Teste Intermédio de Inglês. Parte IV Interação oral em pares. Teste Intermédio

UNIVERSITY OF CAMBRIDGE INTERNATIONAL EXAMINATIONS International General Certificate of Secondary Education PORTUGUESE 0540/03

Desafios tecnológicos para o Projeto Observatório Logístico de Transporte

SISTEMAS DISTRIBUÍDOS 1º EXAME

PROTOCOLOS DE COMUNICAÇÃO

UNIVERSITY OF CAMBRIDGE INTERNATIONAL EXAMINATIONS International General Certificate of Secondary Education

Visitor, is this is very important contact with you. WATH DO WE HERE?

Trabalho de Compensação de Ausência - 1º Bimestre

01-A GRAMMAR / VERB CLASSIFICATION / VERB FORMS

Manual de Comandos Úteis OpenSSL para Certificados Digitais

User interface evaluation experiences: A brief comparison between usability and communicability testing

Instrução para gerar CSR com OpenSSL

Aqui pode escolher o Sistema operativo, e o software. Para falar, faça download do Cliente 2.

CODIGOS CONTROLE RS232 Matrix HDMI 4x2 Control EDID/RS232 (GB )

Completing your Participant Agreement Como preencher o Contrato de Participação

GUIÃO A. Ano: 9º Domínio de Referência: O Mundo do Trabalho. 1º Momento. Intervenientes e Tempos. Descrição das actividades

Triggers no PostgreSQL

Perguntas & Respostas

Conteúdo Programático Anual

Accessing the contents of the Moodle Acessando o conteúdo do Moodle

Versão: 1.0. Segue abaixo, os passos para o processo de publicação de artigos que envolvem as etapas de Usuário/Autor. Figura 1 Creating new user.

Design de Multimédia e Interacção

O caminho da GMB para aprovação técnica no PMC passou pelo projeto GMB2NLM

booths remain open. Typical performance analysis objectives for the toll plaza system address the following issues:

manualdepsiquiatriainfant il manual de psiquiatria infantil

Criação de uma aplicação Web ASP.NET MVC 4

Institutional Skills. Sessão informativa INSTITUTIONAL SKILLS. Passo a passo.

Descrição das actividades

Versão 1. Nome do aluno: N.º: Turma: Atenção! Não vires esta página até receberes a indicação para o fazeres.

Português 207 Portuguese for Business

NOVO SISTEMA DE CORREIO ELETRONICO PARA OS DOMINIOS ic.uff.br & dcc.ic.uff.br

How are you? Activity 01 Warm up. Activity 02 Catch! Objective. Procedure. Objective. Preparation. Procedure. To warm-up and practice greetings.

Programação 2009/2010 MEEC - MEAer Laboratório 5 Semana de 26 de outubro de 2009

Câmbio MONEY CHANGER. I d like to exchange some money. Gostaria de cambiar um pouco de dinheiro. Where can I find a money changer?

Searching for Employees Precisa-se de Empregados

SUMÁRIO VOLUME 1 LÍNGUA INGLESA

Easy Linux! FUNAMBOL FOR IPBRICK MANUAL. IPortalMais: a «brainmoziware» company Manual Jose Lopes

Consultoria em Direito do Trabalho

NORMAS PARA AUTORES. As normas a seguir descritas não dispensam a leitura do Regulamento da Revista Portuguesa de Marketing, disponível em

ACFES MAIORES DE 23 ANOS INGLÊS. Prova-modelo. Instruções. Verifique se o exemplar da prova está completo, isto é, se termina com a palavra FIM.

UNIVERSIDADE DE SÃO PAULO FACULDADE DE EDUCAÇÃO JOÃO FÁBIO PORTO. Diálogo e interatividade em videoaulas de matemática

Número: Nome:

Laboratório 3. Base de Dados II 2008/2009

Sistemas Operativos - Mooshak. 1 Mooshak. in fct.ualg.pt/. mooshak.deei.fct.ualg.pt/.


COMPUTAÇÃO E PROGRAMAÇÃO

Prova Escrita de Inglês

manualdepsiquiatriainfant il manual de psiquiatria infantil

T Ã O B O M Q U A N T O N O V O

MANUAL CONTABILIDADE BANCARIA PDF

5/10/10. Implementação. Building web Apps. Server vs. client side. How to create dynamic contents?" Client side" Server side"

Project Management Activities

Instructions. Instruções

Inglês. Guião. Teste Intermédio de Inglês. Parte III Interacção Oral. Teste Intermédio. Duração do Teste: 10 a 15 minutos De a

3 o ANO ENSINO MÉDIO. Prof. a Christiane Mourão Prof. a Cláudia Borges

Introdução a classes e objetos by Pearson Education do Brasil

Knowledge Representation and Reasoning

Práticas de Desenvolvimento de Software

What is Bullying? Bullying is the intimidation or mistreating of weaker people. This definition includes three important components:1.

Organização Sete de Setembro de Cultura e Ensino - LTDA Faculdade Sete de Setembro FASETE Bacharelado em Administração

Caracterização dos servidores de

#* Online Read Introducao ao Direito Empresarial: Direito Empresarial, Empresa, Empresario, Livros, Denominacao, Fundo de Empresa...

3 o Treino para Alunos da UFPR 18 de Janeiro de 2013

Erasmus Student Work Placement

hdd enclosure caixa externa para disco rígido

Teoria Económica Clássica e Neoclássica

APRESENTAÇÃO. ABNT CB-3 Comitê Brasileiro de Eletricidade Comissão de Estudo CE 03: Instalações Elétricas de Baixa Tensão NBR 5410

Ficha de unidade curricular Curso de Doutoramento

para que Software Produto: Página: 6.0 Introdução O Aker Firewall não vem com Configuração do PPPoE Solução

Efficient Locally Trackable Deduplication in Replicated Systems. technology from seed

Parts of the Solar Charger. Charging the Solar Battery. Using the Solar Lamp. Carry in hand. Shows how much light is left. Table light.

Universidade Estadual do Centro-Oeste Reconhecida pelo Decreto Estadual nº 3.444, de 8 de agosto de 1997

AT A HOTEL NO HOTEL. I d like to stay near the station. Can you suggest a cheaper hotel? Poderia sugerir um hotel mais barato?

The L2F Strategy for Sentiment Analysis and Topic Classification

Programação em MATLAB

CADERNO DE PROBLEMAS

SUMÁRIO VOLUME 1 LÍNGUA INGLESA

Transcrição:

COMPUTAÇÃO E PROGRAMAÇÃO 1º Semestre 2015/2016 MEMec, LEAN Ficha da Aula Prática 6: Cadeias de caracteres (strings). Estruturas de dados (structures). Sumário das tarefas e objectivos da aula: 1. Utilizar as funções pré-definidas que realizam processamento de strings. 2. Criar e utilizar estruturas com informação organizada por campos. 3. Criar e utilizar vectores de estruturas. NOTA 1: Durante a resolução dos exercícios deverá consultar as apresentações das aulas teóricas, e/ou o livro de apoio da disciplina. NOTA 2: antes de começar cada aula deve-se mudar a directoria de trabalho para uma directoria na pen-drive do aluno, isto garante que o aluno ficará com todos os ficheiros que sejam eventualmente criados durante a aula. Exercícios a resolver na aula Docente Alunos (recomendados) Alunos 1.2, 1.18, 2.11 1.16, 1.20. 2.21 Challenge Computação e Programação, LEAN, MEMec 1

1. Exercícios sobre cadeias de caracteres (strings) 2. Write a function that will receive a name and department as separate strings and will create and return a code consisting of the first two letters of the name and the last two letters of the department. The code should be uppercase letters. For exemple: >> namedept('robert','mechanical') ROAL 8. Write a script that will generate a random integer, ask the user for a field width, and print the random integer with the specified field width. The script will use sprintf to create a string such as 'The # is %4d\n' (if, for example, the user entered 4 for the field width), which is then passed to the fprintf function. In order to print (or create a string using sprintf) either the % or \ character, there must be two of them in a row. 11. The functions that label the x and y axes and title on a plot expect string arguments. These arguments can be string variables. Write a script that will prompt the user for an integer n, then create an x vector with integer values from 1 to n, a y vector that is x^2, and then plot with a title that says x^2 with n values where the value of n is actually in the title. 16. Either in a script or in the Command Window, create a string variable that stores a string in which numbers are separated by the character +, for example 12+3+45+2. Create a vector of the numbers, and then get the sum (e.g., for the example given it would be 62 but the solution should be general). 18. In cryptography, the intended message sometimes consists of the first letter of every word in a string. Write a function crypt that will receive a string with the encrypted message and return the message. >> estring = 'The early songbird tweets'; >> m = crypt(estring) m = Test 20. Words in a sentence variable (just a string variable) called mysent are separated by / s instead of blank spaces. For example, mysent might have this value: 'This/is/not/quite/right'. Write a function slashtoblank that will receive a string in this form and will return a string in which the words are separated by blank spaces. This should be general and work regardless of the value of the argument. No loops are allowed in this function; the built-in string function(s) must be used. >> mysent = 'This/is/not/quite/right'; >> newsent = slashtoblank(mysent) newsent = This is not quite right 22. A filename is supposed to be in the form filename.ext. Write a function that will determine whether a string is in the form of a name followed by a dot followed by a three-character extension, or not. The function should return 1 for logical true if it is in that form, or 0 for false if not. Computação e Programação, LEAN, MEMec 2

26. Using the functions char and double, you can shift words. For example, you can convert from lowercase to uppercase by subtracting 32 from the character codes: >> orig = 'ape'; >> new = char(double(orig)-32) new = APE >> char(double(new)+32) ape We ve encrypted a string by altering the character codes. Figure out the original string. Try adding and subtracting different values (do this in a loop) until you decipher it: Jmkyvih$mx$syx$}ixC 2. Exercícios sobre estruturas de dados (structures) 11. Write the code in MATLAB that would create the following data structure, and put the following values into the variable: experiments num code weights Computação e Programação, LEAN, MEMec 3 feet inches 1 33 x 200.34 202.45 5 6 2 11 t 111.45 111.11 7 2 The variable is called experiments, which is a vector of structs. Each struct has four fields: num, code, weights, and. The field num is an integer, code is a character, weights is a vector with two values (both of which are double values), and is a struct with fields feet and inches (both of which are integers). Write the statements that would accomplish this, so that typing the following expressions in MATLAB would give the results shown: >> experiments experiments = 1x2 struct array with fields: num code weights >> experiments(2) num: 11 code: 't' weights: [111.4500 111.1100] : [1x1 struct]

>> experiments(1). feet: 5 inches: 6 9. A complex number is a number of the form a + ib, where a is called the real part, b is called the imaginary part, and i = -1. Write a script that prompts the user separately to enter values for the real and imaginary parts, and stores them in a structure variable. It then prints the complex number in the form a + ib. The script should just print the value of a, then the string '+ i', and then the value of b. For example, if the script is named compnumstruct, running it would result in: >> compnumstruct Enter the real part: 2.1 Enter the imaginary part: 3.3 The complex number is 2.1 + i3.3 (Note: This is just a structure exercise; MATLAB can handle complex numbers automatically as will be seen in Chapter 14.) 14. A script stores information on potential subjects for an experiment in a vector of structures called subjects. The following show an example of what the contents might be: >> subjects subjects = 1x3 struct array with fields: name sub_id weight >> subjects(1) name: 'Joey' sub_id: 111 : 6.7000 weight: 222.2000 For this particular experiment, the only subjects who are eligible are those whose or weight is lower than the average or weight of all subjects. The script will print the names of those who are eligible. Create a vector with sample data in a script, and then write the code to accomplish this. Don t assume that the length of the vector is known; the code should be general.222 20. Quality control involves keeping statistics on the quality of products. A company tracks its products and any failures that occur. For every imperfect part, a record is kept that includes the part number, a character code, a string that describes the failure, and the cost of both labor and material to fix the part. Create a vector of structures and create sample data for this company. Write a script that will print the information from the data structure in an easy-to-read format. 21. Create a data structure to store information on the planets in our solar system. For every planet, store its name, distance from the sun, and whether it is an inner planet or an outer planet. Computação e Programação, LEAN, MEMec 4

Nível Exercício 1 3. Write a function that will prompt the user separately for a first and last name and will create and return a string with the form last, first. 1 2 3 8. Create a structure variable that would store for a student his or her name, university ID number, and GPA. Print this information using fprintf. 16. Create a nested struct to store a person s name, address, and phone numbers. The struct should have three fields for the name, address, and phone. The address fields and phone fields will be structs. (suponha que o address tem os campos morada e código postal, e que o phone tem telemóvel e residência). 19. Write a function rid_multiple_blanks that will receive a string as an input argument. The string contains a sentence that has multiple blank spaces in between some of the words. The function will return the string with only one blank in between words. For example, >> mystr = 'Hello and ho w are you?'; >> rid_multiple_blanks(mystr) Hello and how are you? Os resultados de um questionário de uma turma podem ser organizados num vector de estruturas como o que se representa no quadro seguinte: estudante 3 numeroid questionario 1 12345 14.0 15.0 16.0 2 67890 11.0 12.0 13.0 3 10111 16.0 16.0 16.0 4 12134 12.0 14.0 16.0 Cada elemento do vector estudante será uma estrutura com dois campos: o valor inteiro numeroid e um vector de valores reais questionario contendo os resultados do questionário. Escreva um script onde cria o vector de estruturas apresentado, e que em seguida calcule e escreva a média do questionário para cada estudante. O resultado deverá ter a seguinte aparência: Estudante Média 12345 15.0 67890 12.0 10111 16.0 12134 14.0 Referências Apresentações das aulas teóricas AT 11 e AT 12. Capítulos 7 e 8 de Stormy Attaway (2012), Matlab: A Practical Introduction to Programming and Problem Solving, Elsevier. Computação e Programação, LEAN, MEMec 5