CSC 160 Introduction to Programming for Non-majors. Lecture 4 - Looping Around Loops I: Counting Loops. Why loops?

Similar documents
Introduction to Computer Programming

Introduction to Computer Programming

Program Design Phase. Algorithm Design - Mathematical. Algorithm Design - Sequence. Verify Algorithm Y = MX + B

CSC 270 Survey of Programming Languages

Add Subtract Multiply Divide

People = End Users & Programmers. The Web Browser Application. Program Design Phase. Algorithm Design -Mathematical Y = MX + B

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

introjs.notebook March 02, 2014

CMPT 100 : INTRODUCTION TO

c122mar413.notebook March 06, 2013

JAVASCRIPT LOOPS. Date: 13/05/2012 Page: 1 Total Chars: 4973 Total Words: 967

Number Systems and Binary Arithmetic. Quantitative Analysis II Professor Bob Orr

Adding and Subtracting with Decimals

Exercise 1: Basic HTML and JavaScript

cs1114 REVIEW of details test closed laptop period

CITS1231 Web Technologies. JavaScript

COMP 110 Practice Exercises for Midterm Solutions

PIC 40A. Lecture 10: JS: Wrapper objects, Input and Output, Control structures, random numbers. Copyright 2011 Jukka Virtanen UCLA 1 04/24/17

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

Chapter 9 - JavaScript: Control Structures II

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Flow of Control. Relational Operators. Operators Review. Order of Operations

CSC Web Programming. Introduction to JavaScript

Chapter 4 Section 2 Operations on Decimals

A340 Laboratory Session #5

Repetition Algorithms

