Turn Desktop View Off
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

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();

}

        C program to add two vectors of size n



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), 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