1 / 80

Introduction to Computer Programming

Learn about loops and decisions in computer programming, including if/else statements, counting loops, and nested if/else statements. Understand how to repeat actions and make decisions based on conditions. Program in Java using the Scanner class to find the average of N values.

pmaxim
Download Presentation

Introduction to Computer Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Computer Programming Loops N Decisions If/Else Counting Loops

  2. Your old Average friend 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, value1, value2, value3; //get values System.out.println (“What is value 1?”); value1 = keyb.nextDouble(); System.out.println (“What is value 2?”); value2 = keyb.nextDouble(); System.out.println (“What is value 3?”); value3 = keyb.nextDouble(); sum = value1 + value2 + value3; average = sum/3; System.out.println(“The average is “ + average); }}

  3. Average Program - did you pass? • You have the average program averaging 3 grades, but did you pass? If the grade is over 65, you passed. • How can you code this?

  4. The if statement • if statement: Do this only if true • General syntax: if (<condition>) { <statement> ; ... <statement> ; } • Example: double average = sum/3; if (average >= 65) { System.out.println(“ You passed."); }

  5. Relational expressions

  6. if statement flow diagram

  7. The if/else statement • if/else statement: A Java statement that executes one block of statements if a certain condition is true, and a second block of statements if it is false. • General syntax: if (<condition>) { <statement(s)> ; } else { <statement(s)> ; } • Example: double average = sum/3; if (average >= 65) { System.out.println(“ You passed.");} else{ System.out.println(“You failed.”); }

  8. if/else flow diagram

  9. if/else question • Write code to read a number from the user and print whether it is even or odd using an if/else statement. • Example executions: Type a number: 42 Your number is even Type a number: 17 Your number is odd

  10. Nested if/else statements • nested if/else statement: A chain of if/else that chooses between outcomes using many conditions. • General syntax: if (<condition>) { <statement(s)> ; } else if (<condition>) { <statement(s)> ; } else { <statement(s)> ; } • Example: if (number > 0) { System.out.println("Positive"); } else if (number < 0) { System.out.println("Negative"); } else { System.out.println("Zero"); }

  11. Nested if/else flow diagram if (<condition>) { <statement(s)> ; } else if (<condition>) { <statement(s)> ; } else { <statement(s)> ; }

  12. Nested if/else/if diagram if (<condition>) { <statement(s)> ; } else if (<condition>) { <statement(s)> ; } else if (<condition>) { <statement(s)> ; }

  13. Sequential if diagram if (<condition>) { <statement(s)> ; } if (<condition>) { <statement(s)> ; } if (<condition>) { <statement(s)> ; }

  14. 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?

  15. 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();

  16. 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); if (average >= 65) { System.out.println(“ You passed.");} else{ System.out.println(“You failed.”);} } } • 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!

  17. 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 Java includes several ways of using repetition in a program. • Each case where we repeat a set of statement is called a loop.

  18. 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.

  19. 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"); System.out.println("Hello, again"); System.out.println("Hello, again"); System.out.println("Hello, again"); System.out.println("Hello, again"); } }

  20. 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 }

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

  22. 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!”

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

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

  25. 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"); } }

  26. 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.

  27. 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();

  28. 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.1 Write “Hi, there!”

  29. 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");

  30. 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"); } }

  31. 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

  32. 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();

  33. 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.1 Get the next value 2.1.2 Add it to the total

  34. 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.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)

  35. 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.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)

  36. 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.1 Get the next value 2.1.2 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++) { System.out.println("What is the next value?"); value = keyb.nextInt(); sum = sum + value; }

  37. 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);

  38. 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();

  39. // 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); } }

  40. 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

  41. 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.

  42. 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

  43. 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

  44. 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;

  45. 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++) { }

  46. 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;

  47. 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 } System.out.println("year = " + year + "\tprinciple = “ + principle);

  48. 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;

  49. // 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); } } }

  50. 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!

More Related