0

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?

2
  • 3
    you need to declare arrays Force_V and Disp_V of size 3. Commented Nov 8, 2020 at 4:00
  • Since you seem to be using 3D vectors, the arrays need to be of size 3, not 2. Your loops should be for (int i = 0; i < 3; i++) — this is the idiomatic form for a loop over an array of three elements. Commented Nov 8, 2020 at 4:04

2 Answers 2

1

The array int Force_V[2] has two cells so you must change your loop condition like this :

for(i=0; i<2; i++)
Sign up to request clarification or add additional context in comments.

Comments

1

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;

}

1 Comment

It's better in C (more idiomatic C) to use for (int i = 0; i < 3; i++) to loop over the elements of an array with 3 elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.