function makeline(length, ch){ var str = ""; if (length >= 3)

Lab 2: Structured Program Development in C

CS1100 Introduction to Programming

Chapter 2 C++ Fundamentals

Lab 2 Population. Purpose. Assignment Lab 2 analyzes population growth of a town as well as compare the population growth of two towns.

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

CS 1803 Pair Homework 3 Calculator Pair Fun Due: Wednesday, September 15th, before 6 PM Out of 100 points

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Example 2: Simplify each of the following. Round your answer to the nearest hundredth. a

Structured Program Development

Chapter 3 Problem Solving and the Computer

Enhancing Web Pages with JavaScript

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

A.A. 2008/09. Why introduce JavaScript. G. Cecchetti Internet Software Technologies

Chapter4: HTML Table and Script page, HTML5 new forms. Asst. Prof. Dr. Supakit Nootyaskool Information Technology, KMITL

Divide: Paper & Pencil

Chapter 2 - Control Structures

ITEC136 - Lab 2 Population

(Refer Slide Time: 00:26)

Chapter 10 JavaScript/JScript: Control Structures II 289

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

Chapter 7: Javascript: Control Statements. Background and Terminology. Background and Terminology. Background and Terminology

Division. Reverse Box Method

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Chapter 3 Structured Program Development

CHAPTER 6 JAVASCRIPT PART 1

Lab 1 Concert Ticket Calculator

JavaScript: Control Statements I Pearson Education, Inc. All rights reserved.

Concept Fourth Grade: Second Nine Weeks Readiness Standards Time Key Content Key Vocabulary

Concept Fourth Grade: Second Nine Weeks *Revised 5/21/15 Readiness Standards Time Key Content Key Vocabulary

Like most objects, String objects need to be created before they can be used. To create a String object, we can write

CSC 120 Computer Science for the Sciences. Week 1 Lecture 2. UofT St. George January 11, 2016

For loops and Window Objects:

Lecture Transcript While and Do While Statements in C++

Stepwise Refinement. Lecture 12 COP 3014 Spring February 2, 2017

var num1 = prompt("enter a number between 1 and 12","1"); var promptstring = "What is " + num1 + " times 3?"; var num2 = prompt(promptstring);

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

By the end of this section of the practical, the students should be able to:

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Chapter 3 Structured Program Development in C Part II

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Unit: Rational Number Lesson 3.1: What is a Rational Number? Objectives: Students will compare and order rational numbers.

Chapter 16. JavaScript 3: Functions Table of Contents

Working with JavaScript

JavaScript: Control Statements I

CHAPTER 2 Number Systems

Q1: Multiple choice / 20 Q2: C input/output; operators / 40 Q3: Conditional statements / 40 TOTAL SCORE / 100 EXTRA CREDIT / 10

Chapter 2 Working with Data Types and Operators

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Data Representation. Interpreting bits to give them meaning. Part 1: Numbers, Bases, and Binary

SUMMER REVIEW PACKET 2 FOR STUDENTS ENTERING ALGEBRA 1

2 Number Systems 2.1. Foundations of Computer Science Cengage Learning

Fundamentals of Programming. Lecture 6: Structured Development (part one)

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

. As x gets really large, the last terms drops off and f(x) ½x

COSC 122 Computer Fluency. Programming Basics. Dr. Ramon Lawrence University of British Columbia Okanagan

Adding and Subtracting Integers

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

JavaScript Introduction

CSCE 120: Learning To Code

COMP 202 Java in one week

CSc 110, Spring 2017 Lecture 3: Expressions, Variables and Loops. Adapted from slides by Marty Stepp and Stuart Reges

CPSC 101 Sample Final Exam Questions

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

The. Binary. Number System

Looping Subtasks. We will examine some basic algorithms that use the while and if constructs. These subtasks include

CS 115 Lecture 8. Selection: the if statement. Neil Moore

1. The keyword main in C language is used for

Transcription:

CSC 160 Introduction to Programming for Non-majors Lecture 4 - 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: <html> <body> <script type="text/javascript"> var sum, average; var value1, value2, value3; value1 = parseint(prompt ("What is the first value?", 0)); value2 = parseint(prompt ("What is the second value?", 0)); Example : Average of three numbers (continued) value3 = parseint(prompt ("What is the third value?", 0)); sum = value1 + value2 + value3; average = sum / 3; alert("the average is " + average); </script> </body> </html> 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 JavaScript 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: <html> <body> <script type="text/javascript"> // Hello again - This program writes "Hello, // again" five times document.write("<p>hello, again</p>"); document.write("<p>hello, again</p>"); document.write("<p>hello, again</p>"); document.write("<p>hello, again</p>"); document.write("<p>hello, again</p>"); </script> </body> </html> Counting Loops We use a for loop to write counting loops In JavaScript, 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 5 1.1 Write Hi, there!

Refining HelloAgain 1. FOR i goes from 1 TO 5 1.1 Write Hi, there! for (i = 1; i <= 5; i++) Refining HelloAgain for (i = 1; i <= 5; i++) 1.1 Write Hi, there! document.write("<p>hi, there!</p>");

The New HelloAgain <html> <body> <script type="text/javascript"> // HelloAgain2 - this is a better way to // write"hello, again" five // times var i; for (i = 1; i <= 5; i++) document.write("<p>hello, again</p>"); </script> </body> </html> 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. totaltimes = parseint(prompt ("How many times do you want to say \"hello\"?", 0)); Generalizing HelloAgain (continued) totaltimes = parseint(prompt ("How many times do you want to say \"hello\"?", 0)); 2. Print "Hi, there!" that many times. 2. FOR Count goes from 1 TO TotalTimes 2.1 Write Hi, there!

Generalizing HelloAgain (continued) totaltimes = parseint(prompt ("How many times do you want to say \"hello\"?", 0)); 2. FOR Count goes from 1 TO TotalTimes 2.1 Write Hi, there! for (count = 0; count < totaltimes; count++) document.write( <p>hello, again</p>"); The Revised HelloAgain <html> <body> <script type="text/javascript"> // HelloYetAgain - Write "Hello, again" as many // times as the user wants var i, count, totaltimes; totaltimes = parseint(prompt ("How many times do you want to say \"hello\"?", 0)); for (count = 0; count < totaltimes; count++) document.write("<p>hello, again</p>"); </script> </body> </html>

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 numvalues = parseint(prompt( "How many values are you going to enter?", 0));

