eGevol
eGevol

Reputation: 21

Scanf in to array

This a dot_product function of 2 vectors of the same length.

I don't understand how to build the array because how the machine will know which input goes to which input (for example i want a={1,2,3} but the input of 123 will come a[0]= 123)...

How do I make end of array[index] input and how do I make end of the whole array.

#include <stdio.h>
#include <stdlib.h>
#define MAXINPUT 100
int dot_product(int v[], int u[], int n)
{
    int result = 0;
    int i;
    for (i=0; i < n; i++)
       result += v[i]*u[i];
    return result;
}
 int main(){
int v1[MAXINPUT];
int v2[MAXINPUT];
int count = 0 
int i,print;


printf(" first vector:");
for(i=0;i<MAXINPUT;i++){
  scanf("%d", &v1[i]);
  count +=1;
}
printf(" second vector:");
for(i=0;i<MAXINPUT;i++)
  scanf("%d", &v2[i]);
print = dot_product(v1, v2, count);
printf("v1*v2:%d",print);
return 0;
}

Upvotes: 2

Views: 143

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

The first problem I observe here is with

 count +=1;

where count is an uninitialized automatic local variable, which makes it's initial value indeterminate. Attempt to use that value invokes undefined behavior.

You should be initializing count to 0.

That said, here, you're depending on the user to input the second array with exact same dimension of that of the first one. In case that does not happen, your program will blow up, as you did not initialize the arrays, again.

Upvotes: 1

Related Questions