PRACTICE
LOOP EXERCISES



Exercises

  1. Write a program to calculate a user’s average grade. Since you won’t know how many classes the user is taking, use an appropriate sentinel value to exit the loop. You will also need to track how many grades they enter so you can calculate the average. Print the average grade.
  2. Write code that prints out a rectangle made of *, which is 4 *’s tall and 6 *’s wide.
  3. Write a program that prompts the user for a word, and then prints out the word in reverse. The program should continue to keep prompting and printing in reverse until the user inputs a “-1”.
  4. Write a program that prompts the user to input 2 positive, integer values. The program should print out the largest number that can divide into both inputted values evenly, with no remainder.
  5. Collatz Conjecture: Start with any natural number (positive whole numbers like 1, 2, 3, 4, ...). If the number is even, divide it by 2. If the number is odd, multiply by 3 then add 1. The result is your new number. If you repeat this process enough times, the number should always reach 1.
    Write a program that tests this conjecture by asking the user to enter a natural number, and then apply the Collatz algorithm above until the number reaches 1. Keep track of how many steps are needed until the number reaches 1. Display the step number and the result of each step until 1 is reached.
  6. Write a program that asks the user for a word and tests to see if the word is a palindrome. The program should print “true” if the word is a palindrome and “false” otherwise. A word is a palindrome if it is spelled the same backwards and forwards. Do not let the user input words that are shorter than 2 characters long. If they do, keep asking the user to input a long enough word until they do.
  7. Caesar Cipher: The Caesar cipher is a basic encryption technique used by Julius Caesar to securely communicate with his generals. Each letter is replaced by another letter, n-positions down the English alphabet. For example, for an n-value of  5, the letter 'c' would be replaced by an 'h'. In case of a 'z', the alphabet rotates and it is transformed into a 'd'.
    Write a program that takes an inputted String from the user, and prints its encryption where n=5.
    (HINT: Try adding and subtracting from char values first)