numvalues = parseint(prompt( "How many values are you going to enter?", 0)); 2. Add up all the values. 3. Divide by the number of values 4. Print the result 2. For CurrentValue goes from 1 to NumValues : 2.1 Get the next value 2.2 Add it to the total numvalues = parseint(prompt( "How many values are you going to enter?", 0)); 2.1 For CurrentValue goes from 1 to NumValues : 2.1.1 Get the next value 2.1.2 Add 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)

numvalues = parseint(prompt( "How many values are you going to enter?", 0)); 2.0 Set the total to zero (initially there are no values) 2.1 For CurrentValue goes from 1 to NumValues : 2.1.1 Get the next value 2.1.1 Add it to the total 3. Divide by the number of values 4. Print the result sum = 0.0; for (currentvalue = 1; currentvalue <= numvalues; currentvalue++) { value = parseint(prompt( "What is the next value?", 0)); sum = sum + value; } numvalues = parseint(prompt( "How many values are you going to enter?", 0)); sum = 0.0; for (currentvalue = 1; currentvalue <= numvalues; currentvalue++) { value = parseint(prompt( "What is the next value?", 0)); sum = sum + value; } 3. Divide by the number of values 4. Print the result average = sum / numvalues; alert("the average is " + average);

The AverageN Program <html> <body> <script type="text/javascript"> // AverageN - Find the average of N values var sum, average, value; var numvalues, currentvalue; // Find out how many values there are numvalues = parseint(prompt( "How many values are you going to enter?", 0)); sum // Read in each value and add it to the sum = 0.0; for (currentvalue = 1; currentvalue <= numvalues; currentvalue++) { value = parseint(prompt( "What is the next value?", 0)); } sum = sum + value; // Calculate and print out the average average = sum / numvalues; alert("the average is " + average); </script> </body> </html>

} } // 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.1 FOR Year goes from 1625 TO Present: 2.1.1 Add 5% interest to the principle 2.1.2 Print the current principle

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

Refining The Interest Algorithm principle = 24; 2.1 FOR Year goes from 1625 TO Present: 2.1.1.1 Calculate 5% Interest 2.1.1.2 Add the interest to the principle 2.1.2 Print the current principle for (year = 1625; year < present; year++) { } Refining The Interest Algorithm principle = 24; for (year = 1625; year < present; year++) { 2.1.1.1 Calculate 5% Interest 2.1.1.2 Add the interest to the principle 2.1.2 Print 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.2 Print the current principle } document.write("<tr> <td>" + year + "</td> <td align=\"right\">" + principle + "</td> </tr>"); <html> <body> The Interest Program <script type="text/javascript"> // Calculate the interest that the Canarsie // Indians could have accrued if they had // deposited the $24 in an bank account at // 5% interest. const present = 2005; var year; var rate = 0.05, 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 document.write("<table border=\"1\">\n"); document.write("<tr> <th> Year </th>"); document.write(" <th> Principle </th>" + " </tr>\n"); for (year = 1625; year < present; year++) { interest = rate * principle; principle = principle + interest; document.write("<tr> <td>" + year + "</td> <td align=\"right\">" + principle + "</td> </tr>"); } document.write("</table>"); </script> </body> </html> Output from the Compound Interest Program What will our output look like? year = 1625 principle = 25.2 year = 1626 principle = 26.46 year = 1627 principle = 27.783 year = 1628 principle = 29.172150000000002 year = 2001 principle = 2.3365602874289446E9 year = 2002 principle = 2.4533883018003917E9 year = 2003 principle = 2.5760577168904114E9 year = 2004 principle = 2.704860602734932E9 This does not look the way we expect monetary amounts to be written!

