Well, I am doing a practice problem (preparing for midterm) and I was able to get one of the outputs correct. However, I am having troublesome getting the average input. It ends up at 12.0 instead of 6.5
Here's the prompt question:5.
Complete the following Java program by filling in the bodies of functions sum(), avg(), and ord(). A call to sum(n) should return the sum of all the integers from 1 to n, while avg(n) returns the average of the same set of numbers. A call to the boolean function ord(x, y, z) returns true if x < y< z and false otherwise. The Function main() should produce the following output
Output:
6.5 true false
This is my code:
class Problem5 { // sum(): return 1+2+3+..+n static int sum(int n) { //this is given int sum = 0; for(int i=0; i<n; i++) { sum += n; } return n; } // avg(): return average of {1,2,..,n} static double avg(int n) { // given double sum = 0; for (int i=1; i<n; i++) { sum +=n; } return sum / n; } //ord(): return true if and only if x<y<z static boolean ord(double x, double y, double z){ //given if (x < y && y <z){ return true; } else { return false; } } public static void main (String[]args) { System.out.println(avg(12)); System.out.println(ord(1.2,3.4,5.6)); System.out.println(ord(3.4,1.2,5.6)); } } Overall I am having trouble coding/ filling in the code for static int sum(int) and static double avg(int).
sumis not declared inavg.return n*(n+1)/2, but I think the goal is to understand coding, not maths... ;-)sum([1...n]) == n*(n+1)/2,avg([1...n]) == (n+1)/2(no need for loop), (That is not related to programming, but rather to math)