How does this program works and executes? - java

class Average
{
public static void main(String args[])
{
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
// Assigning some values to the Array
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}
How this Program Works. Can someone explain it to me?

You have created a double array called nums with these values in it {10.1, 11.2, 12.3, 13.4, 14.5}. Then you created a variable result and assigned 0 to it. Then a for loop for which condition is i<5 which means it is going to run 5 times starting from 0 as value of i is 0. Inside the for loop, you are adding value of each element to the result variable.
Basically, you did summation of all elements of array and stored the result into result variable.
And then at the end, you are printing out the average by dividing 5 which is length of the array.

This is how your iteration works:
when
i=0 result = 0+10.1
i=1 result = 10.1+11.2
i=2 result = 21.3+12.3
i=3 result = 33.6+13.4
i=4 result = 47.0+14.5
result= 61.5
61.5/5
= 12.29

Related

Multiply numbers for loop java returning 0

I'm trying to take a number(n) and multiply it by every number before it, enter 4 you get (1x2x3x4) = 24. My code returns a 0. I have an addition just like this that works. Any ideas?
public static int multiplyTooNum()
{
Scanner myIn = new Scanner(System.in);
int n;
System.out.println("Please enter a number");
n = myIn.nextInt();
myIn.nextLine();
int sum = 0;
for (int i=0; i<n; i++)
{
sum = sum * i;
}
int result = sum*n;
System.out.println(result);
myIn.close();
return result;
}
In multiplication, the accumulated variable is not called sum. It is called product. The word sum is only used in the context of addition.
Now, on with your problem:
If you remember your elementary school mathematics, anything multiplied by zero gives zero.
That's why you are receiving a zero in the end.
So, in order to fix this, you have to initialize your product with 1 instead of 0, and then make your for loop start counting from index 1 instead of 0.
for (int i=0; i<n; i++)
{
sum = sum * i;
}
Issue is in this part, you start i from 0, so each time the sum get's 0 and it will be multiplied again. I suggest you to learn debugging and step over in loops to pinpoint the issues.

Prime Numbers Array in Java

I want to return an array that displays all the prime numbers within a certain range from 0 till whatever number I enter.
For the range from 0 to 5 I would like the array returned with [2,3,5]. Within the task I was told by my professor that I should fill the whole array with 0 before replacing those 0 wih prime numbers later.
Currently my code does not return the correct array as I do not seem to access the next location in the array but seem to always assign the value to the first location in the array.
My current result array is not [2,3,5] but [5,0,0,0,0].
Any help would be greatly appreciated.
public static int[] generierePrimzahlen(int bis){
int [] myAry = new int[bis];
Arrays.fill(myAry,0);
for(int i=0;i<myAry.length;i++){
for (int nextprime=1; nextprime < bis; nextprime++){
int counter = 0;
// System.out.println(nextprime);
if (istPrimzahl(nextprime)){
myAry[counter] = nextprime;
counter++;
}
}
System.out.print(myAry[i]+" ");
}
return myAry;
}
PS: I have a functioning method (istPrimzahl), which checks if a certain number is a prime number or not.
The problem is that your counter is in the wrong scope.
so instead of incrementing. on every iteration of the first for loop, you declare a new counter. so that it is 0 at the time u assign the prime number to the array.
public static int[] generierePrimzahlen(int bis){
int [] myAry = new int[bis];
// Arrays.fill(myAry,0); // no need, this is already been done at initialization
for(int i=0;i<myAry.length;i++){
int counter = 0;
// adding <= 'nextprime <= bis;' to check also the last number in the range
for (int nextprime=1; nextprime <= bis; nextprime++){
// int counter = 0; wrong scope
// System.out.println(nextprime);
if (istPrimzahl(nextprime)){
myAry[counter] = nextprime;
counter++;
}
}
if(myAry[0] != 0) // to get rid of displaying Zeros
System.out.print(myAry[i]+" ");
}
return myAry;
}
Put below line outside both for loop. That will work.
Reason for issue is - you are resetting the counter while entering the for loop.
int counter = 0;
ArrayList will be a better choice than array. However if using array is another school requirement, then what you have done:
int[] myAry = new int[size];
will already set all elements to zeroes.
There is also no need to use 2 loops for this. Just:
Loop through from 1 to n
if current number is prime, set it to array of current index
idx++
I do not seem to access the next location in the array but seem to always assign the value to the first location in the array.
That is because you are setting your counter variable back to zero in every iteration. You should declare it outside your loop.
Example:
int idx = 0; //place this outside the loop
for(int i=1; i<=n; i++)
if(isPrime(i))
myAry[idx++] = i;

Result = result + [i]?

class Example {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}
Sorry if the question is too stupid to ask, but I need to know. why do we have to declare double result = 0?
and why write result = result + nums[i]? why cant we write just result = nums [i]?
why do we have to declare double result = 0?
It's because your result variable is a block variable which means
you need to initialize it first before you can use it.
why write result = result + nums[i]? why cant we write just result = nums [i]?
result = nums[i] only assigns the value in the variable.
result = result + nums[i] assigns the sum value of result and nums[i].
You can also use this.
result += nums[i];
instead of this.
result = result + nums[i];
Writing result = nums [i] will assign the value of nums[i] to result, while writing result = result + nums[i] will assign the current value of result plus nums[i] to result.
So every time you go around your loop, you're adding the value of nums[i] to result, instead of replacing it.
Declaring result = 0 just initialises result to the value of 0.
Alright! Alright! Alright!, Here it is. A simple explanation -
Suppose You write result = num[i] inside the for-loop.
During the iteration inside for-loop, where you are writing System.out.println("Average is " + result / 5);
The consequent output will be -
For Iteration 1 - Average is 10.1/5
For Iteration 2 - Average is 11.1/5
For Iteration 3 - Average is 12.3/5
and So on.. for next two iterations.
As you can see, they are not adding up. Its just dividing the index value of your array and printing it.
So, to add the index values of your Array, You need result = result + nums[i]
Now, here is a twist. Since, you are writing result = result + nums[i], thus updating the result value. For first Iteration, there will no previous result value. No updation since previous Value is not known. Hence, you got yourself compilation error.

Find the most frequent value in an array of double in Java (without hashmaps or sorting)

Write a full Java program that does the following:
Creates an array of 100 double.
Reads in an unknown number of doubles from a file named values.txt .
There will be at least 2 distinct values, and no more than 100 distinct values in the file. The values will be in unsorted order. Values will be no smaller than 0, and no larger than 99.
Outputs the most frequently occurring value in the file.
Outputs the least frequently occurring value in the file. The value must occur at least once in order to be output.
Outputs the average of all array values.
You must create and use separate methods for each of the items #2-5.
This is what I have so far. I cannot for the life of me figure out how to get this right:
import java.util.*;
import java.io.*;
public class arrayProgram2 {
static Scanner console = new Scanner(System.in);
static final int ARRAY_SIZE = 100;
static int numOfElements = 0;
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new FileReader("values.txt"));
double[] Arr1 = new double[ARRAY_SIZE];
while (inFile.hasNext()) {
Arr1[numOfElements] = inFile.nextDouble();
numOfElements++;
}
System.out.println("There are " + numOfElements + " values.");
System.out.printf("The average of the values is %.2f%n", avgArray(Arr1));
System.out.println("The sum is " + sumArray(Arr1));
inFile.close();
} //end main
//Method to calculate the sum
public static double sumArray(double[] list) {
double sum = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
return sum;
}
//Method to calculate the average
public static double avgArray(double[] list) {
double sum = 0;
double average = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
average = sum / numOfElements;
return average;
}
} //end program
Notice I am required to make an array of double even though it is not necessary.
If all values are int than you should use int array instead of double. As all values in range 0-99. So, you can increase input value frequency. Look at below logic:
int[] freqArr= new int[100];
while (inFile.hasNext()){
int value = inFile.nextInt();
freqArr[value]++; // count the frequency of selected value.
}
Now calculate the maximum frequency from freqArr
int maxFreq=0;
for(int freq : freqArr){
if(maxFreq < freq){
maxFreq = freq;
}
}
Note: If double array is mandatory than you can also use double array like:
double[] freqArr= new double[100];
while (inFile.hasNext()){
freqArr[(int)inFile.nextDouble()]++;
}
It's possible to find a most-occurring value without sorting like this:
static int countOccurrences(double[] list, double targetValue) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == targetValue)
count++;
}
}
static double getMostFrequentValue(double[] list) {
int mostFrequentCount = 0;
double mostFrequentValue = 0;
for (int i = 0; i < list.length; i++) {
double value = list[i];
int count = countOccurrences(list, value);
if (count > mostFrequentCount) {
mostFrequentCount = count;
mostFrequentValue = value;
}
}
return mostFrequentValue;
}
Pham Thung is right : -
You read in integer inFile.nextInt(), why do you need to use double array to store them? – Pham Thung
You can achieve your first functionality in n time if its integer array.
you question says,
Values will be no smaller than 0, and no larger than 99.
So,
1. Make an array of size 100.(Counter[])
2. Iterate through values of your current array and add count to Counter array.
eg:
if double array contains
2 3 2 5 0 0 0
Our counter array will be like
location : 0 1 2 3 4 5 6 ...........100
values : 3 0 1 1 0 1 0 ..............
and so on.
You can use below algorithm for this
Sort the array (you only need to read unsorted array, but you can sort the array once read from the file)
Make double var : num, mostCommon, count = 0, currentCount = 1
Assign Arr1[0] to num
for i from 1 to length of Arr1
i. if(Arr1[i] == num)
a. Increment currentCount
ii. else
a. if(count > currentCount)
A. Assign currentCount to count
B. Assign num to mostCommon
C. Assign Arr1[i] to num
D. Assign 1 to currentCount
At the end of this loop, you will have most common number in mostCommon var and it's number of occurrence in count.
Note : I don't know how to format the algo

