Sie sind auf Seite 1von 7

Example 1: Program to find the

average of numbers using array


public class JavaExample {

public static void main(String[] args) {


double[] arr = {19, 12.89, 16.5, 200, 13.7};
double total = 0;

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


total = total + arr[i];
}

/* arr.length returns the number of elements


* present in the array
*/
double average = total / arr.length;

/* This is used for displaying the formatted


output
* if you give %.4f then the output would have
4 digits
* after decimal point.
*/
System.out.format("The average is: %.3f",
average);
}
}
Program to print EVEN and ODD
elements from an array in java
import java.util.Scanner;

public class ExArrayEvenOdd


{
public static void main(String[]
args)
{
// initializing and creating
object.
int n;
Scanner s = new
Scanner(System.in);

// enter number for elements.


System.out.print("Enter no. of
elements you want in array : ");
n = s.nextInt();
int a[] = new int[n];

// enter all elements.


System.out.println("Enter all
the elements : ");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Odd numbers
in the array are : ");
for(int i = 0 ; i < n ; i++)
{
if(a[i] % 2 != 0)
{
System.out.print(a[i]+"
");
}
}
System.out.println("");
System.out.print("Even numbers
in the array are : ");
for(int i = 0 ; i < n ; i++)
{
if(a[i] % 2 == 0)
{
System.out.print(a[i]+"
");
}
}
}
}
Output
Enter no. of elements you want in array
: 15
Enter all the elements :
5
6
9
3
12
55
44
66
85
95
31
98
74
11
12
Odd numbers in the array are : 5 9 3 55
85 95 31 11
Even numbers in the array are : 6 12 44
66 98 74 12
Example 1 - Comments
Question
ADDQUESTION

Solution
/**
* Example 1 - Comments
*/
class Comments {
//This is single line comment

/*
This is a multi-line comment, which can span across
lines.
*/
public static void main(String[] arg) {
int /* The delimited comment can extend over a
part of the line */ x = 42;
System.out.printf("%d",x);
}
}

Example 1: Concatenate Two Arrays using


arraycopy
import java.util.Arrays;

public class Concat {

public static void main(String[] args) {


int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};

int aLen = array1.length;


int bLen = array2.length;
int[] result = new int[aLen + bLen];

System.arraycopy(array1, 0, result, 0,
aLen);
System.arraycopy(array2, 0, result,
aLen, bLen);
System.out.println(Arrays.toString(result));
}
}

Das könnte Ihnen auch gefallen