Lecture Notes 6, csc211
Prepared by: Anthony Larrain
These notes serve as an outline to the lecture, they are not intended to be complete. You should be reading the assigned sections. During class I may include or omit certain topics.
Finding the average of a sequence of non-negative integers
Write a Java program to compute the average of a set of exam scores rounded to two places.
Use the following pseudocode
Calculator program
Write a program that mimics a calculator. The program should take as input two integers and an arithmetic operation(+,-,* or /) to be performed. It should then output the numbers, the operator, and the result. (For division, if the denominator is 0, output an appropriate message.)
The for statement
- A count controlled construct.
- Typically used when it can be determined the number of times the loop body should execute.
for (initialization; condition; update) {
execute this block if the condition is true
}
// sum of the first positive 100 integers
int i, sum = 0;
for (i = 1; i <= 100; i++){
sum += i; //equivalent to sum = sum + i;
}
- The initialization, condition and update sections are separated by semi colons ;
- The variable i, in the example statement is called a control variable.
- It keeps track of the number of repetitions.
- The increment can be by any amount, positive or negative.
- The initialization component can also include a declaration of the control variable.
int sum = 0;
for (int i = 1; i <= 100; i++){
sum += i; //equivalent to sum = sum + 1;
}
- The control variable can be incremented or decremented by any amount.
// The sum of even integers up to and including 100.
int sum = 0;
for(int i = 2; i <= 100; i += 2) {
sum += i;
}
Blast off
for(int i = 10; i > 0; i--) {
System.out.println(i);
}
System.out.println("Blast Off");
// the first 10 powers of 2
for(int i = 1; i < 10; i++){
System.out.println(Math.pow(2,i));
}