chapter 4 practice cont.. practice with nested loops 1.what will be the output of the following...

5
Chapter 4 Practice cont.

Upload: tracey-sutton

Post on 14-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 4 Practice cont.. Practice with nested loops 1.What will be the output of the following program segment: 1.for (int i = 1; i

Chapter 4 Practicecont.

Page 2: Chapter 4 Practice cont.. Practice with nested loops 1.What will be the output of the following program segment: 1.for (int i = 1; i

Practice with nested loops

1. What will be the output of the following program segment:

1. for (int i = 1; i <5; i++) {for (int j = 1; j < 5; j++)

System.out.print (2*i+j + “ “);System.out.println();

}2. for (int i = 1; i <5; i++) {

for (int j = 0; j <= i; j++) System.out.print (2*i+j + “ “);

System.out.println();}

Page 3: Chapter 4 Practice cont.. Practice with nested loops 1.What will be the output of the following program segment: 1.for (int i = 1; i

Practice with File input and output

1. Write code that does the following: opens a file named MyName.txt, writes your name to the file, then closes the file.

2. Write code that does the following: opens a file named MyName.txt, reads the first line from the file and displays it, then closes the file.

3. A text file contains a sequence of integers, each in a separate line. Write code that reads this file and displays the sum of all numbers in the file.

Page 4: Chapter 4 Practice cont.. Practice with nested loops 1.What will be the output of the following program segment: 1.for (int i = 1; i

Practice with Random class

1. Write code to display a random number in the interval [0, 1).

2. Write code to display a random number in the interval [0, 100).

3. Write code to display a random number in the interval [13, 19] (teenager)

4. Write code to display a random letter [A..Z]

5. Write code to display a string of 5 random letters.

Page 5: Chapter 4 Practice cont.. Practice with nested loops 1.What will be the output of the following program segment: 1.for (int i = 1; i

Sample Problems

1. The sum S(n) is defined as:S(n) = 1 + ½ + 1/3 + … + 1/n.Write a program that reads a number M from keyboard, then displays the smallest value of n so that S(n) >= M.

2. Write a program to calculate the square root of a non-negative number n, using the while loop. Compare the result with the Math.sqrt() method.

See instructions in class.