1 / 9

Software Engineering Foundations

6 More basics Repetition and Division Answers. Software Engineering Foundations. Loop exercises. Print the even numbers from 2 to 10 for (int ct = 2; ct <=10; ct+= 2) { System.out.println(ct); } Print every number from the value in num down to 1 for (int ct = num; ct >=1; ct--) {

jason
Download Presentation

Software Engineering Foundations

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. 6 More basics Repetition and Division Answers Software Engineering Foundations

  2. Loop exercises • Print the even numbers from 2 to 10 for (int ct = 2; ct <=10; ct+= 2) { System.out.println(ct); } • Print every number from the value in num down to 1 for (int ct = num; ct >=1; ct--) { System.out.println(ct); }

  3. Loop exercises • Print 20 asterisks for (int ct = 1; ct <=20; ct++) { System.out.println(‘*’); } • Create a String of 20 asterisks String s = “2”; for (int ct = 1; ct num; ct++) { S += ‘*’; }

  4. Loop exercises • Print a number of characters, when the number of characters is stored in num and character to be printed is stored in char ch for (int ct = 1; ct num; ct++) { System.out.println(ch); }

  5. Loop exercises • Count the number of letter ‘A’s in a String s int count = 0; for (int index = 0; index < s.length(); index++) { if (s.charAt(index) == ‘A’ ) count++; }

  6. Loop exercises • While loop for 1st one int ct = 2; while (ct <=10) { System.out.println(ct); ct+=2; }

  7. Division exercise 1 • Given int u; double v; int w = 0; int x = 3; int y = 7; double z = 8; • What is the result of: • u = y/x; 7/3 = 2 • u = y%x; 7%3 = 1 • v = y/x; 7/3 = 2, stored as a double • u = z/x; 8.0/3 – can’t store double result in int • u = x/w; 3/0 – can’t divide by 0 • v = z/x; 8.0/3 = 2.6666.....

  8. Division answers 2 • Share out a number of items int items between a number of people int people • Find the number of items each person gets • Find the number of items left over int numItems = people/items; int numLeft = people%items;

  9. SJF L3 division Answers conts • Divide the number int num by 2 into int part1 and int part2. The 2 parts should be equal (e.g. 4 -> 2 & 2) or separated by 1 (e.g. 5 -> 2 & 3) int part1 = num/2; int part2 = part1 + num%2; OR int part2 = num – part1;

More Related