Hi Im new to Java Im trying to make a counter. What Id like to do is calculate the numbers from 1 to x, for example if x is 5, calculate 1 + 2 + 3 + 4 + 5.
This is what I wrote, but I get 6 as output instead of 15.
public class Counter {
public int count (int x){
int contatore = 0;
int sum = 0;
for (int i = 0; i <= x; i++) {
sum = i;
System.out.println(i);
}
System.out.println(sum);
return sum;
}
}
You need to add i to the sum in each iteration of the loop:
public int count (int x) {
int contatore = 0;
int sum = 0;
for (int i = 0; i <= x; i++) {
sum += i;
System.out.println(i);
}
System.out.println(sum);
return sum;
}
You are assigning the loop variable to the sum - you need to add it to the sum
public int count (int x){
int sum = 0;
for (int i = 0; i <= x; i++) {
sum = sum + i;
}
return sum;
}
As others have noted, you can use the following shorthand notation for addition with assignment.
sum += i; // equivalent to sum = sum + i;
Related
I have to create classes to be implemented with the main class someone else has and for some reason I am not getting the right outputs, I'm not sure where this error is coming from.
Expected Output:
Median = 44.5
Mean = 49.300
SD = 30.581
public class StatPackage {
int count;
double [] scores;
StatPackage() {
count = 0;
scores = new double[500];
}
public void insert (double value) {
if (count < 500){
scores[count] = value;
++ count;
}
}
public double Mean () {
double sum = 0;
//For loop for calculating average or mean
for(int i = 0; i < count; i++){
sum += (scores[i]);
}
double average = sum/count;
return average;
}
public double Median() {
int min;
int tmp;
int size;
for (int i = 0; i < count; i ++)
{
min = i;
for (int pos = i + 1; pos < count; pos ++)
if (scores [pos] < scores [min])
min = pos;
tmp = (int)scores [min];
scores [min] = scores [i];
scores [i] = tmp;
}
double median = 0;
if (count % 2 == 0){
median = (scores[scores.length/2-1] + scores[scores.length/2])/2;
}
else {
median = (scores[((scores.length/2))]);
}
return median;
}
public double Variance () {
double variance = 0;
double sum = 0;
//For loop for getting the variance
for(int i = 0; i < count; i++){
sum += scores[i];
variance += scores[i] * scores[i];
}
double varianceFinal = ((variance/count)-(sum*sum)/(count*count));
return (varianceFinal);
}
public double StdDev (double variance) {
double sum = 0;
for(int i = 0; i < count; i++){
sum += scores[i];
variance += scores[i] * scores[i];
}
double varianceFinal = ((variance/count)-(sum*sum)/(count*count));
return Math.sqrt(varianceFinal);
}
You have a problem in your Median() method. Try changing
if (count % 2 == 0){
median = (scores[scores.length/2-1] + scores[scores.length/2])/2;
}
else {
median = scores[scores.length/2];
}
to
if (count % 2 == 0)
median = (scores[count/2] + scores[count/2 - 1])/2;
else
median = scores[count/2];
Because you have a fixed-size array with 500 elements, the code you have will return the mean value of the items at position 249 and 250, which will be 0 if you have less than 251 values in your array.
In a fit of charity/insanity, I quickly wrote a driver program to try to test this thing.
public static void main(String[] args)
{
StatsPackage sp = new StatsPackage();
for (int i = 0; i < 101; ++i) {
sp.insert(i);
}
System.out.println("count: " + sp.count);
System.out.println("mean: " + sp.Mean());
System.out.println("median: " + sp.Median());
System.out.println("variance: " + sp.Variance());
}
Beyond the fact the median doesn't compute the right values (and #BadCash may have the solution for that problem), there is no ArrayOutOfBounds thrown.
EDIT: making the update as #BadCash suggested to the Median method seems to resolve the median not giving the correct answer.
So this is what I have:
public static void Positive () {
int limit = 50;
for(int i=1; i <= limit; i++){
System.out.print(i + ", ");
}
}
That prints out all numbers 1-50 with a loop
How do I return the sum of this using a loop?
I changed the return type to int.
public static int Positive () {
int limit = 50;
int sum = 0;
for(int i=1; i <= limit; i++){
System.out.print(i + ", ");
sum += i;
}
return sum;
}
Another approach
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
You havent cleared yet that you want to return the value or just print it from the function so you can use either of the approach in answers of your question. One with int type can return the value and print as well
Here is what you can do
public static void Positive () {
int limit = 50;
int total = 0;
for(int i=1; i <= limit; i++){
total = total + i;
}
System.out.print(total);
}
Write a function int bentley(int a) that return the index, j, from a pair of indices (i,j) such that a[i]+a[i+1]++a[j-1] is maximum over all such pairs (i,j).
^^This is the question i have to answer. Im assuming "a[i]+a[i+1]++a[j-1]" means from a[i ] to a[j-1]. So far this is what i have:
public static int bentley(int[] a) {
int max = 0;
int oldsum = 0;
int sum = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
sum = oldsum + a[j];
if (sum > oldsum) {
max = j;
oldsum = sum;
}
else {
sum = oldsum;
}
}
}
return max;
}
It doesnt work, i dont know why or how to fix it.
public void calculatePercentage(int exam[][])
{
int perc = 0;
for (int i = 0; i < examen.length; i++)
{
for (int[] score : exam)
perc += score;
perc /= exam.length;
}
}
Hello,
I am really stuck at this one. I want to create a new mathod calculatePercentages given the parameter exam[][]. The double array exam holds 3 rows of elements. What the method has to do is simple calculate the sum of each row. The answer is probably quite simple, but I just don't know how to do it.
For a single array, I guess the code is:
double perc = 0;
for(int score : exam)
{
perc += score;
}
perc /= (exam.length);
return perc;
The exam[][] could look like:
|10 12 18 5 3 |
|12 3 5 15 20 |
|20 15 13 11 9 |
The output percentage[] should like:
{48,55,68} Each element of percentage[] is the sum of the elements of 1 row of exam[]
The double array exam holds 3 rows of elements. What the method has to do is simple calculate the sum of each row.
The name makes no sense, but it does what you want it to do.
public int[] calculatePercentage(int exam[][]) {
int[] sums = new int[exam.length];
for (int i = 0; i < exam.length; i++) {
int sum = 0;
for (int j = 0; j < exam[i].length; j++) {
sum += exam[i][j];
}
sums[i] = sum;
}
return sums;
}
Also a double array would be double[], you are talking about two dimensional int arrays int[][]
EDIT
Pshemo pointed out a shorter solution is possible:
public int[] calculatePercentage(int exam[][]) {
int[] sums = new int[exam.length];
for (int i = 0; i < exam.length; i++) {
for (int j = 0; j < exam[i].length; j++) {
sums[i] += exam[i][j];
}
}
return sums;
}
or even just
public int[] calculatePercentage(int exam[][]) {
int[] sums = new int[exam.length];
for (int i = 0; i < exam.length; i++)
for (int j = 0; j < exam[i].length; j++)
sums[i] += exam[i][j];
return sums;
}
but I still prefer the first one, for it's readability.
for (int i = 0; i < exam.length; i++) {
int sum = 0;
for (int j = 0; j < exam[i].length; j++) {
sum += exam[i][j];
}
}
using for each
for (int x[] : exam) {
for (int y : x) {
sum += y;
}
}
I have an array of 100 numbers and I only gave the array even values. How can I print out how many elements of the array I have to add to obtain a sum < than 1768 using a WHILE LOOP? The following is what I have so far and I am stuck... thanks in advance for the help
void setup() {
int[] x = new int[100];
int i=0;
int sum=0;
for(i=0; i<100; i++) {
if (i%2==0) {
x[i]=i;
sum+=x[i];
}
}
}
void setup() {
int i = 0;
int sum = 0;
int counter = 0;
while (sum < 1768) {
sum += i;
i += 2;
counter++;
}
System.out.println(counter);
}
You start with the even index of 0. Then just skip odd numbers by using i += 2.
If the number of elements is limited with 100, add i < 200 to the while condition:
while (sum < 1768 && i < 200)
The array of 100 even numbers will contain numbers from 0 to 200.
The variable counter will contain the number of additions performed. Its value will be equal to i / 2, so you can remove that additional variable.
You can use this loop and element number would be i+1.
for(int i=0,k=0; k<1768; i++,k+=x[i]) {
System.out.println(x[i]+" - "+k);
}
While loop -
int i=0,k=0;
while(k<1768; ) {
System.out.println(x[i]+" - "+k);
i++,k+=x[i];
}
You are skipping indexes in your array.You are only filling every other 'slot'
Also, it would probably be easier to use a while loop to check against your max value (1728)
int[] x = new int[100];
int i = 0;
int sum = 0;
int max = 1728;
while (sum < max && i < 100)
{
x[i] = i*2;
if ((x[i] + sum) < max)
{
sum += x[i];
}
i++;
}
void setup() {
int[] x = new int[100];
int maxValue = 1768;
int i;
int sum=0;
while(sum<maxValue) {
if (i%2==0) {
x[i]=i;
sum+=x[i];
i++;
}
}
System.out.println(i+" Elements needed")
}
following is code:
void setup() {
int[] x = new int[100];
int i=0;
int sum=0;
for(i=0; i<100; i++) {
if (i%2==0) {
sum += i;
if(sum<1768){
num +=1;
}
}
}
}