Sum of squares in an array using function - java

Question :
Write a program that allows the entry of an integer value n, followed by two sets of n integer values into arrays A and B. The program should use a function to calculate the sum of the square of corresponding values of A and B. These values should then be displayed.
My piece of code :
import java.util.Scanner;
public class Question9_SumOfSquareInArrays {
public static void main(String[] args) {
int sumA = 0;
int sumB = 0;
int n;
int i=0;
Scanner src=new Scanner(System.in);
System.out.print("Please enter value :");
n=src.nextInt();
int [] A=new int[n];
int [] B=new int[n];
System.out.println("Enter value for array A :");
for(i=0;i<n;i++)
{
A[i]=src.nextInt();
}
System.out.println("Enter value for array B :");
for(i=0;i<n;i++)
{
B[i]=src.nextInt();
}
src.close();
System.out.println("Total sum for array A is " + SumOfA(sumA));
System.out.println("Total sum for array B is " + sumOfB(sumB));
}
public static int SumOfA(int sumA)
{
int square=1;
int sum=0;
int n=6;
int [] A= new int[n];
for(int i=0;i<n;i++)
{
square=A[i]*A[i];
sum+=square;
}
return sum;
}
public static int sumOfB(int sumB)
{
int square=1;
int n=6;
int sum=0;
int [] B=new int [n];
for(int i=0;i<n;i++)
{
square=B[i]*B[i];
sum+=square;
}
return sum;
}
}
I am not able to find out my mistakes. Can someone please help me?

public static int SumOfA(int sumA)
{
int square=1;
int sum=0;
int n=6;
int [] A= new int[n]; // you are calculating the sum of this array
for(int i=0;i<n;i++)
{
square=A[i]*A[i];
sum+=square;
}
return sum;
}
is problematic because it calculates the sum of an array of 0s.
Instead, you need to pass your array to the method, i.e.
in main you need
System.out.println("Total sum for array A is " + SumOfA(A));
and modify your SumOfA as follows. Notice it's better to use n = A.length since the length of A is not necessarily always 6.
public static int SumOfA(int[] A)
{
int square=1;
int sum=0;
int n=A.length; // use length to handle array A of any length
for(int i=0;i<n;i++)
{
square=A[i]*A[i];
sum+=square;
}
return sum;
}
The other method has the same problem

Related

i want to find the span of a array. Span is defined as difference of maximum value and minimum value [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I tried by creating two functions for greatest and smallest values and then subtracting them .but the code doesn't seem to work
here's the code.See if u could help me out .im new to java and still learning.
import java.io.*;
import java.util.*;
public class Main{
public static void smler(int arr[],int j){
for (int i=0;i<=j;j++){
if(arr[i]<arr[i+1]){
int temp =arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
public static void grter(int arr[],int j){
for (int i=0;i<=j;j++){
if(arr[i]>arr[i+1]){
int temp =arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
public static void main(String[] args) throws Exception {
Scanner sc= new Scanner (System.in);
int n=sc.nextInt();
int[] arr= new int[n];
for(int i=0;i<=n;i++){
arr[i]=sc.nextInt();
}
grter(arr,n);
int y= arr[n];
smler(arr,n);
int z = arr[n];
System.out.println(y-z);
}
}
There are a lot of errors in your logic.
The for loop does not need to be <= it needs to be < otherwise you will get out of bounds exception.
The way you are calculating the min and max are wrong.
Here is an example for you to study that does what you are trying to accomplish:
import java.util.Scanner;
public class ArraySpan {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter array size:");
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter value:");
arr[i] = sc.nextInt();
}
int min = findMin(arr);
int max = findMax(arr);
System.out.println("The span of the array = " + (max - min));
sc.close();
}
static int findMax(int[] a) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] > max)
max = a[i];
}
return max;
}
static int findMin(int[] a) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] < min)
min = a[i];
}
return min;
}
}
and output:
Enter array size:
3
Enter value:
1
Enter value:
2
Enter value:
3
The span of the array = 2
It would better if you could look for complexity improvement.
Idea is to get the max and the min in best possible way and this can be achieved using any sorting techniques, let us assume your sort method runs in O(n log n) time, and then you just need to get the difference of 1st element(0 th index) and last element(n-1 th index).
public static void main(String[] args) throws Exception {
Scanner sc= new Scanner (System.in);
int n=sc.nextInt();
int[] arr= new int[n];
// insert values into your array
if(arr.length >= 2){
sort(arr); // Implement your any sorting method
// Make sure that your arr has exactly n elements, ,
// Otherwise rest of the indices will all be zero(0)
System.out.println(arr[0]-arr[arr.length-1]); // last index is 'arr.length-1'
return; // Return from here
}
// arr has not sufficient elements to determine span
throw new UnsupportedOperationException("Invalid entry");
}
}
Index starts from 0 and it goes till n-1.
So, the condition in for-loop should be i<n instead of i<=n,for(int i=0;i<n;i++).
You have created 2 functions but it doesn't return any value nor changes anything. As you are passing the array by value, not by references.
You don't need the 2 functions, just one for finding max and min in linear, or sort the array in ascending order and array[0] will be the min and array[n-1] will be max.
There is an approach very similar to what you want to do.
import java.io.*;
import java.util.*;
public class Main{
public static int smler(int arr[],int N){
int smaller = arr[0];
for (int i=1;i<N;i++){
if(arr[i] < smaller){
smaller = arr[i];
}
}
return smaller;
}
public static int grter(int arr[],int N){
int greater = arr[0];
for (int i=0;i<N;i++){
if(arr[i] > greater){
greater = arr[i];
}
}
return greater;
}
public static void main(String[] args) throws Exception {
Scanner sc= new Scanner (System.in);
int n=sc.nextInt();
int[] arr= new int[n];
for(int i=0;i<=n;i++){
arr[i]=sc.nextInt();
}
System.out.println(grter(arr, n) - smler(arr, n));
}
}