tofixed() The method tofixed() gives us a way to write floating point numbers that are formatted, i.e., we can control how many decimal places are used. We write the method: variablename.tofixed(numplaces); We can use this as if it were another value in the program, but the value is rounded to to numplaces decimal places tofixed()- Some Simple Examples We can use document.write or alert to print any value rounded off with tofixed(): document.write("the average is " + average.tofixed(2); alert("the average is " + average.tofixed(2);

Changing The Precision Number tofixed(n) Prints as: 2.718281828 5 2.71828 2.718281828 3 2.718 2.718281828 2 2.72 2.718281828 0 3 2.718281828 11 2.71828182800 2.718281828 12 2.718281828000 The revised Compound program <html> <body> <script type="text/javascript"> // Calculate the interest that the Canarsie // Indians could have accrued if they had // deposited the $24 in an bank account at // 5% interest. const present = 2005; var year; var rate = 0.05, 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 document.write("<table border=\"1\">\n"); document.write("<tr> <th> Year </th> " + " <th> Principle </th> </tr>\n"); for (year = 1625; year < present; year++) { interest = rate * principle; principle = principle + interest; document.write("<tr> <td>" + year + "</td> <td align=\"right\">" + principle.tofixed(2) + "</td> </tr>"); } document.write("</table>"); </script> </body> </html> The output from the Revised Compound Program Our output now looks like this: year = 1625 principle = $ 25.20 year = 1626 principle = $ 26.46 year = 1627 principle = $ 27.78 year = 1628 principle = $ 29.17 year = 2001 principle = $2336560287.43 year = 2002 principle = $2453388301.80 year = 2003 principle = $2576057716.89 year = 2004 principle = $2704860602.73

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 20 is 5). Integer Division (continued) What we really want is the remainder from integer division 5/3 = 1R2 16/3 = 5R1 6/2 = 3R0 15/4 = 3R3 quotient remainder

Integer Division (continued) In JavaScript, the / operator produces a floating point quotient evenfor integer division. But if you want the remainder from integer division, you can use the % operator <html> <title>a test</title> <body> <script type = "text/javascript"> // A few examples of integer division using // % document.write("<p>8 / 3 = " + 8 / 3 document.write("<p>8 % 3 = " + 8 % 3 document.write("<p>2 / 3 = " + 2 / 3 document.write("<p>2 % 3 = " + 2 % 3 document.write("<p>49 / 3 = " + 49 / 3 document.write("<p>49 % 3 = " + 49 % 3

document.write("<p>49 / 7 = " + 49 / 7 document.write("<p>49 % 7 = " + 49 % 7 document.write("<p>-8 / 3 = " + -8 / 3 document.write("<p>-8 % 3 = " + -8 % 3 document.write("<p>-2 / 3 = " + -2 / 3 document.write("<p>-2 % 3 = " + -2 % 3 document.write("<p>-2 / -3 = " + -2 / -3 document.write("<p>-2 % -3 = " + -2 % -3 document.write("<p>2 / -3 = " + 2 / -3 document.write("<p>2 % -3 = " + 2 % -3 document.write("<p>-49 / 3 = " + -49 / 3 document.write("<p>-49 % 3 = " + -49 % 3 document.write("<p>-49 / -3 = " + -49 / -3 document.write("<p>-49 % -3 = " + -49 % -3 document.write("<p>49 / -3 = " + 49 / -3 document.write("<p>49 % -3 = " + 49 / -3

document.write("<p>-49 / 7 = " + -49 / 7 document.write("<p>-49 % 7 = " + -49 % 7 document.write("<p>-49 / -7 = " + -49 / -7 document.write("<p>-49 % -7 = " + -49 % -7 document.write("<p>49 / -7 = " + 49 / -7 document.write("<p>49 % -7 = " + 49 % -7 </script> </body> </html> Integer Division Results 8 % 3 = 2 2 % 3 = 2 49 % 3 = 1 49 % 7 = 0-8 % 3 = -2-2 % 3 = -2-2 % -3 = -2 2 % -3 = 2-49 % 3 = -1

Final Compound Interest Program <html> <body> <script type="text/javascript"> // Calculate the interest that the Canarsie // Indians could have accrued if they had // deposited the $24 in an bank account at // 5% interest. const present = 2005; var year; var rate = 0.05, 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 document.write("<table border=\"1\">\n"); document.write("<tr> <th> Year </th> " + "<th> Principle </th> </tr>\n"); for (year = 1625; year < present; year++) { interest = rate * principle; principle = principle + interest; } // Print the principle for every 20th year if (year % 20 == 5) document.write("<tr> <td>" + year + "</td> <td align=\"right\">" + principle.tofixed(2) + "</td> </tr>");

// Print the values for the last year document.write("<tr> <td>" + year + "</td> <td align=\"right\">" + principle.tofixed(2) + "</td> </tr>"); document.write("</table>"); </script> </body> </html> 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 Average 90.0+ A 80-89.9 B 70-79.9 C Letter Grade 60-69.9 D below 60.0 F 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 80-90 average is a B. A 70-80 average is a C. A 60-70 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. Refining 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. 2.1 Add up the test grades 2.2 Divide the total by n

1. Find the number of tests 2.1 Add up the test grades 2.2 Divide the total by n 3. Find the corresponding letter grade and print it out. 2.1 For each of the n tests: 2.1.1 Read the test grade 2.1.2 Add it to the total 1. Find the number of tests 2.1 For each of the n tests: 2.1.1 Read the test grade 2.1.2 Add it to the total 2.2 Divide the total by n 3. Find the corresponding letter grade and print it out. numtests = parseint(prompt ("How many tests did you take?", 0));

numtests = parseint(prompt ("How many tests did you take?", 0)); 2.1 For each of the n tests: 2.1.1 Read the test grade 2.1.2 Add it to the total 2.2 Divide the total by n 3. Find the corresponding letter grade and print it out. for (thistest = 0; thistest < numtests; thistest++) { numtests = parseint(prompt ("How many tests did you take?", 0)); for (thistest = 0; thistest < numtests; thistest++) { 2.1.1 Read the test grade 2.1.2 Add it to the total } 2.2 Divide the total by n 3. Find the corresponding letter grade and print it out. thisgrade = parseint(prompt ("What grade did you get on this test?", 0));

numtests = parseint(prompt ("How many tests did you take?", 0)); for (thistest = 0; thistest < numtests; thistest++) { thisgrade = parseint(prompt ("What grade did you get on this test?", 0)); 2.1.2 Add it to the total } 2.2 Divide the total by n 3. Find the corresponding letter grade and print it out. total = total + thisgrade; numtests = parseint(prompt ("How many tests did you take?", 0)); for (thistest = 0; thistest < numtests; thistest++) { thisgrade = parseint(prompt ("What grade did you get on this test?", 0)); total = total + thisgrade; } 2.2 Divide the total by n 3. Find the corresponding letter grade and print it out. testaverage = total/numtests;

numtests = parseint(prompt ("How many tests did you take?", 0)); 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 numtests = parseint(prompt ("How many tests did you take?", 0)); 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 <html> <body> <script type="text/javascript"> var thistest, numtests, total, thisgrade; var testaverage; var coursegrade; // Find out the number of classes numtests = parseint(prompt ("How many tests did you take?", 0)); total = 0; for (thistest = 0; thistest < numtests; thistest++) { thisgrade = parseint(prompt ("What grade did you get on this test?", 0)); } // 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. alert("your test average is " + testaverage + "\n" + "Your grade will be " + coursegrade); </script> </body> </html> 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 <html> <body> <script type="text/javascript"> var thistest, numtests, total, thisgrade; var testaverage; var coursegrade; // Find out the number of classes numtests = parseint(prompt ("How many tests did you take?", 0)); total = 0; for (thistest = 0; thistest < numtests; thistest++) { thisgrade = parseint(prompt ("What grade did you get on this test?", 0)); } // Make sure that the grades are valid // percentages if (thisgrade > 100) alert("this is not a valid test grade."); else if (thisgrade >= 0) total = total + thisgrade; else alert("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. alert("your test average is " + testaverage + "\n" + "Your grade will be " + coursegrade); </script> </body> </html>