user4766244
user4766244

Reputation: 69

How to get each element of a array from user input then pass it to a function in another file in C

How can I get each element of an array from user input then pass it to a function in another file. I'm having trouble and need help please. This my code.

main.c

#include <stdio.h>
#include "lab8.h"

int x[100];
int y[100];

int main(void) {  
    int count, i, product;

    printf("Enter the length of both arrays\n");
    scanf("%d", &count);

    printf("Enter the first array's elements\n");
    for(i=0; i<count; i++){
        scanf("%i", &x[i]);
    }
    printf("Element: %i\n", x[i]);
    printf("Enter the second array's elements\n");
    for(i=0; i<count; i++){
        scanf("%i", &y[i]);
    }   
    product = inner_product(x, y, count);
    printf("Inner product: %i\n", product);

    return(0);
}

lab8.c

#include <stdio.h>
#include "lab8.h"

int inner_product(int a[], int b[], int count) {
    int i;
    int result = 0;

    for( i=1; i<count; i++) {
        result = result + (a[i] * b[i]);
    }    
    return result;
}

It only seems to multiply the last element entered for both arrays heres the output.

Enter the length of both arrays
2
Enter the first array's elements
1
2
Element: 0
Enter the second array's elements
3
3
Inner product: 6

Upvotes: 0

Views: 55

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

The problem is that you are iterating from 1 and you should iterate from 0, in the inner_product() function

for( i=1; i<count; i++) {
/*     ^ this should be 0 */

also, don't use global variables specially because you got the rest of it right, you are passing the arrays as arguments to the inner_product() function.

Upvotes: 2

Related Questions