Issue with Cumulative Sum - java

Here is an easy one that I am having trouble with. The problem requires me to write a method called fractionSum which accepts an integer parameter and returns a double of the sum of the first n terms.
for instance, if the parameter is 5, the program would add all the fractions of (1+(1/2)+(1/3)+(1/4)+(1/5)). In other words, it's a form of the Riemann sum.
For some reason, the for loop does not accumulate the sum.
Here's the code:
public class Exercise01 {
public static final int UPPER_LIMIT = 5;
public static void main(String[] args) {
System.out.print(fractionSum(UPPER_LIMIT));
}
public static double fractionSum(int n) {
if (n<1) {
throw new IllegalArgumentException("Out of range.");
}
double total = 1;
for (int i = 2; i <= n; i++) {
total += (1/i);
}
return total;
}
}

you need to type cast to double
try this way
public class Exercise01 {
public static final int UPPER_LIMIT = 5;
public static void main(String[] args) {
System.out.print(fractionSum(UPPER_LIMIT));
}
public static double fractionSum(int n) {
if (n<1) {
throw new IllegalArgumentException("Out of range.");
}
double total = 1;
for (int i = 2; i <= n; i++) {
total += (1/(double)i);
}
return total;
}
}

The operation
(1/i)
is working on integers and hence will generate the result in terms of int. Update it to:
(1.0/i)
to get the fractional result and not the int result.

Related

Need help storing values i get from a while loop

I would like to be able to store the data I get which is the sum from this while loop so I can add them together in the end.
public class Sum
{
public static void main(String[] args)
{
double second = 1;
double n = 4;
double start = 1;
double sum1= 1.0;
while(second<=n)
{
sum1 = start/second;
second++;
System.out.println(sum1);
}
}
}
You can add the value to the sum1 variable and at last, you can get the total of all the values.
public class Sum
{
public static void main(String[] args)
{
double second = 1;
double n = 4;
double start = 1;
double sum1 = 0;
while(second<=n)
{
sum1 += start/second;
second++;
}
System.out.println(sum1);
}
}

How to pass elements of an array from sub class to main class

