Examples Using the for Structure


for (int i = 1; i <= 100; i++)

for (int i = 100; i >= 1; i--)

for (int i = 7; i <= 77; i += 7)

for (int i = 20; i >= 2; i -= 2)

for (int i = 2; i <= 20; i += 3)

for (int i = 99; i >= 0; i -= 11)


// Counter-controlled repetition with the for structure
import java.awt.Graphics;
import java.applet.Applet;

public class Sum extends Applet {

public void paint( Graphics g )
{

int sum = 0;

for ( int number = 2; number <= 100; number += 2 )

sum += number;

g.drawString( "Sum is " + sum, 25, 25 );

}

}


Consider the following problem.

A person invests $1000 in a savings account yielding 5% interest. Assuming that all interest is left on deposit, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula for determining these amounts:

a = p(1 + r)^n

where

p is the original amount invested

r is the annual interest rate

n is the number of years

a is the amount on deposit at the end of the nth year.