Computer Science, asked by anaborah77, 4 days ago

write a program in Java to initialize a SDA of 10 numbers and find the average of the odd numbers

pls help me​

Answers

Answered by anindyaadhikari13
8

SOLUTION.

Here comes my approach for the problem.

import java.util.*;

public class Array{

   public static void main(){

       Scanner sc=new Scanner(System.in);

       System.out.println("Enter 10 elements. ");

       int a[]=new int[10];

       int c=0;

       float sum=0;

       for(int i=0;i<10;i++){

           System.out.print("> ");

           a[i]=sc.nextInt();

           if(a[i]%2!=0){

               sum+=a[i];

               c++;

           }

       }

       sc.close();

       sum/=(float)c;

       System.out.println("Average of odd numbers: "+sum);

   }

}

LOGIC.

  • Accept the numbers.
  • Initialise sum=0, count=0. count stores the number of odd numbers present in array.
  • If number is not divisible by 2, add the number to sum and increment the value of count by 1.
  • Divide sum by count and store it in same variable.
  • Display the value of the variable 'sum'.

See attachment for output.

Attachments:

anindyaadhikari13: Thanks for the Brainliest ^_^
Answered by kamalrajatjoshi94
1

Answer:

Program:-

import java.util.*;

public class Main

{

public static void main(String args[])

{

Scanner in=new Scanner(System.in);

int a[]=new int[10];

int sum=0,c=0;

double avg=0;

System.out.println("Enter the elements of the array:");

for(int i=0;i<a.length;i++)

{

a[i]=in.nextInt();

}

System.out.println("Given Array:"+Arrays.toString(a));

for(int i=0;i<a.length;i++)

{

if(a[i]%2!=0)

{

sum=sum+a[i];

c++;

}

}

avg=sum/(double)c;

System.out.println("The average of odd elements="+avg);

}

}

Logic:-

  • Enter the elements of the array
  • If an element is not divisible by 2 i.e an odd element, so c is incremented. Variable c is the number of odd elements that is present in the array.
  • Finally , avg=sum/(double) c (explicit conversion in order to get the correct average as Java treats '/' as only the quotient not in decimal places so explicit conversion need to be there.
  • Finally print the average.

Output is attached.

Attachments:
Similar questions