So I am very new to learning java and I have a sub class which contains the main and a parent class which does all the calculations. I am having problems on how to pass the elements of an array from the main class to the parent class.
Here is my code. Please help me with how to instantiate the array.
import java.util.Scanner;
public class GreatestLeastAverageApp {
public GreatestLeastAverageApp() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
GreatestLeastAverage number = new GreatestLeastAverage();
int[] x = {0};
int a = 0, b = 0;
x = new int[a];
{
for (int i = 0; i <= a; i++)
{
for (int j = 0; j <= a; j++)
GreatestLeastAverage.a[i] = x[j]; // loop to pass the values of the array elements to the parent class from the sub class.
}
}
Scanner keyboard = new Scanner(System.in); // for the input from the user
System.out.println("Enter the number of elements:");
a = keyboard.nextInt(); // enter the number of integers to be entered so loop can run accordingly
System.out.println("Enter a set of integers( Enter -99 to exit):");
do // do loop so the user can input the variables until one of the variable is =-99.
{
{
for (b = 0; b <= a; b++)
x[b] = keyboard.nextInt();
}
} while (x[b] != -99);
//GreatestLeastAverage number = new GreatestLeastAverage(); // object made for parent class.
System.out.println("The Greatest Number is" + number.computegreatest()); // output line.
System.out.println("The Smallest Number is" + number.computeleast());
System.out.println("The average is " + number.computeaverage());
keyboard.close();
}
}
public class GreatestLeastAverage {
static int x; //variables declared for input in super class.
public static int[] a; // static variable to access in both classes.
int temp;
int temp1;
int temp2;
int average;
public int greatestleastaverage(int d) {
d = x;
return x;
}
public static int getarray(int[] b) {
for (int i = 0; i <= x; i++) {
for (int j = 0; j <= x; j++) {
a[i] = b[j];
}
}
return b[];
}
I know you can't return elements of an array but I really need help.
Use Lists. They're generally more flexible, and if you use ArrayList properly, it can be virtually just as performant as an array.
public class GreatestLeastAverage {
// ... other private members
private List<Integer> a = new ArrayList<Integer>();
public List<Integer> getA() {
return a;
}
}
This lets you do code like:
GreatestLeastAverage gla = new GreatestLeastAverage();
for (int b = 0; b <= a; b++) {
gla.getA().add(keyboard.nextInt());
}
If you should require that data for other uses, it's in gla already! Simply reuse it.
for(int a : gla.getA()) {
// Do something with a
}
I'm sure you used static members because you didn't know how to make it work otherwise, but just know that using static members is generally discouraged unless they're final (constant).
You shouldn't pass data (array) to methods in GreatestLeastAverage class by setting the value of the static field (public static int[] a;). Instead you should pass data to methods as theirs arguments. Your program should look like this:
import java.util.Scanner;
public class GreatestLeastAverageApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int numOfElems = input.nextInt();
int[] numbers = new int[numOfElems];
System.out.println("Enter a set of integers:");
for (int i = 0; i < numOfElems; i++) {
numbers[i] = input.nextInt();
}
System.out.println("Statistics:");
System.out.println(" min: " + GreatestLeastAverage.findMin(numbers));
System.out.println(" max: " + GreatestLeastAverage.findMax(numbers));
System.out.println(" average: " + GreatestLeastAverage.findAverage(numbers));
}
}
class GreatestLeastAverage {
public static int findMin(int[] numbers) {
int candidate = numbers[0];
for (int num : numbers) {
if (num < candidate) candidate = num;
}
return candidate;
}
public static int findMax(int[] numbers) {
int candidate = numbers[0];
for (int num : numbers) {
if (num > candidate) candidate = num;
}
return candidate;
}
public static double findAverage(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum / (double) numbers.length;
}
}
To make this code even better:
The min/max/average calculations above are not great, e.g. If you pass empty array to findAverage, then numbers.length will be 0 and you'll divide by 0. You should make those calculations better, see: #1, #2, #3.
Consider using ArrayList instead of array, when you need to dynamically change the size of the list during runtime (See Neil's answer).

Error of addition of curly brackets at end of enhanced FOR loop within a method

public class ClassOne {
public static void main(String[] args) {
System.out.println(av(5, 6, 7));
}
public static int av(int... numbers) {
int total = 0;
for (int x: numbers) total = total += x;
return total / numbers.length;
}
}
I am a java beginner.
I can't understand really why it fails if you had intuitively added two curly brackets at the end of the "for loop" like this below, which accordingly to presently acquired knowledge looks the most normal and natural to do it.
for (int x: numbers) {
total = total += x;
return total / numbers.length;
}
You can check that now. It fails after you added the curly brackets:
public class ClassFour {
public static void main(String[] args) {
System.out.println(av(5, 6, 7));
}
public static int av(int... numbers) {
int total = 0;
for (int x: numbers) {
total = total += x;
return total / numbers.length;
}
}
}​
I would be grateful if anyone could clarify. Thanks.

Write a function when given one integer x ; returns e with the following approximation

![enter image description here][1]The question:
Write a function with name ʻ expʼ that ,when given one integer x; returns
with the following approximation. In this function, you should use previous two functions to calculate factorial and power.
This is my code;
import java.util.Scanner;
public class ass7_q3 {
public static int power(int x, int y)
{
int result = 1;
for(int i = 1; i <= y; i++)
{
result = result * x;
}
return result;
}
public static int factorial(int n)
{
int fact = 1;
for(int i = 1; i<= n; i++)
fact = fact * i;
return fact;
}
public static int exp( int x)
{
int result;
result = (power(x,x) / factorial(x) );
return result;
}
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int sum = 0;
int x;
x = read.nextInt();
for(int i=0; i<=10; i++)
{
sum = sum + exp(x);
}
System.out.println(sum);
}
}
However, when I run this code, it always gives me the wrong answer.
What can I do?
You should start by working with doubles instead of integers. You can't expect to approximate a Real number using only integer calculations.
For example, power(x,x) / factorial(x) would always return an integer, since both methods return an int.
5/2 will return 2. You need cast it to double like ((double)5)/2 will return 2.5
You should think about range of integer ( in java 2,147,483,647)
if your input is grater than 12, integer can not handle.
Factorial method will return wrong value. because
factorial(12)=479,001,600 but
factorial(13)=6,227,020,800

While loop numbers sum

I need help on how to calculate sum of the numbers that while loop prints. I have to get numbers 1 to 100 using while loop and calculate all those together. Like 1+2+3...+98+99+100. I can get numbers but can't calculate them together. Here's my code:
public class Loops {
public static void main(String[] args) throws Exception {
int i = 1;
while (i < 101) {
System.out.print(i);
i = i + 1;
}
}
}
How do I make it only print the last sum? If I try to trick the equation it just hangs.
Use another variable instead of i which is the loop variable:
int i = 1;
int sum = 0;
while (i < 101) {
sum += i;
i++;
}
Now sum will contain the desired output. In the previous version, you didn't really loop on all values of i from 1 to 101.
First either change your sum variable or index variable
public class Loops {
public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i < 101) {
sum = sum + i;
++i;
}
System.out.println(sum);
}
Your sum (i) is also your index. So each time you add to it, you're skipping numbers which you want to add to it.
public class Loops {
public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i < 101) {
//System.out.print(i);
sum = sum + i;
++i;
}
System.out.println(sum);
}
Alternatively, use the Gauss sum: n(n+1)/2
So, the end sum is 100(101)/2 = 5050
Try the following. Moved the values around a bit to ensure that you add up to 100 and always show the sum.
public static void main(String[] args) throws Exception {
int i = 1;
long tot = 1;
while (i < 100) {
i += 1;
tot += i;
System.out.print("Number :" + i + " ,sum="+tot);
}
}
public class Loops {
public static void main(String[] args) throws Exception {
int i = 1;
int sum = 0;
while (i < 101) {
sum = i + 1;
}
System.out.print(sum);
}
}

Categories