printMax method with array using Java...one thing I don't understand is double result = numbers[0]

I'm learning java with Intro to Java Programming 9e with Liang. Why does there have to be numbers[0] as in double result = numbers[0]? What I mean is in the brackets, why does it have to be 0?
public class VarArgsDemo {
public static void main(String[] args) {
printMax(34, 3, 3, 2, 56.5);
printMax(new double[] {1, 2, 3});
}
public static void printMax(double... numbers) {
if (numbers.length == 0) {
System.out.println("No arguments passed");
return;
}
double result = numbers[0];
for (int i = 1; i < numbers.length; i++)
if (numbers[i] > result)
result = numbers[i];
System.out.println("The max value is " + result);
}
}
You ask about what this means:
double result = numbers[0];
Taken by itself, it is just assigning the first element of the numbers array to result. The zero is an index value.
The reason for the use of the zero value is that in Java (and most programming languages!) arrays are indexed starting from zero, not from one. So for instance,
double[] array = new double[] {1.0, 2.0, 3.0};
is creating an array whose length is 3 and whose indexes are 0, 1 and 2. Of course, the value of array[0] is 1.0.
If you then look at the context, the loop following this statement is examining the other elements of the numbers array, from one to the last one (i.e. numbers.length - 1), and comparing them with result.
So from that respect, the statement you are asking about is "priming" the algorithm ... like you "prime" a pump to get it started.
If we prime the algorithm where numbers[0] will be the first value, then how does this work when the for loop starts with int i = 1, and increases up until i = 3. What happens to numbers[0]?
If the array has 3 elements, the loop finishes when i gets to 3.
Try and understand what this statement is doing:
if (numbers[i] > result)
result = numbers[i];
Pedantically ... nothing happens to numbers[0]. You are not assigning anything to it! You are assigning a value to result. Focus on what happens to that.
this indicates the index of the element in the array, it is zero based, so 0 is the first element

Categories