For two vectors a and b having n elements each, the addition operation yields a vector (say c) of size n. The ith element of the result vector is obtained by adding the corresponding vector elements, i.e., ci =ai+ bi. The algorithm to perform the desired addition is given below.
Read n, the number of elements in given vectors
Read vector a Read vector b Perform vector addition c = a + b Print result vector c
The program given below implements this algorithm in a straight-forward way using a separate for loop for the vector operation.
/* Vector addition */ #include<stdio.h> int main() { int a[10], b[10]; /* vectors to be added */ int c[10]; /* result vector */ int n, i; clrscr(); /* read vectors a and b */ printf("Enter vector size: "); scanf("%d", &n); printf("Enter elements of vector a:\n"); for (i = 0; i < n; i++) scanf("%d", &a[i]); printf("Enter elements of vector b:\n"); for (i = 0; i < n; i++) scanf("%d", &b[i]); /* perform vector addition */ for (i = 0; i < n; i++) c[i] = a[i] + b[i]; /* print addition vector C */ printf("Addition vector:\n"); for (i = 0; i < n; i++) printf("%d ", c[i]); getch(); }