Array in two methods

import java.util.Scanner;
public class ld11 {
public static void firstMethod(int[] A) {
int size = A.length;
int equal[] = new int[size];
int less[] = new int[size];
int B[] = new int[size];
int i,j,k;
for(i=0; i<size; i++){
for(j=0;j<size;j++){
if(A[i]==A[j]){equal[i]++;}
else if(A[i]>A[j]){less[i]++;}
}}
for(i=0;i<size;i++){k=less[i];for(j=0;j<equal[i];j++){B[k+j]=A[i];}}
System.arraycopy(B, 0, A,0, A.length);
}
private static void sellaMethod(int[] A){
int t;
t=(int) (Math.log(A.length)/Math.log(2)-1);
int[] h = new int[t];
h[0]=1;
for(int i=1;i<h.length;i++)
h[i]=2*h[i-1]+1;
t--;
while(t>=0){
int inc=h[t];
t--;
for(int i=inc;i<A.length;i++){
int temp=A[i];
int j=i-inc;
while (j>=0 && A[j]>temp) {
A[j+inc]=A[j];
j=j-inc;
}
A[j+inc]=temp;
}
}
}
public static void main(String[] args) {
System.out.println("1st task");
System.out.print("Method(1/2): ");
Scanner sc = new Scanner(System.in);
int x;
if (sc.hasNextInt())
x = sc.nextInt();
else {System.out.println("input-output-error");
sc.close();
return;}
if(x!=1 && x!=2){
System.out.println("input-output-error");
return;}
System.out.print("Count: ");
int y;
if (sc.hasNextInt())
y = sc.nextInt();
else {
System.out.println("input-output-error");
sc.close();
return;}
int []A = new int[y];
System.out.println("Items:");
int i = 0;
do {if(sc.hasNextInt()){
int z = sc.nextInt();
A[i]=z;
i++;}
else{System.out.println("input-output-error");sc.close();return;}} while(i<y);
sc.close();
System.out.println("Sorted:");
if(x==1){firstMethod(A);}
else if(x==2){sellaMethod(A);}
for(i=0;i<y;i++){System.out.print(A[i]+" ");}
}
The user needs to choose which method it wants to use then write how many numbers and then write them, and programme sorts numbers in a way which is described in the method. With first method everything is okay, but with second shows errors :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ld11.sellaMethod(ld11.java:26) (h[0]=1; in this row))
at ld11.main(ld11.java:79) (else if(x==2){sellaMethod(A);} in this row
As you can see it is Shell sort method.
Could you please help?
The problem in line t=(int) (Math.log(A.length)/Math.log(2)-1);
If array has length less than 6 then t will be zero. So you'll create array with zero lenght. It's a bug. Probably you need some checks, probably another formula. Anyway, you have to review code.
As mentioned, your problem is your formula for getting the length of your h array.
A simple fix is just change this line:
t = (int) (Math.log(A.length) / Math.log(2) - 1);
to:
t = A.length;
as all you want is the new array to be same length as the initial array.

finding the average of array then finding the number above the average to print

import java.util.Scanner;
public class ProjectFour {
public static void main(String args[]) {
int[] firstArray = {1,2,3,2,1,6,3,4,5};
System.out.println("this is the average of array : "+analyzeNumbers(firstArray));
System.out.println("These are the numbers above the average : "+aboveAvg(firstArray));
}
//finding the average
public static int analyzeNumbers(int[] firstArray){
int avg;
avg=sumArray(firstArray);
avg=avg/firstArray.length;
return avg;
}
//suming the array method
public static int sumArray(int[] firstArray){
int sum = 0;
for(int x=0;x<firstArray.length;x++){
sum+=firstArray[x];
}
return sum;
}
**this is where im running into problems im kinda stumpted**
// this is my method i cant figure out trying to take the average and find all the numbers in the array above the average and printing them.
public static int aboveAvg(int[] firstArray){
int[] aboveAvg;
aboveAvg = new int[0];
int x;
for(x=analyzeNumbers(firstArray);x<firstArray.length;x++){
aboveAvg+=firstArray[x];
}
return aboveAvg;
}
}
Try using a for loop.
int sum = 0;
for(int i = 0; i < firstArray; i++) {
int getSum = firstArray.get(i);
sum + getSum;
}
int average = sum / firstArray.length;
int[] aboveAverage;
for(int c = 0; c < firstArray; c++) {
if(firstArray.get(c) > average) {
aboveAverage.add(firstArray.get(c));
}
}
This aboveAvg function is completly wrong.
public static List<Integer> aboveAvg(int[] firstArray){
List<Integer> aboveAvg = new ArrayList<Integer>();
int Avg = analyzeNumbers(firstArray);
for(int i = 0; i<firstArray.length; i++)
{
if(firstArray[i] > Avg)
{
aboveAvg.add(firstArray[i]);
}
}
return aboveAvg;
}
Check your for loop and more examples about it
+= will sum two values, won't add new element on any array.
you have to define your return value correctly.
You can use List for create arrays, it's more flexible.

How do i store user input in a variable?

package practiceit;
import java.util.Scanner;
public class numbers {
public static void main (String[]args) {
int max=0;
int min = 0;
}
public static int smallestLargest() {
Scanner console= new Scanner(System.in);
System.out.print("how many numbers do you want to enter?");
int num= console.nextInt();
for (int i=1; i<=num; i++) {
int nums =console.nextInt();
System.out.println("Number "+i+": "+nums);
}
return nums;
}
}
How can I return nums so that it is stored as both a max and min variable, so I can print the highest and lowest value typed by the user?
So something like this?
import java.util.Scanner;
public class numbers
{
public static void main(String[] args)
{
int min = 0, max = 0, current, nums;
Scanner scan = new Scanner(System.in);
System.out.println("How many numbers do you want to enter: ");
nums = scan.nextInt();
for(int i = 0; i < nums; i++)
{
current = scan.nextInt();
if(i == 0)
{
min = current;
max = current;
}
if(current < min)
min = current;
if(max < current)
max = current;
}
//after the loop you should have the max and min value the user entered.
System.out.println("The max number is: "+max);
System.out.println("The min number is: "+min);
scan.close();
}
}
You will have all the value in array
package practiceit;
import java.util.Scanner;
public class numbers {
int[] array = null;
public static void main (String[]args) {
int max=0;
int min = 0;
}
public static int smallestLargest() {
Scanner console= new Scanner(System.in);
System.out.print("how many numbers do you want to enter?");
int num= console.nextInt();
array[] = new int[num];
for (int i=1; i<=num; i++) {
int nums =console.nextInt();
System.out.println("Number "+i+": "+nums);
array [i]= nums;
}
return nums;
}
}
If you use Array.sort(array); you will have sorted array and it will be easy to read minimum and maximum value

how to fill array with given values

i have to get a sequence of numbers and count how many times it takes and then put it into an array so i can sort the array and look for the 10th largest. I can get the count but cant seem to fill the array, i either put in the final count at every index in the array or i just increase the value of the array at index 0 to the count of all numbers, can anyone help.
public class seBuilder
{
//int count=0;
//int [] myArray= new int[10];
public static void main (String args[])
{
int count=0;
int [] myArray= new int[13];
int z=0;
for(int i=2;i<=myArray.length;i++)
{
z=valuegetter(i);
System.out.println(z);
}
//arraycounter(myArray, z);
}
public static int valuegetter(int num)
{
int count=0;
do// do while loop
{
//if its an odd number
if(num%2==1){
num=(num*3)+1;//do this from the question
count++;// add one to count
}
//if num is 2 this will catch and make the code break out
else if(num==2){
//devide num by 2, this will give you 1 allways
System.out.println(num/2);
count++;//adds 1 again
}
else
{
num=num/2;//this will use if number is even
count++;//adds one to count
}
}
while(num>2);//the condition to jump out of loop
//System.out.println("there are "+count+" sequences in that mumber");
return count;
}
public static int[] arraycounter(int myArray[], int count)
{
for(int i=0;i<=myArray.length-1;i++)
{
myArray[i]=count;
System.out.println(" "+myArray[i]);
}
return myArray;
}
public static int tenhigh()
{
}
}
Try to change your main to this:
public static void main (String args[])
{
int count=0;
int [] myArray= new int[13];
int z=0;
for(int i=2;i<=myArray.length;i++) {
z=valuegetter(i);
System.out.println(z);
arraycounter(myArray, z, i);
}
for (int i=0; i < myArray.length; i++) {
System.out.print(myArray[i] + ", ");
}
}
Also change your arrayCounter method to this:
public static int[] arraycounter(int myArray[], int count, int i)
{
int j = i - 2;
myArray[j] = count;
return myArray;
}
If you want to fill an array with a given value, use Arrays.fill, from the java.utils.Arrays class.

Categories

Resources