Introduction to Computer Programming Looping Around Loops I: Counting Loops.

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Introduction to Computer Programming Decisions If/Else Booleans.
Scanner Pepper With credits to Dr. Siegfried. The Scanner Class Most programs will need some form of input. At the beginning, all of our input will come.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Introduction to Computer Programming Decisions, Decisions: Boolean Expressions and Selection.
Introduction to Computer Programming Loops N Decisions If/Else Counting Loops.
Computer Science 1620 Programming & Problem Solving.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection Statement 4.6 if else Selection Statement 4.7 while.
Java Variables and Expressions CSC160 Professor Pepper (presentation adapted from Dr. Siegfried)
Introduction to Computer Programming Looping Around Loops II : Conditional Loops.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Moving To Code 3 More on the Problem-Solving Process §The final step in the problem-solving process is to evaluate and modify (if necessary) the program.
Scanner & Stepwise Refinement Pepper With credit to Dr. Siegfried.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Introduction to Computer Programming Counting Loops.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
CSC 270 – Survey of Programming Languages C++ Lecture 1 : C++ As A Better C.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) public static void main(String[]
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1.
Chapter 4: Control Structures II
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
CSC Programming I Lecture 6 September 4, 2002.
Introduction to Computing Concepts Note Set 12. Writing a Program from Scratch public class SampleProgram1 { public static void main (String [] args)
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
 2003 Prentice Hall, Inc. All rights reserved. 1 Will not cover 4.14, Thinking About Objects: Identifying Class Attributes Chapter 4 - Control Structures.
 CSC111 Quick Revision. Problem Write a java code that read a string, then show a list of options to the user to select from them, where:  L to print.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Java Fundamentals 4.
Formatted Output (printf)
Chapter 5: Control Structures II
Repetition-Counter control Loop
Chapter 5: Control Structures II
OUTPUT STATEMENTS GC 201.
INPUT STATEMENTS GC 201.
Control Statement Examples
Introduction to Computer Programming Counting Loops 2
Control Statements Loops.
Introduction to Computer Programming
Examples Example Problems, their Algorithms, and their C Source Code.
Chapter 4 - Control Structures: Part 1
Control Statements Loops.
Repetition Statements
Unit 3: Variables in Java
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
CS 1054 Introduction to Programming in Java
Incremental Programming
Input and Formatted Output (printf)
Getting Started With Coding
Presentation transcript:

Introduction to Computer Programming Looping Around Loops I: Counting Loops

Why loops? Computers offer several advantages over calculators. If it is necessary, they can perform the same steps over and over again, simply by rerunning the program. But is this the only way to get a computer to perform the same action repeatedly? And is this the only reason for getting a computer to repeat itself?

Example : Average of three numbers Let’s take another look at our program that finds the average of three numbers: import java.util.Scanner; public class AverageThree { public static void main(String[] args) { Scanner keyb = new Scanner(System.in); int value1, value2, value3; int sum, average; System.out.println ("What is the first value?"); value1 = keyb.nextInt(); System.out.println ("What is the second value?"); value2 = keyb.nextInt();

Example : Average of three numbers (continued) System.out.println ("What is the third value?"); value3 = keyb.nextInt(); sum = value1 + value2 + value3; average = sum / 3; System.out.println("Average = " + average); } What would we do if we wanted the program to average 5 values instead of 3? or 10? or 100? This is clearly not the best way to write this!

Loops We need the ability to perform the same set of instructions repeatedly so we don’t have to write them over and over again. This is why C++ includes several ways of using repetition in a program. Each case where we repeat a set of statement is called a loop.

Counting Loops The first type of loop is a counting loop. Counting loops are repeated a specific number of times. If you read the loop, you can easily figure out how many times its statements will be performed.

Example: Hello Again Example - Write a program that greets the user with "Hi there!" five times. We could write the program like this: import java.util.Scanner; public class HelloAgain { // Hello again - this program writes "Hello, again" five times public static void main(String[] args) { System.out.println("Hello, again"); }

Counting Loops We use a for loop to write counting loops In Java, it looks like this: for (count = start; count <= finish; count++) statement or for (count = start; count <= finish; count++) { statements }

Counting Loops (continued) for (count = start; count <= finish; count++) statement variable used to count times through the loop initial value of the counter final value of the counter

Example: Rewriting HelloAgain Let's write the steps that our new version of that program must perform: 1.Write "Hi, there!" on the screen 5 times. 1.FOR i goes from 1 TO Write “Hi, there!”

Refining HelloAgain 1.FOR i goes from 1 TO Write “Hi, there!” for (i = 1; i <= 5; i++)

Refining HelloAgain for (i = 1; i <= 5; i++) 1.1 Write “Hi, there!” System.out.println("Hi, there! " );

The New HelloAgain public class HelloAgain2 { // HelloAgain2 - this is a better way to write // "Hello, again" five times public static void main(String[] args) { int i; for (i = 1; i <= 5; i++) System.out.println("Hello, again"); }

Generalizing HelloAgain This program is also flawed; it gives us no choices as to how many times we can print “Hi, there!” We can to let the user select how many times to print the message and making this version of the program more general is fairly easy: Our algorithm will start as: 1.Find out how many time to print the message. 2.Print "Hi, there!" that many times.

Generalizing HelloAgain (continued) 1.Find out how many time to print the message. 2.Print "Hi, there!" that many times. System.out.println("How many times do you want to " + "say \"hello\"?"); totalTimes = keyb.nextInt();

Generalizing HelloAgain (continued) System.out.println("How many times do you want to " + "say \"hello\"?"); totalTimes = keyb.nextInt(); 2.Print "Hi, there!" that many times. 2. FOR Count goes from 1 TO TotalTimes 2.1Write “Hi, there!”

Generalizing HelloAgain (continued) System.out.println ("How many times do you want to " + "say \"hello\" ?"; totalTimes = keyb.nextInt(); 2. FOR Count goes from 1 TO TotalTimes 2.1 Write “Hi, there!” for (count = 0; count < totalTimes; count++) System.out.println("Hello, again");

The Revised HelloAgain import java.util.Scanner; public class HelloAgain3 { // HelloAgain3 - Write "Hello, again" as many times // as the user wants public static void main(String[] args) { Scanner keyb = new Scanner(System.in); int i, count, totalTimes; System.out.println("How many times do you want to " + "say \"hello\"?"); totalTimes = keyb.nextInt(); for (count = 0; count < totalTimes; count++) System.out.println("Hello, again"); }

Example: Averaging n Numbers Let's get back to our original problem. We want to able to average any number of values. Let's start by outlining our algorithm: 1.Find out how many values there are. 2.Add up all the values. 3.Divide by the number of values 4.Print the result

Refining Avgn 1.Find out how many values there are. 2.Add up all the values. 3.Divide by the number of values 4.Print the result System.out.println ("How many values are you going to enter?"); numValues = keyb.nextInt();

Refining Avgn System.out.println ("How many values are you going to enter?"); numValues = keyb.nextInt(); 2.Add up all the values. 3.Divide by the number of values 4.Print the result 2.1 For CurrentValue goes from 1 to NumValues : 2.1.1Get the next value 2.1.2Add it to the total

Refining Avgn System.out.println ("How many values are you going to enter?"); numValues = keyb.nextInt(); 2.1 For CurrentValue goes from 1 to NumValues : 2.1.1Get the next value 2.1.2Add it to the total 3.Divide by the number of values 4.Print the result 2.0 Set the total to zero (initially there are no values)

Refining Avgn System.out.println ("How many values are you going to enter?"); numValues = keyb.nextInt(); 2.0 Set the total to zero (initially there are no values) 2.1 For CurrentValue goes from 1 to NumValues : 2.1.1Get the next value 2.1.2Add it to the total 3.Divide by the number of values 4.Print the result 2.0 Set the total to zero (initially there are no values)

Refining Avgn System.out.println ("How many values are you going to enter?"); numValues = keyb.nextInt(); 2.0 Set the total to zero (initially there are no values) 2.1 For CurrentValue goes from 1 to NumValues : 2.1.1Get the next value 2.1.2Add it to the total 3.Divide by the number of values 4.Print the result sum = 0.0; for (currentValue = 1; currentValue <= numValues; currentValue++) { System.out.println("What is the next value?"); value = keyb.nextInt(); sum = sum + value; }

Refining Avgn System.out.println ("How many values are you going to enter?"); numValues = keyb.nextInt(); sum = 0.0; for (currentValue = 1; currentValue <= numValues; currentValue++) { System.out.println("What is the next value?"); value = keyb.nextInt(); sum = sum + value; } 3.Divide by the number of values 4.Print the result average = sum / numValues; System.out.println("The average is " + average);

The AverageN Program import java.util.Scanner; public class AverageN { //AverageN - Find the average of N values public static void main(String[] args) { Scanner keyb = new Scanner(System.in); double sum, average, value; int numValues, currentValue; //Find out how many values there are System.out.println ("How many values are you going to enter?"); numValues = keyb.nextInt();

// Read in each value and add it to the sum sum = 0.0; for (currentValue = 1; currentValue <= numValues; currentValue++) { System.out.println("What is the next value?"); value = keyb.nextInt(); sum = sum + value; } // Calculate and print out the average average = sum / numValues; System.out.println("The average is " + average); }

Example: Interest Program Example - Write a program that calculates the interest that the Canarsie Indians would have accumulated if they had put the $24 that they had received for Manhattan Island in the bank at 5% interest. Input - none; all the values are fixed Output - Year and Principle Other Information - Principle is initially 24 Interest = Interest Rate * Principle New Principle = Old Principle + Interest

Example: Interest Program Our initial algorithm is: 1.Set the principle to 24 2.For every year since 1625, add 5% interest to the principle and print out the principle.

Refining The Interest Algorithm 1.Set the principle to 24 2.For every year since 1625, add 5% interest to the principle and print out the principle. 2.1FOR Year goes from 1625 TO Present: 2.1.1Add 5% interest to the principle 2.1.2Print the current principle

Refining The Interest Algorithm 1.Set the principle to FOR Year goes from 1625 TO Present: 2.1.1Add 5% interest to the principle 2.1.2Print the current principle Calculate 5% Interest Add the interest to the principle

Refining The Interest Algorithm 1.Set the principle to FOR Year goes from 1625 TO Present: Calculate 5% Interest Add the interest to the principle 2.1.2Print the current principle principle = 24;

Refining The Interest Algorithm principle = 24; 2.1FOR Year goes from 1625 TO Present: Calculate 5% Interest Add the interest to the principle 2.1.2Print the current principle for (year = 1625; year < present; year++){ }

Refining The Interest Algorithm principle = 24; for (year = 1625; year < present; year++){ Calculate 5% Interest Add the interest to the principle 2.1.2Print the current principle } interest = rate * principle; principle = principle + interest;

Refining The Interest Algorithm principle = 24; for (year = 1625; year < present; year++) { interest = rate * principle; principle = principle + interest; 2.1.2Print the current principle } System.out.println("year = " + year + "\tprinciple = “ + principle);

The Interest Program public class Interest { // Calculate the interest that the Canarsie // Indians could have accrued if they had // deposited the $24 in an bank account at // 5% interest. public static void main(String[] args) { final int present = 2005; int year; final double rate = 0.05; double interest, principle; // Set the initial principle at $24 principle = 24;

// For every year since 1625, add 5% interest // to the principle and print out // the principle for (year = 1625; year < present; year++) { interest = rate * principle; principle = principle + interest; System.out.println("year = " + year + "\tprinciple = " + principle); }

Output from the Compound Interest Program What will our output look like? year = 1625principle = 25.2 year = 1626principle = year = 1627principle = year = 1628principle = … … … … … year = 2001principle = E9 year = 2002principle = E9 year = 2003principle = E9 year = 2004principle = E9 This does not look the way we expect monetary amounts to be written!

System.out.printf() The method System.out.printf() gives us a way to write output that is formatted, i.e., we can control its appearance. We write the method: System.out.printf(ControlString, Arg1, Arg2,... ) The control string is a template for our output, complete with the text that will appear along with whatever values we are printing.

System.out.printf() : Some Simple Examples System.out.printf() will print whatever is in the control string with a few exceptions: System.out.printf("This is a test"); System.out.printf("This is a test"). will produce: This is a testThis is a test If you want these to be on two separate lines: System.out.printf("This is a test\n"); System.out.printf("This is a test\n").

Special Characters There are a number of special characters that all begin with a backslash: –\n new line –\b backspace –\t tab These can appear anywhere with a string of characters: System.out.printf("This is a test\nIt is!!\n");

%d and %f The specifiers %d and %f allow a programmer to specify how many spaces a number will occupy and (in the case of float values) how many decimal places will be used. %nd will use at least n spaces to display the integer value in decimal (base 10) format. %w.df will use at least w spaces to display the value and will have exactly d decimal places.

Changing the width ```-182 %7d -182 `-182 %5d -182 %4d -182 ``182 %7d 182 ``182 %5d 182 %3d 182 %2d 182 Print as:FormattingNumber

Changing the width (continued) … %10d %6d %6d11023 %4d11023 ……23%8d23 ….23%6d23 %2d23 %1d23 Print as:FormattingNumber

Changing The Precision NumberFormattingPrints as: %8.5f ` %8.3f ``` %8.2f ```` %8.0f ```````` %13.11f %13.12f

The revised Compound program public class Interest2 { // Calculate the interest that the Canarsie // Indians could have accrued if they had // deposited the $24 in an bank account at // 5% interest. public static void main(String[] args) { final int present = 2005; int year; final double rate = 0.05; double interest, principle; // Set the initial principle at $24 principle = 24;

// For every year since 1625, add 5% interest // to the principle and print out // the principle for (year = 1625; year < present; year++) { interest = rate * principle; principle = principle + interest; System.out.printf ("year = %4d\tprinciple = $%13.2f\n", year, principle); }

The output from the Revised Compound Program Our output now looks like this: year = 1625principle = $ year = 1626principle = $ year = 1627principle = $ year = 1628principle = $ … … … … … … … … … … … … … … … year = 2001principle = $ year = 2002principle = $ year = 2003principle = $ year = 2004principle = $

Integer Division Our compound interest program prints the values for every year where every ten or twenty years would be good enough. What we really want to print the results only if the year is ends in a 5. (The remainder from division by 10 is 5).

Integer Division (continued) Division of an integer by an integer produces an integer quotient: 5/3 = 1R216/3 = 5R1 6/2 = 3R015/4 = 3R3 quotient remainder

Integer Division (continued) In Java, the / operator produces n integer quotient for integer division. If you want the remainder from integer division, you want to use the % operator

public class DivTest { public static void main(String[] args) { // A few examples of integer division using // / and % System.out.println("8 / 3 = " + 8 / 3 ); System.out.println("8 % 3 = " + 8 % 3 ); System.out.println("2 / 3 = " + 2 / 3 ); System.out.println("2 % 3 = " + 2 % 3 ); System.out.println("49 / 3 = " + 49 / 3 ); System.out.println("49 % 3 = " + 49 % 3 ); System.out.println("49 / 7 = " + 49 / 7 ); System.out.println("49 % 7 = " + 49 % 7 ); System.out.println("-8 / 3 = " + -8 / 3 ); System.out.println("-8 % 3 = " + -8 % 3 );

System.out.println("-2 / 3 = " + -2 / 3 ); System.out.println("-2 % 3 = " + -2 % 3 ); System.out.println("-2 / -3 = " + -2 / -3 ); System.out.println("-2 % -3 = " + -2 % -3 ); System.out.println("2 / -3 = " + 2 / -3 ); System.out.println("2 % -3 = " + 2 % -3 ); System.out.println("-49 / 3 = " / 3 ); System.out.println("-49 % 3 = " % 3 ); System.out.println("-49 / -3 = " / -3 ); System.out.println("-49 % -3 = " % -3 ); System.out.println("49 / -3 = " + 49 / -3 ); System.out.println("49 % -3 = " + 49 % -3 );

System.out.println("-49 / 7 = " / 7 ); System.out.println("-49 % 7 = " % 7 ); System.out.println("-49 / -7 = " / -7 ); System.out.println("-49 % -7 = " % -7 ); System.out.println("49 / -7 = " + 49 / -7 ); System.out.println("49 % -7 = " + 49 % -7 ); }

Integer Division Results -49 % 3 = / 3 = %-3 = 22 / -3 = 0 -2 % -3 = -2-2 / -3 = 0 -2 % 3 = -2-2 / 3 = 0 -8 % 3 = -2-8 / 3 = % 7 = 049 / 7 = 7 49 % 3 = 149 / 3 = 16 2 % 3 = 22 / 3 = 0 8 % 3 = 28 / 3 = 2

Integer Division Results (continued) -49 % 7 = 0-49 / 7 = % -3 = 149 / -3 = % -3 = / -3 = 16

Final Compound Interest Program public class Interest3 { // Calculate the interest that the Canarsie // Indians could have accrued if they had // deposited the $24 in an bank account at // 5% interest. public static void main(String[] args) { final int present = 2005; int year; final double rate = 0.05; double interest, principle; // Set the initial principle at $24 principle = 24;

// For every year since 1625, add 5% interest // to the principle and print out // the principle for (year = 1625; year < present; year++) { interest = rate * principle; principle = principle + interest; // Print the principle for every 20th year if (year % 20 == 5) System.out.printf ("year = %4d\tprinciple = $%13.2f\n", year, principle); } // Print te values for the last year System.out.printf ("year = %4d\tprinciple = $%13.2f\n", year, principle); }

A program to calculate Grade Point Average Example – Professor Smith gives n tests during the term and uses a grading system, where each test is 1/n of the course grade. Assuming that that the average of the test grades translate into a letter grade as follows: Test AverageLetter Grade 90.0+A B C D below 60.0F write a program that will calculate a student's grade.

A Program To Calculate Test Average Input - Number of tests and the student's test grades Output – Test average and course grade Other information A 90+ average is an “A”. A average is a “B”. A average is a “C”. A average is a “D” An average below 60 is an “F”. Test average = Sum of the test grade/ Number of tests Our first step is to write out our initial algorithm: 1.Find the number of tests 2.Find the average of n tests 3.Find the corresponding letter grade and print it out.

Designing the Grade Program 1.Find the number of tests 2.Find the average of n tests 3.Find the corresponding letter grade and print it out. 1.1Prompt the user for number of tests 1.2Read the number of tests

Refining the Grade Program 1.1Prompt the user for number of tests 1.2Read the number of tests 2.Find the average of n tests 3.Find the corresponding letter grade and print it out. 2.1Add up the test grades 2.2Divide the total by n

Refining the Grade Program 1.1Prompt the user for number of tests 1.2Read the number of tests 2.1Add up the test grades 2.2Divide the total by n 3.Find the corresponding letter grade and print it out. 2.1For each of the n tests: 2.1.1Prompt the user for the test grade 2.1.2Read the test grade 2.1.3Add it to the total

Refining the Grade Program 1.1Prompt the user for number of tests 1.2Read the number of tests 2.1For each of the n tests: 2.1.1Prompt the user for the test grade 2.1.2Read the test grade 2.1.3Add it to the total 2.2Divide the total by n 3.Find the corresponding letter grade and print it out. System.out.println ("How many tests did you take ?"); numTests = keyb.nextInt();

Refining the Grade Program System.out.println ("How many tests did you take ?"); numTests = keyb.nextInt(); 2.1For each of the n tests: 2.1.1Prompt the user for the test grade 2.1.2Read the test grade 2.1.3Add it to the total 2.2Divide the total by n 3.Find the corresponding letter grade and print it out. for (thisTest = 0; thisTest < numTests; thisTest++) {

Refining the Grade Program System.out.println ("How many tests did you take ?"); numTests = keyb.nextInt(); for (thisTest = 0; thisTest < numTests; thisTest++) { 2.1.1Prompt the user for the test grade 2.1.2Read the test grade 2.1.3Add it to the total } 2.2Divide the total by n 3.Find the corresponding letter grade and print it out. System.out.println ("What grade did you get on this test ?"); thisGrade = keyb.nextInt();

Refining the Grade Program System.out.println ("How many tests did you take ?"); numTests = keyb.nextInt(); for (thisTest = 0; thisTest < numTests; thisTest++) { System.out.println ("What grade did you get on this test ?"); thisGrade = keyb.nextInt(); 2.1.3Add it to the total } 2.2Divide the total by n 3.Find the corresponding letter grade and print it out. total = total + thisGrade;

Refining the Grade Program System.out.println ("How many tests did you take ?"); numTests = keyb.nextInt(); for (thisTest = 0; thisTest < numTests; thisTest++) { System.out.println ("What grade did you get on this test ?"); thisGrade = keyb.nextInt(); total = total + thisGrade; } 2.2Divide the total by n 3.Find the corresponding letter grade and print it out. testAverage = total/numTests;

Refining the Grade Program System.out.println ("How many tests did you take ?"); numTests = keyb.nextInt(); for (thisTest = 0; thisTest < numTests; thisTest++) { … … } testAverage = total/numTests; 3.Find the corresponding letter grade and print it out. 3.1 IF Average >= 90 THEN Grade = ‘A’ 3.2 ELSE IF Average >= 80 THEN Grade = ‘B’ 3.3 ELSE IF Average >= 70 THEN Grade = ‘C’ 3.4 ELSE IF Average >= 60 THEN Grade = ‘D’ 3.2 ELSE Grade = ‘F’

Refining the Grade Program … testAverage = total/numTests; 3.1 IF Average >= 90 THEN Grade = ‘A’ 3.2 ELSE IF Average >= 80 THEN Grade = ‘B’ 3.3 ELSE IF Average >= 70 THEN Grade = ‘C’ 3.4 ELSE IF Average >= 60 THEN Grade = ‘D’ 3.2 ELSE Grade = ‘F’ if (testAverage >= 90) courseGrade = 'A'; else if (testAverage >= 80) courseGrade = 'B'; else if (testAverage >= 70) courseGrade = 'C'; else if (testAverage >= 60) courseGrade = 'D'; else courseGrade = 'F';

Our program public static void main(String[] args) { Scanner keyb = new Scanner(System.in); int thisTest, numTests, total, thisGrade; float testAverage; char courseGrade; // Find out the number of classes System.out.println ("How many tests did you take ?"); numTests = keyb.nextInt(); for (thisTest = 0; thisTest < numTests; thisTest++) { System.out.println ("What grade did you get on this test ?"); thisGrade = keyb.nextInt();

// Make sure that the grades are valid // percentages total = total + thisGrade; } // Find the average testAverage = total/numTests; // Find the letter grade corresponding to the // average if (testAverage >= 90) courseGrade = 'A'; else if (testAverage >= 80) courseGrade = 'B'; else if (testAverage >= 70) courseGrade = 'C'; else if (testAverage >= 60) courseGrade = 'D'; else courseGrade = 'F';

// Print the results. System.out.println ("Your test average is " + testAverage); System.out.println ("Your grade will be " + courseGrade); }

One Last Refinement A test score must be between 0 and 100; therefore any grade greater than 100 or else than 0 is invalid. Let’s test each grade to make sure it’s valid. Also, we have to initialize the total to zero before we do any addition.

The Final Grade Program import java.util.Scanner; public class CalcGrade { // Calculates the average test grade and // converts it to a letter grade assuming that // A is a 90 average, B is an 80 average and so // on.that public static void main(String[] args) { Scanner keyb = new Scanner(System.in); int thisTest, numTests, total, thisGrade; float testAverage; char courseGrade; // Find out the number of classes System.out.println ("How many tests did you take ?"); numTests = keyb.nextInt();

//Add up the test grades total = 0; for (thisTest = 0; thisTest < numTests; thisTest++) { System.out.println ("What grade did you get on this test ?"); thisGrade = keyb.nextInt(); // Make sure that the grades are valid // percentages if (thisGrade > 100) System.out.println ("This is not a valid test grade."); else if (thisGrade >= 0) total = total + thisGrade; else System.out.println ("This is not a valid test grade."); }

// Find the average testAverage = total/numTests; // Find the letter grade corresponding to the // average if (testAverage >= 90) courseGrade = 'A'; else if (testAverage >= 80) courseGrade = 'B'; else if (testAverage >= 70) courseGrade = 'C'; else if (testAverage >= 60) courseGrade = 'D'; else courseGrade = 'F';

// Print the results. System.out.println ("Your test average is " + testAverage); System.out.println ("Your grade will be " + courseGrade); }