COMPUTAÇÃO E PROGRAMAÇÃO º Semestre 205/206 MEMec, LEAN Ficha da Aula Prática 3: Estruturas de repetição. Sumário das tarefas e objectivos da aula:. Estruturas de repetição controladas por contador 2. Estruturas de repetição controladas por expressão lógica NOTA : 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 2, 8, 23 7,22 Challenge Computação e Programação, LEAN, MEMec
. Exercícios 2. Write a script that asks the user for a positive integer value n, and then calculates and returns the sum of to n in steps of 2. For example, if the user input is, it will return + 3 + 5 + 7 + 9 +. Do this using a for loop. 3. Write a script that asks the user for a positive integer value n, and then calculates and returns the product of the odd integers from to n (or from to n if n is even). The following examples of calls to this function illustrate what the result should be: >> Enter a value for r: 2 Enter a value for n: 4 The value of the geometric series is 3 5. Prompt the user for an integer n and print I love this stuff! n times. 6. In the Command Window, write a for loop that will iterate through the integers from 32 to 255. For each, show the corresponding character from the character encoding. 7. In the Command Window, write a for loop that will print the elements from a vector variable in sentence format. For example, if this is the vector: >> vec = [5.5 3.45]; this would be the result: Element is 5.50. Element 2 is.00. Element 3 is 3.45. The for loop should work regardless of how many elements are in the vector. 4. Write a script that will ask the user to input a matrix and will calculate and return the overall average of all numbers in the matrix. Use loops, not built-in functions, to calculate the average. 6. Create a vector of five random integers, each in the range from 0 to 0. Perform each of the following two ways: using built-in functions, and also using loops (with if statements if necessary): Subtract 3 from each element. Count how many are positive. Get the absolute value of each element. Find the maximum. 7. Create a 3 5 matrix. Perform each of the following two ways: using built-in functions, and also using loops (with if statements if necessary): Find the maximum value in each column. Find the maximum value in each row. Find the maximum value in the entire matrix. Computação e Programação, LEAN, MEMec 2
8. Write a script that will print the following multiplication table: 2 4 3 6 9 4 8 2 6 5 0 5 20 25 2. Generate a random integer n, create a vector of the integers through n in steps of 2, square them, and plot the squares. 22. A vector v stores for several employees of the Green Fuel Cells Corporation their hours worked one week followed for each by the hourly pay rate. For example, if the variable stores >> v v = 33.0000 0.5000 40.0000 8.0000 20.0000 7.5000 that means the first employee worked 33 hours at $0.50 per hour, the second worked 40 hours at $8 an hour, and so on. Write code that will separate this into two vectors, one that stores the hours worked and another that stores the hourly rates. Then, use the array multiplication operator to create a vector, storing in the new vector the total pay for every employee. 23. The mathematician Euler proved the following: 6 =+ 4 + 9 + 6 + Rather than finding a mathematical proof for this, try to verify whether the conjecture seems to be true or not. Note: There are two basic ways to approach this: either choose a number of terms to add, or loop until the sum is close to π/6. 24. Write a script that will prompt the user for the radius and height of a cone, error-check the user s input for the radius and the height, and then calculate and print the volume of the cone. 25. Write a script (for example, called findmine) that will prompt the user for minimum and maximum integers, and then another integer that is the user s choice in the range from the minimum to the maximum. The script will then generate random integers in the range from the minimum to the maximum, until a match for the user s choice is generated. The script will print how many random integers had to be generated until a match for the user s choice was found. For example, running this script might result in this output: >> findmine Please enter your minimum value: 2 Please enter your maximum value: 3 Now enter your choice in this range: 0 It took 3 tries to generate your number 28. Write a script that will present the user a menu with choices for functions fix, floor, and ceil. Error-check by looping until the user selects a valid option. Then, generate a random number and print the result of the user s function choice of that number (e.g., fix(5)). Computação e Programação, LEAN, MEMec 3
30. Write a script called prtemps that will prompt the user for a maximum Celsius value in the range from 6 to 20; error-check to make sure it s in that range. Then, print a table showing degrees F and degrees C until this maximum is reached. The first value that exceeds the maximum should not be printed. The table should start at 0 degrees F, and increment by 5 degrees F until the max (in C) is reached. Both temperatures should be printed with a field width of 6 and one decimal place. The formula is C = 5/9 (F 32). For example, the execution of the script might look like this (the format should be exactly like this): >> prtemps When prompted, enter a temp in degrees C in range 6 to 20. Enter a maximum temp: 30 Error! Enter a maximum temp: 9 F C 0.0 7.8 5.0 5.0 0.0 2.2 5.0 9.4 20.0 6.7 25.0 3.9 30.0. 35.0.7 40.0 4.4 45.0 7.2 Nível Exercício 2. Write a for loop that will print the column of real numbers from. to 2.9 in steps of 0.. 4. Write a script called geomser that prompts the user for values of r and n, and will calculate and return the sum of the geometric series: + r + r 2 + r 3 + r 4 +... + r n 27. Write a script that will continue prompting the user for positive numbers, keeping a count of how many numbers were entered, and storing them in a vector variable, until the user types a negative number. 29. Write a script echoletters that will prompt the user for letters of the alphabet and echo-print them until the user enters a character that is not a letter of the alphabet. At that point, the script will print the non-letter, and a count of how many letters were entered. Here are examples of running this script: >> echoletters Enter a letter: T Thanks, you entered a T Enter a letter: a Thanks, you entered a a Enter a letter: 8 8 is not a letter You entered 2 letters >> echoletters Enter a letter:!! is not a letter You entered 0 letters The format must be exactly as shown. Computação e Programação, LEAN, MEMec 4
3 3 9. Write a script beautyofmath that produces the following output. The script should iterate from to 9 to produce the expressions on the left, perform the specified operation to get the results shown on the right, and print exactly in the format shown below: >> beautyofmath x 8 + = 9 2 x 8 + 2 = 98 23 x 8 + 3 = 987 234 x 8 + 4 = 9876 2345 x 8 + 5 = 98765 23456 x 8 + 6 = 987654 234567 x 8 + 7 = 9876543 2345678 x 8 + 8 = 98765432 23456789 x 8 + 9 = 98765432 Escreva um programa que percorra uma-a-uma as linhas de uma matriz de inteiros introduzida pelo utilizador, e que para cada linha apresente o número da primeira coluna onde encontrou o valor -. Se não existir nenhum valor - nessa linha o programa apresentará o valor 0. Por uma questão de eficiência, assim que for encontrado o valor - numa linha o programa deve continuar imediatamente a sua pesquisa na linha seguinte, evitanto perder tempo a percorrer a linha até ao fim. Referências Capítulo 4 do livro de apoio: Matlab: A Practical Introduction to Programming and Problem Solving Apresentação da AT 6 Computação e Programação, LEAN, MEMec 5