Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

ADD Array Problem

  Asked By: Wayne    Date: Jul 03    Category: Java    Views: 911
  

I have to add two array in a list. Say the list is n size from that
n size you have to add two array together.

Problem : a[] = {1,2,3,....120,.....,n};
a[] = {1,2,3,....120,.....,n};
__________________________________________________
public class AddArray {
public static void main( String[] args ) {

int a[] = {2,3,5,6,7,8,9}; // Could be n size going thru the list
int b[] = {5,7,2,9}; // also could be n size

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

System.out.println( a[i]+b[i]) + ", " };
}
____________________________________________________

This program works but it gives me more than what i need something
worong in my for loop. I need some help.

The output should be : 7, 10, 7, 15, 7, 8, 9

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Jamie Roberts     Answered On: Jul 03

I think this must solve your problem...

public class AddArray {
public static void main( String[] args ) {

int a[] = {2,3,5,6,7,8,9}; // Could be n size  going thru the list
int b[] = {5,7,2,9}; // also could be n size

if(a.length>b.length){
int temp=b.length;
for(int i=0;i<a.length;i++){
if(temp!=0){
System.out.println(a[i]+b[i]);
temp--;
}else{
System.out.println(a[i]);
}
}
}else{
int temp=a.length;
for(int i=0;i<b.length;i++){
if(temp!=0){
System.out.println(a[i]+b[i]);
temp--;
}else{
System.out.println(b[i]);
}
}
}


}
}

 
Didn't find what you were looking for? Find more on ADD Array Problem Or get search suggestion and latest updates.




Tagged: