Vector that generates elements

Asked

Viewed 74 times

1

I would like to generate a vector where your next position element is added to 1. For example: be a vetor[3], would like that v[0] = 1 and v[1] = v[0] + 1, v[2] = v[1] + 1 and so on. How would you do that?

Follow my code for now:

#include <stdio.h>
#include<stdlib.h>

int main(){

    int N, M, i;

    int *v;

    printf ("Entre com N: ");
    scanf ("%d", &N);
    printf ("Entre com M: ");
    scanf ("%d", &M);

    v = (int *)malloc(M * sizeof (int));

    v[0] = 1;

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

2 answers

2


The main problem of the code is that it is not assigning anything to the vector. I removed what was not being used, organized and modernized the code.

#include <stdio.h>
#include<stdlib.h>

int main() {
    int M;
    printf("Entre com M: ");
    scanf("%d", &M);
    int *v = malloc(M * sizeof (int));
    for (int i = 0; i < M; ++i) {
        v[i] = i + 1;                
        printf ("%d ", v[i]);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

2

The error in your code is here:

for (i=0; i < M; ++i){
    v[i]++;  // Essa linha não faz a soma que você quer          
    printf ("%d ", v[i]);
}

The right thing is for you to use: v[i] = v[i] + 1;.

If you want the user to enter the vector values, you can do so:

#include <stdio.h>
#include<stdlib.h>

int main() {

    int N, M, i;
    int *v;

    printf ("Entre com N: ");
    scanf ("%d", &N);

    v = (int *)malloc(N * sizeof (int));

    printf ("Entre com os valores do vetor (M): ");
    for(i=0; i<N;i++){
        scanf ("%d \n", &M);
        v[i] = M;
    }

    for (i=0; i < N; ++i){
        v[i] = v[i] + 1;                
        printf ("Vetor[%d]=%d ",i, v[i]);
    }
}

See working on Ideone.

Browser other questions tagged

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