displacement of all values of the elements to the next position, last value must be in the first position

Asked

Viewed 36 times

-1

Good afternoon, can anyone help me develop that question? (c) rotation of the elements of the vector, with the displacement of all values of the elements for the next position, except the last value, which shall be placed in the of the first element; had used v[i]=v[i+1];, but it is not working, I would like it to be like: (assuming the vector tam. is 9) and the values were: 10 2 3 4 5 6 7 8 9 and I want you to print 9 10 2 3 4 5 6 7 8, but this printing 9 10 3 4 5 6 7 8 9, follows the attachment I have done so far:

#include <stdio.h>
int main() {
    int v[10]; int soma=0; int val; int qtd = 0;
    v[10] = 0;
    for (int i = 0; i < 9; ++i) {
        scanf("%d", &v[i]);
        soma += v[i];
        if(v[i]==0) {
            printf("Digite um numero maior que 0.\n");
            scanf("%d", &v[i]);
        }
    }

    for (int i = 0; i < 9; ++i) {
        printf("%d ", v[i]);
    }

    printf("\nSoma: %d\n", soma);
    int aux = v[0];
    for (int i = 0; i < 9; ++i) {
        if (i==0) {
            v[i] = v[8];
        }
        if (i==8) {
            v[1] = aux;
        }
    }

    printf("\n");
    for (int i = 0; i < 9; ++i) {
        printf("%d ", v[i]);
    }

    printf("\nInforme o valor para verificar se existe no vetor.\n");
    scanf("%d", &val);
    for (int i = 0; i < 9; ++i) {
        if (val == v[i]) {
            qtd++;
        }
    }
    printf("Quantidade de vezes em que aparece no vetor: %d\n", qtd);

    return 0;
}

1 answer

1


What you want is to do a right shift on the vector. The code to do this is this, n being the number of elemtos of the vector:

    temp=a[n-1];
    for(i=n-1;i>0;i--)
    {
        a[i]=a[i-1];
    }
    a[0]=temp;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.