Sunteți pe pagina 1din 6

Programming Exercises

 If statement exercises
Even or Odd? (PS13L)
Write a program that reads an integer from the user. Then your program should display a message
indicating whether the integer is even or odd.

Dog Years (P22L)


It is commonly said that one human year is equivalent to 7 dog years. However this simple
conversion fails to recognize that dogs reach adulthood in approximately two years. As a result,
some people believe that it is better to count each of the first two human years as 10.5 dog years,
and then count each additional human year as 4 dog years.

Write a program that implements the conversion from human years to dog years described in the
previous paragraph. Ensure that your program works correctly for conversions of less than two
human years and for conversions of two or more human years. Your program should display an
appropriate error message if the user enters a negative number.

Vowel or Consonant (PS16L)


In this exercise you will create a program that reads a letter of the alphabet from the user. If the
user enters a, e, i, o or u then your program should display a message indicating that the entered
letter is a vowel. If the user enters y then your program should display a message indicating that
sometimes y is a vowel, and sometimes y is a consonant. Otherwise your program should display a
message indicating that the letter is a consonant.

Name that Shape (PS31L)


Write a program that determines the name of a shape from its number of sides. Read the number of
sides from the user and then report the appropriate name as part of a meaningful message. Your
program should support shapes with anywhere from 3 up to (and including) 10 sides. If a number of
sides outside of this range is entered then your program should display an appropriate error
message.

Name that Triangle (PS20L)


A triangle can be classified based on the lengths of its sides as equilateral, isosceles or scalene. All
3 sides of an equilateral triangle have the same length. An isosceles triangle has two sides that are
the same length, and a third side that is a different length. If all of the sides have different lengths
then the triangle is scalene. Write a program that reads the lengths of 3 sides of a triangle from the
user. Display a message indicating the type of the triangle.

What Color is that Square? (P22L)


Positions on a chess board are identified by a letter and a number. The letter identifies the column,
while the number identifies the row, as shown below:
Write a program that reads a position from the user. Use an if statement to determine if the column
begins with a black square or a white square. Then use modular arithmetic to report the color of the
square in that row. For example, if the user enters a1 then your program should report that the
square is black. If the user enters d5 then your program should report that the square is white. Your
program may assume that a valid position will always be entered. It does not need to perform any
error checking.

Chinese Zodiac (PS35L)


The Chinese zodiac assigns animals to years in a 12 year cycle. One 12 year cycle is shown in the
table below. The pattern repeats from there, with 2012 being another year of the dragon, and 1999
being another year of the hare.

Year Animal
2000 Dragon
2001 Snake
2002 Horse
2003 Sheep
2004 Mokey
2005 Rooster
2006 Dog
2007 Pig
2008 Rat
2009 Ox
2010 Tiger
2011 Hare

Write a program that reads a year from the user and displays the animal associated with that year.
Your program should work correctly for any year greater than or equal to zero, not just the ones
listed in the table.

 Loop exercises
Sentinel Average (P26L)
In this exercise you will create a program that computes the average of a collection of values
entered by the user. The user will enter 0 as a sentinel value to indicate that no further values will
be provided. Your program should display an appropriate error message if the first value entered by
the user is 0. For example:
10 20 30 40 50 60 0
returns 35 as result.

Hint: Because the 0 marks the end of the input it should not be included in the average.

1/n*11 series
Write a program that reads a value n from the user and then calculates the result of the following
series:

1-1/22+1/33-1/44+1/55-…±1/n*11
Pitagoric Table (P13L)
Write a program that reads an integer n between 1 and 10 and then displays in the screen a
pitagoric table for the numbers from 1 to n. The program must check for errors. For example, if user
puts 3, the program must show:
1 2 3

1 1 2 3

2 2 4 6

3 3 6 9

Sentinel Sum
Write a program that calculates the sum of a sequence of integers read from the user. Suppose that
the first integer entered specifies the remaining numbers to enter. The program must read a number
at a time. A typical sequence of number could be:

5 100 200 300 400 500

where 5 indicates that the next five values will be added.

Hint: Because the first number marks the start of the input it should not be included in the sum.

Sentinel Minimum
Write a program that find the smallest of several integers. Suppose that the first value entered
specifies the remaining number to enter. For example:

5 100 7 89 -35 18
returns 7 as result.
Hint: Because the first number marks the start of the input it should not be included in the
calculation.
 Lists / array exercises

Sorted Order (PS21L)


Write a program that reads integers from the user and stores them in a list. Your program should
continue reading values until the user enters 0. Then it should display all of the values entered by
the user (except for the 0) in order from smallest to largest, with one value appearing on each line.
Use either the sort method or the sorted function to sort the list.

Reverse Order (P20L)


Write a program that reads integers from the user and stores them in a list. Use 0 as a sentinel
value to mark the end of the input. Once all of the values have been read your program should
display them (except for the 0) in reverse order, with one value appearing on each line.

Avoiding Duplicates (PS21L)


