Vector that generates elements

1

I would like to generate a vector where its next position element is added by 1. For example: be vetor[3] , I'd like 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]);
    }
}      
    
asked by anonymous 07.11.2016 / 18:42

2 answers

2

The main problem with 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]);
    }
}

See running on ideone and on CodingGround .

    
07.11.2016 / 18:55
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 correct one is you use: v[i] = v[i] + 1; .

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

#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 at Ideone .

    
07.11.2016 / 19:04