This is all my code. I am having problems with the standard deviation formula.
I run the program with these values:
Number of items: 5
Items: 16 25 81 80 24
I'm supposed to get this output:
Average: 45.20
Std Dev: 32.41
Less than Avg: 3
Array is not in sorted order
Instead, I get this output:
Array is not in sorted order
Average: 45.20
Std Dev: 55.60
Less than Avg: 3
import java.text.DecimalFormat;
import java.util.Scanner;
public class array {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat df = new DecimalFormat ("#.00");
System.out.println("How many values do you want?");
int num = input.nextInt();
if (num< 1 || num > 100)
{
System.out.println("Error");
System.exit(0);
}
int[] array= valueArray(input, num);
double o= average(num, array);
double standdev = getStdDev(array, num);
int lessThanAvg = lessAvg ( array, num, o );
boolean sorted=isArraySorted(array, num);
System.out.println("Average: " + df.format(o));
System.out.println("Std Dev: " + df.format(standdev));
System.out.println("Less than Avg: " + lessThanAvg);
}
public static int[] valueArray (Scanner input, int num )
{
int[] values = new int[100];
System.out.println("What numbers do you want to put in?");
for (int j = 0; j < num; j++)
{
values[j]=input.nextInt();
}
return values;
}
public static double average ( int num ,int[] values)
{
double avg=0.0;
for (int i = 0; i < num; i++)
{
avg = avg+values[i];
}
return avg/num;
}
public static double getStdDev (int [] values, int num)
{
double avg = 0.0;
double sum = 0 ;
for (int i = 0; i < num - 1; i++)
{
sum = Math.sqrt ((Math.pow((values[i]-avg),2) + Math.pow((values[num-1]),2)) / num-1);
}
return sum;
}
public static int lessAvg ( int [] values, int num, double avg )
{
int counter = 0;
for (int i = 0; i < num; i++ )
{
if (values[i] < avg)
{
counter = counter + 1;
}
}
return counter;
}
public static boolean isArraySorted (int [] values, int num)
{
for (int i = 0; i < num - 2; i++)
{
if (values[i]>values[i+1])
{
System.out.println("Array is not in sorted order");
return false;
}
}
System.out.println("Array is in sorted order");
return true;
}
}
to get the standard deviation
find out the mean.
Then for each number of your array subtract the Mean and square the
result.
Then work out the mean of those squared differences
find the square root of that.
For reference you can look at this Post
Related
I have this java code that sorts a set of random scores. What I need to do is modify sortArray so that it returns the total number of comparisons that were made during its calls to findMinLoc and modify the main to call the modified sortArray correctly, capturing the number of comparisons total into a variable. I am very new to programming and I'm having a complete block on how to do this. I've attempted to use a counter however it always displays only the amount of scores not how many comparisons were made to put the array in order.
import java.util.Scanner;
public class Lab11
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
final int Size = 10;
double [] scores = new double[Size];
// set all the scores to a random number [0 - 99]
for (int s = 0; s < Size; ++s)
scores[s] = (int)(Math.random() * 100);
// print the scores - original order
System.out.println("Scores - Original");
System.out.println("------------------");
printArray(scores, Size);
System.out.println("\n");
// sort the scores
System.out.println("Sorting ...\n");
// print the scores - sorted order
sortArray(scores, Size);
System.out.println("Size of array = " + Size);
System.out.println("Comparisons needed = \n");
System.out.println("Scores - Sorted");
System.out.println("----------------");
printArray(scores, Size);
System.out.println("\n");
stdIn.close();
}
public static void printArray(double [] arr, int eSize)
{
for (int i = 0; i < eSize; ++i)
System.out.println(arr[i]);
}
public static int findMinLoc(double [] arr, int startInd, int endInd)
{
int minLoc = startInd;
for (int i = startInd; i <= endInd; ++i)
{
if (arr[i] < arr[minLoc])
minLoc = i;
}
return minLoc;
}
public static void swapInArray(double [] arr, int ind1, int ind2)
{
double tmp = arr[ind1];
arr[ind1] = arr[ind2];
arr[ind2] = tmp;
}
public static void sortArray(double [] arr, int eSize)
{
for (int i = 0; i < eSize; ++i)
{
int ind = findMinLoc(arr, i, eSize-1);
swapInArray(arr, i, ind);
}
}
}
It should look something like..
Scores - Original -----------------
69.0
56.0
19.0
70.0
88.0
86.0
56.0
19.0
79.0
20.0
Sorting ...
Size of array = 10
Comparisions needed = 55
Scores - Sorted
19.0
19.0
20.0
56.0
56.0
69.0
70.0
79.0
86.0
88.0
each method I tried always came up with the caparisons needed being 10 and I don't understand why. Any suggestions on how to solve this?
If 55 was the amount of comparisons you were expecting.
Globally define
static int minLocComps = 0;
and add an increment
for (int i = startInd; i <= endInd; ++i)
{
if (arr[i] < arr[minLoc])
minLoc = i;
minLocComps++; //<-- Here
}
And finally your print out.
System.out.println("Comparisons needed = " + minLocComps +"\n");
Just define static count variable globally and add increment the count in the finfMinLoc function as below:
static int count=0;
public static int findMinLoc(double [] arr, int startInd, int endInd)
{
int minLoc = startInd;
for (int i = startInd; i <= endInd; ++i)
{
count++;
if (arr[i] < arr[minLoc])
minLoc = i;
}
return minLoc;
}
And add the count variable in print statement:
System.out.println("Comparisons needed = \n" +count);
simply add a counter and place it after the compare:
import java.util.Scanner;
public class tst
{
private static int comparisonCount = 0;
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
final int Size = 10;
double [] scores = new double[Size];
// set all the scores to a random number [0 - 99]
for (int s = 0; s < Size; ++s)
scores[s] = (int)(Math.random() * 100);
// print the scores - original order
System.out.println("Scores - Original");
System.out.println("------------------");
printArray(scores, Size);
System.out.println("\n");
// sort the scores
System.out.println("Sorting ...\n");
// print the scores - sorted order
sortArray(scores, Size);
System.out.println("Size of array = " + Size);
System.out.println("Comparisons needed = " + comparisonCount + "\n");
System.out.println("Scores - Sorted");
System.out.println("----------------");
printArray(scores, Size);
System.out.println("\n");
stdIn.close();
}
public static void printArray(double [] arr, int eSize)
{
for (int i = 0; i < eSize; ++i)
System.out.println(arr[i]);
}
public static int findMinLoc(double [] arr, int startInd, int endInd)
{
int minLoc = startInd;
for (int i = startInd; i <= endInd; ++i)
{
if (arr[i] < arr[minLoc])
minLoc = i;
comparisonCount++;
}
return minLoc;
}
public static void swapInArray(double [] arr, int ind1, int ind2)
{
double tmp = arr[ind1];
arr[ind1] = arr[ind2];
arr[ind2] = tmp;
}
public static void sortArray(double [] arr, int eSize)
{
for (int i = 0; i < eSize; ++i)
{
int ind = findMinLoc(arr, i, eSize-1);
swapInArray(arr, i, ind);
}
}
}
First of all let me say I am quite new to programming its been my second week since I started so if you see any bad practice or error in code please accept my apologies.
I want to print sum of first n odd numbers. But so far I can only do the sum of odd number up to the given number. kindly help.
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int sum = 0;
for (int i = 0; i <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
}
}
return sum;
}
}
You don't have to use a loop at all
static int sumOfOdd(int num) {
return num*num;
}
For Any Arithmetic Progression, the sum of numbers is given by,
Sn=1/2×n[2a+(n-1)×d]
Where,
Sn= Sum of n numbers
n = n numbers
a = First term of an A.P
d= Common difference in an A.P
Using above formula we can derive this quick formula to calculate sum of first n odd numbers,
Sn(odd numbers)= n²
Try this it uses a for loop that increments by two to only account for odd numbers.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();
System.out.println("The sum of the first " + n + " odd numbers is: " + sumOfOddNumbers(n));
}
public static int sumOfOddNumbers(int n) {
int sum = 0;
for(int i = 1; i < n*2; i+=2) {
sum += i;
}
return sum;
}
}
Example usage:
Enter the value of n: 5
The sum of the first 5 odd numbers is: 25
Try this:
static int sumOfOdd(int num) {
int sum = 0;
for (int i = 0; i < num; i++){
sum += i*2+1;
}
return sum;
}
It sums up all odd numbers until the limit is reached.
With i*2+1 you get the next odd number. Then you add it to the sum.
Tested with System.out.println(sumOfOdd(4)); and got the expected result 16 (1+3+5+7)
Change the counter to the number of times you add an odd number to the sum value...
static int sumOfOdd(int num) {
int sum = 0;
int i = 0;
int count = 0;
do {
if(i % 2 != 0) {
sum += i;
count++;
}
i++;
} while (count < num);
return sum;
}
Or even cleaner:
static int sumOfOdd(int num) {
int sum=0;
for (int i=1;i<num*2;i+=2) {
sum=sum+i;
}
return sum;
}
You should count how many numbers have you added and in the condition to check if count of numbers you summed is less or equal than your n. Just add the counter in your for loop and set condition to: count <= num and it should work.
Every time you add a number to the sum increment the count by count++.
The code suppose to look like this:
static int sumOfOdd(int num)
{
int sum = 0;
int count = 0;
for (int i = 0, count= 0; count <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
count++;
}
}
return sum;
}
I haven't checked it, but it should be correct
Since you don't know how many loop cycles are required you have to change the exit condition of the for loop.
Or you can use a while loop exploiting the same exit condition.
static int sumOfOdd(int num){
int sum = 0;
int counter = 0;
int currentNumber = 0;
while (counter<num){
if(currentNumber % 2 != 0){
sum += currentNumber;
counter++;
}
currentNumber++;
}
return sum;
}
Here is the complete code you'd be using:
public class YourClass {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int counter = 0;
for (int i = 0;; i++)
{
int sum = 0;
if(i % 2 != 0)
{
counter++;
sum += i;
}
if(counter == num) return sum;
}
}
}
Another alternative.
static int sumOfOdd(int num) {
int sum = 0;
int last = 2*num-1;
for (int i = 1; i <= last; i+=2){
sum += i;
}
return sum;
}
Obviously return num*num; is the most efficient but if you're obliged to use a loop then this method avoids a * inside the loop.
This will be a tiny (tiny) bit more efficient than:
for (int i = 0; i < num; ++i){
sum += 2*i+1;
}
import java.util.*;
class karan{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = n;
int sumOddNumber = n * i;
System.out.println(n*i);
}
}
I am trying to return the sum of all the values in the the array while also trying to return the largest value to the main method, however, the program states that I have an error at return total and at return number. The error states, "Type mismatch: cannot convert from int to int[]."
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
int myArray[] = new int[10];
for(int i = 0; i <= myArray.length-1; i++ ) {
System.out.println("Enter Number: ");
int nums = number.nextInt();
myArray[i] = nums;
}
int [] sum = computeTotal(myArray);
System.out.println("The numbers total up to: "+sum);
int [] largest = getLargest(myArray);
System.out.println("The largest number is: "+largest);
}
public static int[] computeTotal(int myArray[]) {
int total = 0;
for (int z : myArray){
total += z;
}
return total;
}
public static int[] getLargest(int myArray[]) {
int number = myArray[0];
for(int i = 0; i < myArray.length; i++) {
if(myArray[i] > number) {
number = myArray[i];
}
}
return number;
}
The methods computeTotal and getLargestshould be changed the return types to int. Please refer this:
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
int myArray[] = new int[10];
for(int i = 0; i <= myArray.length-1; i++ ) {
System.out.println("Enter Number: ");
int nums = number.nextInt();
myArray[i] = nums;
}
int sum = computeTotal(myArray);
System.out.println("The numbers total up to: "+sum);
int largest = getLargest(myArray);
System.out.println("The largest number is: "+largest);
}
public static int computeTotal(int myArray[]) {
int total = 0;
for (int z : myArray){
total += z;
}
return total;
}
public static int getLargest(int myArray[]) {
int number = myArray[0];
for(int i = 0; i < myArray.length; i++) {
if(myArray[i] > number) {
number = myArray[i];
}
}
return number;
}
Hope this help.
Probably in java8 there're easier way to get the max and sum.
int sum = Arrays.stream(new int[] {1,2, 3}).sum(); //6
int max = Arrays.stream(new int[] {1,3, 2}).max().getAsInt(); //3
I was practicing with some exercises from UVA Online Judge, I tried to do the Odd sum which basically is given a range[a,b], calcule the sum of all odd numbers from a to b.
I wrote the code but for some reason I don't understand I'm getting 891896832 as result when the range is [1,2] and based on the algorithm it should be 1, isn't it?
import java.util.Scanner;
public class OddSum
{
static Scanner teclado = new Scanner(System.in);
public static void main(String[] args)
{
int T = teclado.nextInt();
int[] array = new int[T];
for(int i = 0; i < array.length; i++)
{
System.out.println("Case "+(i+1)+": "+sum());
}
}
public static int sum()
{
int a=teclado.nextInt();
int b = teclado.nextInt();
int array[] = new int[1000000];
for (int i = 0; i < array.length; i++)
{
if(a%2!=0)
{
array[i]=a;
if(array[i]==(b))
{
break;
}
}
a++;
}
int res=0;
for (int i = 0; i < array.length; i++)
{
if(array[i]==1 && array[2]==0)
{
return 1;
}
else
{
res = res + array[i];
}
}
return res;
}
}
Your stopping condition is only ever checked when your interval's high end is odd.
Move
if (array[i] == (b)) {
break;
}
out of the if(a % 2 != 0) clause.
In general, I don't think you need an array, just sum the odd values in your loop instead of adding them to the array.
Keep it as simple as possible by simply keeping track of the sum along the way, as opposed to storing anything in an array. Use a for-loop and add the index to the sum if the index is an odd number:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter minimum range value: ");
int min = keyboard.nextInt();
System.out.println("Enter maximum range value: ");
int max = keyboard.nextInt();
int sum = 0;
for(int i = min; i < max; i++) {
if(i % 2 != 0) {
sum += i;
}
}
System.out.println("The sum of the odd numbers from " + min + " to " + max + " are " + sum);
}
I don't have Java installed right now, however a simple C# equivalent is as follows: (assign any values in a and b)
int a = 0;
int b = 10;
int result = 0;
for (int counter = a; counter <= b; counter++)
{
if ((counter % 2) != 0) // is odd
{
result += counter;
}
}
System.out.println("Sum: " + result);
No major dramas, simple n clean.
I need to write a java method sumAll() which takes any number of integers and returns their sum.
sumAll(1,2,3) returns 6
sumAll() returns 0
sumAll(20) returns 20
I don't know how to do this.
If your using Java8 you can use the IntStream:
int[] listOfNumbers = {5,4,13,7,7,8,9,10,5,92,11,3,4,2,1};
System.out.println(IntStream.of(listOfNumbers).sum());
Results: 181
Just 1 line of code which will sum the array.
You need:
public int sumAll(int...numbers){
int result = 0;
for(int i = 0 ; i < numbers.length; i++) {
result += numbers[i];
}
return result;
}
Then call the method and give it as many int values as you need:
int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
int sum = 0; //start with 0
for(int n : nums) { //this won't execute if no argument is passed
sum += n; // this will repeat for all the arguments
}
return sum; //return the sum
}
Use var args
public long sum(int... numbers){
if(numbers == null){ return 0L;}
long result = 0L;
for(int number: numbers){
result += number;
}
return result;
}
import java.util.Scanner;
public class SumAll {
public static void sumAll(int arr[]) {//initialize method return sum
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println("Sum is : " + sum);
}
public static void main(String[] args) {
int num;
Scanner input = new Scanner(System.in);//create scanner object
System.out.print("How many # you want to add : ");
num = input.nextInt();//return num from keyboard
int[] arr2 = new int[num];
for (int i = 0; i < arr2.length; i++) {
System.out.print("Enter Num" + (i + 1) + ": ");
arr2[i] = input.nextInt();
}
sumAll(arr2);
}
}
public static void main(String args[])
{
System.out.println(SumofAll(12,13,14,15));//Insert your number here.
{
public static int SumofAll(int...sum)//Call this method in main method.
int total=0;//Declare a variable which will hold the total value.
for(int x:sum)
{
total+=sum;
}
return total;//And return the total variable.
}
}
You could do, assuming you have an array with value and array length: arrayVal[i], arrayLength:
int sum = 0;
for (int i = 0; i < arrayLength; i++) {
sum += arrayVal[i];
}
System.out.println("the sum is" + sum);
I hope this helps.