Friday 29 September 2017

Java method that takes an integer n and returns the sum of all the odd positive integers less than or equal to n.

Problem:

Write a short Java method that takes an integer n and returns the sum of all the
odd positive integers less than or equal to n.

Solution:

package com.basics;

import java.util.Scanner;

public class SumOfOddPositiveIntegers {

static int number;
int oddNumbers[];

public static void main(String[] args) {
SumOfOddPositiveIntegers findSum = new SumOfOddPositiveIntegers();
findSum.getTheNumber();
findSum.findOddNumbers(number);
System.out.println("the odd numbers are");
findSum.printOddNumbers();
System.out.println();
System.out.println("the sum of all odd positive integers less than or equal to n is:  " + findSum.findSum());

}

public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the number");
number = scanner.nextInt();
oddNumbers = new int[number/2  + 1];
scanner.close();
}

public int findSum(){
int sum = 0;
for (int i = 0; i < oddNumbers.length; i++) {
sum = sum + oddNumbers[i];
}
return sum;
}

public void findOddNumbers(int n){
int j = 0;
for (int i = 1; i <= n; i++) {
if((i % 2) != 0){
oddNumbers[j++] = i;
}
}
}

public void printOddNumbers(){
for (int i = 0; i < oddNumbers.length; i++) {
System.out.print(oddNumbers[i] + " ");
}
}

}


Output:

enter the number
6
the odd numbers are
1 3 5 0
the sum of all odd positive integers less than or equal to n is:  9

enter the number
15
the odd numbers are
1 3 5 7 9 11 13 15 
the sum of all odd positive integers less than or equal to n is:  64


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...