Class Activities Week 3 Lecture 3
Exercise 1: if
Write a program that asks the user to enter a three letter word. The program should indicate whether the letters in the word are in alphabetical order, reverse alphabetical order, or neither. Sample interaction should look like this:
Enter three letters: aim
The three letters entered are in alphabetical order.
Enter three letters: tub
The three letters entered are in reverse alphabetical order.
Enter three letters: bye
The three letters entered are not in order.
Exercise 2: switch
Suppose you are making a game that needs to control a character on the screen. The following key mappings should be used: h - left, j - down, k - up, l - right. Write a program that accepts a character and prints the appropriate direction. Sample interaction should look like this:
j
down
k
up
h
left
Exercise 3: Rewrite for
loop as while
loop
Rewrite the following for loop as a while loop:
for(int i=1; i<10; i=i+1) { System.out.println(i + "^2 = " + i * i); }
Exercise 4: Loops
Write a program that asks the user to enter a word. The program should indicate whether the letters in the word are in alphabetical order, reverse alphabetical order, or neither. Sample interaction should look like this:
Enter a word: abhors
The letters entered are in alphabetical order.
Enter a word: soon
The letters entered are in reverse alphabetical order.
Enter a word: typical
The letters entered are not in order.
Exercise 5: Loops
Ask the user to enter two integer values: height and width. Your program should then generate a box of *s that is height tall and width wide. Sample interaction may look like this:
Please enter the height: 3
Please enter the width: 5
*****
*****
*****
Exercise 6: Loops
Ask the user to enter a name and print all of the letters in the name, one per line. Include line numbers for the lines. Sample interaction may look like this:
Enter a name: Chris
Letters:
1. C
2. h
3. r
4. i
5. s
Exercise 7: Loops
Ask the user to enter as many positive integers as the user wants followed by a non-positive integer. The program should then display the sum of all positive values that are divisible by 3. Sample interaction may look like this:
Enter a bunch of positive integers followed by a non-positive integer:
1 2 3 4 5 6 7 8 9 10 11 18 0
Answer: 36
Exercise 8: Loops
Suppose you are making a game that needs to control a character on the screen. The following key mappings should be used: h - left, j - down, k - up, l - right. Write a program that accepts a string of characters and generates a sequence of moves. Characters other than the directional characters specified earlier should be ignored. Sample interaction should look like this:
jjlllk
down
down
right
right
right
up
Exercise 9: Loops
Rewrite the program in the previous exercise so that the output matches the sample below.
jjlllk
2 down
3 right
1 up