Print the Result
In this final step, you will enhance the vector operations program by adding formatted output and creating a function to print vector results in a clear, readable format.
Update the vector_operations.c
file with the following improved implementation:
cd ~/project
nano vector_operations.c
Add the new printing function and modify the main program:
#include <stdio.h>
#define VECTOR_SIZE 3
void readVector(float vector[], int size) {
printf("Enter %d vector components (separated by space): ", size);
for (int i = 0; i < size; i++) {
scanf("%f", &vector[i]);
}
}
float computeDotProduct(float vector1[], float vector2[], int size) {
float dotProduct = 0.0;
for (int i = 0; i < size; i++) {
dotProduct += vector1[i] * vector2[i];
}
return dotProduct;
}
void computeCrossProduct(float vector1[], float vector2[], float result[]) {
result[0] = vector1[1] * vector2[2] - vector1[2] * vector2[1];
result[1] = vector1[2] * vector2[0] - vector1[0] * vector2[2];
result[2] = vector1[0] * vector2[1] - vector1[1] * vector2[0];
}
// New function to print vector with formatting
void printVector(const char* label, float vector[], int size) {
printf("%s: [", label);
for (int i = 0; i < size; i++) {
printf("%.2f%s", vector[i], (i < size - 1) ? ", " : "");
}
printf("]\n");
}
int main() {
float vector1[VECTOR_SIZE];
float vector2[VECTOR_SIZE];
float crossProductResult[VECTOR_SIZE];
// Input vectors
printf("Vector Input:\n");
printVector("Vector 1", vector1, VECTOR_SIZE);
readVector(vector1, VECTOR_SIZE);
printVector("Vector 2", vector2, VECTOR_SIZE);
readVector(vector2, VECTOR_SIZE);
// Compute results
float dotProduct = computeDotProduct(vector1, vector2, VECTOR_SIZE);
computeCrossProduct(vector1, vector2, crossProductResult);
// Print formatted results
printf("\nVector Operations Results:\n");
printVector("Vector 1", vector1, VECTOR_SIZE);
printVector("Vector 2", vector2, VECTOR_SIZE);
printf("Dot Product: %.2f\n", dotProduct);
printVector("Cross Product", crossProductResult, VECTOR_SIZE);
return 0;
}
Compile and run the updated program:
gcc vector_operations.c -o vector_operations
./vector_operations
Example output:
Vector Input:
Vector 1: [0.00, 0.00, 0.00]
Enter 3 vector components (separated by space): 1 2 3
Vector 2: [0.00, 0.00, 0.00]
Enter 3 vector components (separated by space): 4 5 6
Vector Operations Results:
Vector 1: [1.00, 2.00, 3.00]
Vector 2: [4.00, 5.00, 6.00]
Dot Product: 32.00
Cross Product: [-3.00, 6.00, -3.00]
Explanation
- Added
printVector()
function to create consistent, formatted vector output
- Enhanced
main()
function to demonstrate vector input and result printing
- Improved readability of vector and computation results
- Provides a clean, professional output format for vector operations