0% found this document useful (0 votes)
8 views

Arrays in Java Part 2

Uploaded by

Dhavan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Arrays in Java Part 2

Uploaded by

Dhavan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Accessing Array elements using for loop:

syntax:

for(int i=0;i<arrayname.length;i++){
//process
}

ex:

int x[]={4,2,5,6,8,9,2,5};
//print all array elements
for(int i=0;i<x.length;i++) {
System.out.print(x[i]+" ");
}

Iterating array elements using for-each loop:

iterator -> object,can store morethan one element.


syntax:

for(datatype variable:iterator) {
//process;
}

ex:
int x[]={4,2,5,6,8,9,2,5};
//iteration
for(int data: x){
System.out.print(data+" ");
}

//program to add all array elements

int arr[]={4,2,5,6,7,5,4,3,4,5};
int res=0;

for(int d:arr){
res=res+d;
}
System.out.println(sum);

//program to add only even numbers stored in array

int arr[]={4,2,5,6,7,5,4,3,4,5};
int sum=0;

for(int d:arr){
if(d%2==0){
sum=sum+d;
}
}
System.out.println(sum);

//program to add only odd numbers stored in array


int arr[]={4,2,5,6,7,5,4,3,4,5};
int sum=0;
for(int d:arr){
if(d%2==1){
sum=sum+d;
}
}
System.out.println(sum);

//program to print only prime numbers stored in array

int arr[]={4,2,5,6,7,5,4,3,4,5};
int flag=0; // prime number

for(int d:arr){
for(int count=2;count<d/2;count++){
if(d%count==0){
flag=1;//non-prime number
break;// stop the inner loop
}
}
if(flag==0){
System.out.println(d);
}
flag=0;
}

//program to count a number how many times it is repeated

int arr[]={4,2,5,6,7,5,4,3,4,5};
int count=0; // counter
int ele=4; // element
for(int d:arr){
if(d==ele){
count++;
}
}
System.out.println(count);

//program to print index numbers of repeated element


int arr[]={4,2,5,6,7,5,4,3,4,5};
int count=0; // counter
int ele=4; // element
int index=0;
for(int d:arr){
if(d==ele){
System.out.println("Element found at "+index);
count++;
}
index++;
}
System.out.println(count);

You might also like