Java

TOPIC 23 – FOR LOOPS

 

LESSON WORK

 


PART A – OUTPUTTING NUMBERS

QUESTION 1
Write the program that will output all numbers from 1 to 100 on a separate line using a FOR loop.

QUESTION 2
Write the program that will output every 5th number from 50 to 100 using a FOR loop.

QUESTION 3
Write the program that will output all numbers from 20 to 1 backwards using a FOR loop.

QUESTION 4
Copy your program from Question 2 and alter it so that all numbers are outputted on the same line and separated by commas.

QUESTION 5

Write the program that will output all numbers divisible by 14 between 100 and 200 using a FOR loop.

PART B – SMALL PROGRAMS

QUESTION 6 (NEW 2021)

Write a program that gets two positive integers from the user and calculates, without using Math.pow() or any similar built-in function, the power of the first number raised to the power of the second number.

 

Sample IO 1:

Enter two numbers.

4
2

16

 

Sample IO 2:

Enter two numbers.

3
3

27

 

QUESTION 7 (NEW 2021)

Write a program that uses a FOR loop to calculate the sum of the series below where n is inputted by the user.

 

1 + 1/2 + 1/3 + 1/4 + ... + 1/n


QUESTION 8
Write the program that asks the user for a lower bound and a higher bound.  It then outputs all numbers between the two bounds inclusively.  Once you've completed this, alter your program so that the user is also asked "by how much" like shown below:

Sample output 1:

Enter low bound.
9
Enter high bound.
22
By how much.
4
Here we go:
9
13
17
21


Sample output 2:

Enter low bound.
5
Enter high bound.
10
By how much.
1
Here we go:
5
6
7
8
9

10

 

QUESTION 9
Write the program that asks the user how many numbers they want to add up.  Then, inside a for loop, get the numbers from the user and add them together.  Output the total at the end.

QUESTION 10

Write a program that will ask the user for a number representing rows and the program will then output a rectangle made of asterisks with that many rows.  There should be 4 columns to the rectangle.

 

Sample output 1:

 

     How many rows?
     3

 

     ****
     ****
     ****

 

Sample output 2:

 

     How many rows?

     6

 

     ****
     ****
     ****

     ****
     ****
     ****