FOR LOOP WITH CHALLENGES
FOR LOOP
Syntax : for( int i=0; i<6; i++){
System.out.println("Loop "+ i + " hello");
}
System.out.println("Loop "+ i + " hello");
}
Using the for statement call calculateInterest method with the amount of 10000 with an interest rate of 2,3,4,5,6,7 and 8 and print the result.
Soln package com.cnc;
public class Main {
public static void main(String[] args) {
for( double i=2; i<9; i++){
System.out.println("10,000 at "+ i +
"% interest = "+calculateInterest(10000,i));}
}
}
}
}
}
public static double calculateInterest(double amount,double interestRate){
return(amount*(interestRate/100));
}
}
Create a for the statement using any range of numbers. Determine if the number is a prime number, print it out AND increment a count of the numbers of prime numbers found and if you get to the stage where 3 or more are found then I want you to exit the loop.[HINT: Use the break statement to exit].
Soln LECTURE 64
Create a for statement using a range of numbers from 1 to 1000 inclusive.
Sum all the numbers that can be divided with both 3 and also with 5.
For those numbers that met the above conditions, print out the numbers.
break out of the loop once you find 5 numbers that meet the above conditions.
NOTE: Type all code in the main method.
Soln
package com.cnc;public class Main {
public static void main(String[] args) {
int count = 0;
int sum = 0;
for (int i = 1;i<=1000;i++){
if(i%3==0 && i%5==0){
count++;
sum += i;
System.out.println("Found number = "+i);
}
if(count == 5){
break;
}
}
}
}
Write a method called isOdd with an int as a parameter and called it a number. The method needs to return boolean.
Check that number is >0 if it does not return false.
If the number is odd return true, otherwise return false.
Write a second method called sum0dd that has two parameters start and end, which represent a range of numbers.
The method should use for loop to sum all odd numbers in that range including the end and return the sum.
It should call the method isOdd to check if each number is odd.
The parameter end needs to be greater than or equal to start and both start and end parameters have to be greater than 0.
If those conditions are not satisfied then return -1 from the method to indicate invalid output.
Soln
package com.cnc;
public class Main {
public static void main(String[] args) {
System.out.println(isOdd(3));
System.out.println(sumOdd(100, 100));
}
public static boolean isOdd(int number) {
if (number > 0) {
return number % 2 != 0;
}
return false;
}
public static int sumOdd(int start, int end) {
if (start > end || start <= 0) {
return -1;
}
int sum = 0;
for (int i = start; i <= end; i++) {
if (isOdd(i)) {
sum = sum + i;
}
}return sum;
}
}