Member Avatar for Member #866461

how do i make a program that calculates the product of two vectors in C ?

this is what i have but i think im doing it wrong i need some help?

#include <stdio.h>
double inner(double m[ ] , double n[ ] , int size ) ;
int main( int argc, char *argv[ ] ) {

int i,k ;

double m[8] , n[8] ;

for(i = 0 ; i < 8 ; i++ ) {

printf("Please enter a number for m :") ;
scanf("%lf",&m[i]) ;
}
for(k=0 ; k < 8 ; k++ ) {

printf("{{lease enter a number for n :") ;
scanf("%lf",&n[i]) ;
}

printf("The inner product of the two vectors is : %lf ",inner(m,n,8 ) ) ;


return 0 ;

}


double inner(double m[ ] , double n[ ] , int size ){

int j ;
double sum = 0.0 ;

for( j = 0 ; j < size-1 ; j++){

sum =+ (m[j] * n[j]) ;

}

return sum ;

}

Dani AI

Generated

A concise diagnostic and minimal fixes building on 's fencepost note.

The algorithm (dot/inner product = sum of pairwise products) is fine, but the posted code has three practical bugs that stop it from working as intended:

  • The second input loop calls scanf with &n[i] instead of &n[k], so the n array never receives the intended values.
  • The inner-product loop uses j < size - 1, which omits the last element; it should iterate j < size.
  • The accumulation uses sum =+ (m[j] * n[j]), which assigns the positive product to sum instead of adding; use sum += m[j] * n[j];.

A compact, correct inner implementation (keeps intent clear and avoids the above mistakes):

double inner(const double m[], const double n[], int size)
{
    double sum = 0.0;
    int j;
    for (j = 0; j < size; ++j)
        sum += m[j] * n[j];
    return sum;
}

Additional practical notes: ensure the second input loop uses &n[k] and fix the prompt text; always check scanf return values for robustness; print the final result with a trailing newline; enable compiler warnings (e.g. -Wall -Wextra) to catch typos like =+; consider using size_t for lengths and const on input arrays to document intent. Testing with small, known vectors (for example all ones) quickly verifies correctness.

Recommended Answers

All 3 Replies

Your inner() function doesn't multiply the last set of values. On line 33, the loop termination should be j < size.

That's the only issue that comes to mind; assuming your inner product algorithm is correct.

Member Avatar for Member #866461

i meant calculating the inner product of two vectors , I dont think my inner function is correct thats why I need help with it :(

Ah ... well, that one's a math question. From a quick scan of Wikipedia, I believe your algorithm is right (except for the fencepost error at the end). You might want to check that part on a math forum...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.