#Help with my code

28 messages · Page 1 of 1 (latest)

patent moat
#

im trying to do a loop and finding the average of 50 odd numbers using an array
but for some reason when i divide the sum with length it always show's 0.

public class KAtiallo {

public static void main(String[] args) {
    int[] Pinakas = new int[100];
    int sum=0;
    int length = Pinakas.length;
    for (int i=1; i<Pinakas.length; i=i+2) {
        sum+=Pinakas[i];
    }
    double average = sum/length;
    System.out.println(average);
    
}

}

haughty cedarBOT
#

This post has been reserved for your question.

Hey @patent moat! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

#
im trying to do a loop and finding the average of 50 odd numbers using an array
but for some reason when i divide  the sum with length it always show's 0.



public class KAtiallo {

    public static void main(String[] args) {
        int[] Pinakas = new int[100];
        int sum=0;
        int length = Pinakas.length;
        for (int i=1; i<Pinakas.length; i=i+2) {
            sum+=Pinakas[i];
        }
        double average = sum/length;
        System.out.println(average);
        
    }
}
river creek
#

all elements of an int[] are 0 by default

#

until you set them to something else

patent moat
#

so should i change them to float?

river creek
#

those are also 0 by default

#

if you want otjer values, you need to set those values

#

if ypu want them to be 0, 1, 2, 3, 4, ..., you need to set these

patent moat
#

by default?

#

i mean i need to type them 1 by 1?

river creek
#

you can use a loop

patent moat
#

thats what im trying to do and ive been stuck for an hour

river creek
#

just create a loop over all elements and set these elements in the array

patent moat
#

ok.
but i have another question. How do i add all the odd numbers in my array?

river creek
#

like you are doing but currently, you are skipping every second number

#

and all numbers are 0 so the sum is 0

patent moat
#

sorry but i still dont understand

river creek
#

forget the thing with skipping - I missread the odd

#

you can check whether a numver is odd using theNumber%2==1

#

if it is, you add it to the sum

#

if it isn't, you don't

patent moat
#

ok thx

#

lemme go try that

#

ay man thx for the help

#

finally did it

river creek
#

nice