100 likes | 223 Views
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--) {
E N D
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--) { System.out.println(ct); }
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 += ‘*’; }
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); }
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++; }
Loop exercises • While loop for 1st one int ct = 2; while (ct <=10) { System.out.println(ct); ct+=2; }
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.....
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;
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;