Reputation: 1
Here is a code in C language I got stuck.
#include<stdio.h>
int main(){
int Force_V[2], w;
int i, j, Disp_V[2];
printf("Enter Force Vector: ");
for(i=0; i<=2; i++){
scanf("%d", &Force_V[i]);
}
printf("Enter Displacement Vector: ");
for(j=0; j<=2; j++){
scanf("%d", &Disp_V[j]);
}
printf("Force vector: %di+%dj+%dk", Force_V[0],Force_V[1],Force_V[2]);
printf("\nDisplacement vector== %di+%dj+%dk", Disp_V[0],Disp_V[1],Disp_V[2]);
w= (Force_V[0]*Disp_V[0])+(Force_V[1]*Disp_V[1])+(Force_V[2]*Disp_V[2]);
printf("The work: %df", w);
return 0;
}
output for Force_V[2] is showing the output of Disp_V[0]. Can anyone tell me where's the error?
Upvotes: 0
Views: 76
Reputation: 1460
Note that C does not have strict array index checking.
You declared the arrays int Force_V[2]
which denotes that it has two integer memory location indexed 0 and 1. Further on you try to set and access the memory using index 2, which might be used by some other variable. In your case it is being referred by Disp_V, but usually this gives undefiined behaviuor.
#include<stdio.h>
int main(){
int Force_V[3], w;
int i, j, Disp_V[3];
printf("Enter Force Vector: ");
for(i=0; i<3; i++){
scanf("%d", &Force_V[i]);
}
printf("Enter Displacement Vector: ");
for(j=0; j<3; j++){
scanf("%d", &Disp_V[j]);
}
printf("Force vector: %di+%dj+%dk", Force_V[0],Force_V[1],Force_V[2]);
printf("\nDisplacement vector== %di+%dj+%dk", Disp_V[0],Disp_V[1],Disp_V[2]);
w= (Force_V[0]*Disp_V[0])+(Force_V[1]*Disp_V[1])+(Force_V[2]*Disp_V[2]);
printf("The work: %df", w);
return 0;
}
Upvotes: 1
Reputation: 4111
The array int Force_V[2]
has two cells so you must change your loop condition like this :
for(i=0; i<2; i++)
Upvotes: 1