# Thread: Finding the length of a vector

1. Member
Join Date
Feb 2013
Posts
33
Rep Power
0

## Finding the length of a vector

I'm not sure if I did this right but when I run it, the answer is 0.0. I want to know what I am doing wrong.

Write a function that finds the length of a vector.
double Length( double X[ ] )
The length of a vector is the square root of the sum of the squares of the elements in the array. Use dynamic memory and allocate 10 elements for X. Initialize the data values of X to the counting numbers 1-10.

Java Code:
```class Length {
public Length() {}

double length ( double[] X ) {
double sum = 0;
double l = 0;

for ( int i = 1; i < X.length; i++ ) {
sum += Math.pow(X[i], 2);
l = Math.sqrt(sum);
return l;
}
}
}```

Java Code:
```class LengthTest {
public static void main( String [] args ) {
Length myLength = new Length();

double[] X;

X = new double [ 11 ];

System.out.println( );
System.out.println("Length of the vector is " + myLength.length(X) + ".");
System.out.println( );

}
}```
Last edited by wheehoowaffles; 04-06-2013 at 03:14 AM.

2. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
18

## Re: Finding the length of a vector

What are the numbers in the array array when you pass it to the length() method?

Also it would be a good idea to add some braces to the for loop in the length() method to show clearly just what is being repeated each time around the loop. (although this isn't the problem here. but every ounce of clarity helps when - or before - things go wrong!)

3. Member
Join Date
Feb 2013
Posts
33
Rep Power
0

## Re: Finding the length of a vector

It said to initialize the data values of X from 1-10 so I tried doing it by using a for loop.

4. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
18

## Re: Finding the length of a vector

You see that the place to do that initialisation is in the main() method, right?

5. Member
Join Date
Feb 2013
Posts
33
Rep Power
0

## Re: Finding the length of a vector

Yes I know. I figured it out. Thanks anyway.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•