# C program to add two vectors of size n

by Dinesh Thakur Category: Array

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

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.

#include<stdio.h>

int main()

{

int a, b;     /* vectors to be added */

int c;              /* 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]);

for (i = 0; i < n; i++)

c[i] = a[i] + b[i];

/* print addition vector C */

for (i = 0; i < n; i++)

printf("%d ", c[i]);

getch();

} Dinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles