# Finding the length of a vector

Printable View

• 04-06-2013, 02:56 AM
wheehoowaffles
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.

What i'm asked to do:

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.

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;         }         } }```

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( );         } }```
• 04-06-2013, 03:03 AM
pbrockway2
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!)
• 04-06-2013, 03:13 AM
wheehoowaffles
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.
• 04-06-2013, 03:26 AM
pbrockway2
Re: Finding the length of a vector
You see that the place to do that initialisation is in the main() method, right?
• 04-06-2013, 03:34 AM
wheehoowaffles
Re: Finding the length of a vector
Yes I know. I figured it out. Thanks anyway.