Create arrays A, B and C of size 3, perform C = A + B.
Learn how to perform element-wise addition of two arrays in C
๐งพ Step-by-Step Explanation
๐น Step 1: Include Header File
#include <stdio.h>
This includes the standard input-output library which provides:
printf()
for output displayscanf()
for user input- Other essential I/O functions
๐น Step 2: Declare Arrays and Variables
int A[3], B[3], C[3];
int i;
- A[3] and B[3]: Arrays to store user inputs (3 elements each)
- C[3]: Array to store the sum of corresponding elements
- i: Loop counter variable for array traversal
๐น Step 3: Input Values in Array A
for(i = 0; i < 3; i++) {
printf("A[%d]: ", i);
scanf("%d", &A[i]);
}
This loop:
- Runs 3 times (i = 0 to 2)
- Prompts user for each element with index position
- Stores input values in array A
- Uses
&A[i]
to get memory address for storage
๐น Step 4: Input Values in Array B
for(i = 0; i < 3; i++) {
printf("B[%d]: ", i);
scanf("%d", &B[i]);
}
Similar to Step 3, but for array B:
- Same loop structure
- Stores values in array B
- Maintains parallel indexing with array A
๐น Step 5: Add Corresponding Elements
for(i = 0; i < 3; i++) {
C[i] = A[i] + B[i];
}
Performs element-wise addition:
- Adds A[0] + B[0] and stores in C[0]
- Adds A[1] + B[1] and stores in C[1]
- Adds A[2] + B[2] and stores in C[2]
- Process is called vector addition
๐น Step 6: Display Result
for(i = 0; i < 3; i++) {
printf("C[%d] = %d\n", i, C[i]);
}
Outputs the result array C:
- Prints each element with its index
- Uses
\n
for newline between elements - Shows the sum of corresponding elements from A and B
๐งช Sample Output
Enter 3 elements of array A:
A[0]: 2
A[1]: 4
A[2]: 6
Enter 3 elements of array B:
B[0]: 1
B[1]: 3
B[2]: 5
Resultant array C (A + B):
C[0] = 3
C[1] = 7
C[2] = 11
๐ Key Concepts Covered
Array
A linear data structure that stores elements of the same type in contiguous memory
Element-wise Addition
Adding corresponding elements from two arrays of the same size
for Loop
Control structure used to traverse and process array elements sequentially
Array Indexing
Accessing individual array elements using their position (0-based index)
I/O Operations
Using printf() and scanf() for formatted output and input
No comments:
Post a Comment