In this exercise, you will create a program that reads words from the user until the user enters a
blank line. After the user enters a blank line your program should display each word entered by the
user exactly once. The words should be displayed in the same order that they were entered. For
example, if the user enters:

first
second
first
third
second

then your program should display:

first
second
third

Negatives,Zeros and Positives (PS38L)


Create a program that reads integers from the user until a blank line is entered. Once all of the
integers have been read your program should display all of the negative numbers, followed by all of
the zeros, followed by all of the positive numbers. Within each group the numbers should be
displayed in the same order that they were entered by the user. For example, if the user enters the
values 3, -4, 1, 0, -1, 0, and -2 then your program should output the values -4, -1, -2, 0, 0, 3, and 1.
Your program should display each value on its own line.

Below and Above Average (P44L)


Write a program that reads numbers from the user until a blank line is entered. Your program
should display the average of all of the values entered by the user. Then the program should
display all of the below average values, followed by all of the average values (if any), followed by all
of the above average values. An appropriate label should be displayed before each list of values.

Remove Outliers (PS43L)


When analysing data collected as part of a science experiment it may be desirable to remove the
most extreme values before performing other calculations. Write a function that takes a list of values
and an non-negative integer, n, as its parameters. The function should create a new copy of the list
with the n largest elements and the n smallest elements removed. Then it should return the new
copy of the list as the function’s only result. The order of the elements in the returned list does not
have to match the order of the elements in the original list.

Write a main program that demonstrates your function. Your function should read a list of numbers
from the user and remove the two largest and two smallest values from it. Display the list with the
outliers removed, followed by the original list. Your program should generate an appropriate error
message if the user enters less than 4 values.

Max in position
Write a program that reads a list of number from the user, and then indicates which is the greatest
value and its position in the list.

Filling an array
Write a program defining an array nums that will store 100 numbers initialized like below:

C:
int nums[100] = {1, 3, 5};

Python:
nums = [1, 3, 5]

Although if the array can store 100 numbers, only the first three values have been initialized. Your
program must generates the remaining values integers according to the next formula:

nums[i] = nums[0] + nums[1] + … + nums[i – 1]

for example, for i = 3

nums[3] = nums[0] + nums[1] + nums[2] = 1 + 3 + 5 = 9

After filling every array element, print it.

Matrix by scalar
Realizar la multiplicación de una matriz de mxn por un escalar.

 Functions
Capitalize It (PS48L)
Many people do not use capital letters correctly, especially when typing on small devices like smart
phones. In this exercise, you will write a function that capitalizes the appropriate characters in a
string. A lowercase “i” should be replaced with an uppercase “I” if it is both preceded and followed
by a space. The first character in the string should also be capitalized, as well as the first non-space
character after a “.”, “!” or “?”. For example, if the function is provided with the string “what time do i
have to be there? what’s the address?” then it should return the string “What time do I have to be
there? What’s the address?”. Include a main program that reads a string from the user, capitalizes it
using your function, and displays the result.

Does a String Represent an Integer? (PS30L)


In this exercise you will write a function named isInteger that determines whether or not the
characters in a string represent a valid integer. When determining if a string represents an integer
you should ignore any leading or trailing white space. Once this white space is ignored, a string
represents an integer if its length is at least 1 and it only contains digits, or if its first character is
either + or - and the first character is followed by one or more characters, all of which are
digits.Write a main program that reads a string from the user and reports whether or not it
represents an integer. Ensure that the main program will not run if the file containing your solution is
imported into another program.

Is a Number Prime? (PS28L)


A prime number is an integer greater than 1 that is only divisible by one and itself. Write a function
that determines whether or not its parameter is prime, returning True if it is, and False otherwise.
Write a main program that reads an integer from the user and displays a message indicating
whether or not it is prime. Ensure that the main program will not run if the file containing your
solution is imported into another program.

Twin Primes
Los números “primos gemelos” son aquel par de números primos que difieren por 2; por ejemplo, el
3 y el 5 son números “primos gemelos”. Escriba un programa que imprima todos los números “primos
gemelos” desde 1 hasta el 1000.

Hypotenuse
Defina una función hipotenusa() que calcule la longitud de la hipotenusa de un triángulo rectángulo,
cuando son conocidos dos lados. La función debe tomar dos argumentos del tipo double que son las
longitudes de los lados y regresar la hipotenusa también como double.

Power
Escriba una función potenciaEnteros(base, exponente) que devuelva el valor baseexponente.
Suponga que exponente es un entero positivo, y base es un entero. La función potenciaEnteros
debe utilizar un ciclo para controlar el cálculo.

Múltiplo
Escriba una función multiplo que determine para un par de números, si el segundo de ellos es
múltiplo del primero. La función debe tomar dos argumentos enteros y regresar 1 (verdadero) si el
segundo es un múltiplo del primero, y 0 (falso) de no ser así. Utilice esta función en un programa
que introduzca una serie de pares enteros.

S-ar putea să vă placă și