Error in vector (one-dimensional array)

0

Does anyone know what is wrong with this algorithm?

Make a program where the user enters N values and stores the first 10 even numbers in a vector named pair. When you reach the tenth even number, close the program and print the vector ....

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

int par[10],a,count;

main(){
    setlocale(LC_ALL, "Portuguese");
    while(count<10){
            printf("Digite um número: \n");
            scanf("%d",&a);
            if(a%2==0){
                par[a]=a;
                a++;
                count++;
            }//fim do if

    }//fim do while
    for(a=1;a<=10;a++){
        printf("valores de vetor: %d \n",par[a]);
    }//fim do for



    system("pause");
}//fim do main
What is happening is the following, when printing the even numbers of the first vector up to the ninth, everything is ok, but the printing of the tenth vector is adding "1" to the number, for example if I type the following sequences, 2 4 6 8 10 2 4 6 8 10 it will print:  2 4 6 8 10 2 4 6 8 "11" ...

    
asked by anonymous 07.06.2014 / 22:47

1 answer

1

C ++ arrays start at 0. I believe the error is in the final loop, where you are iterating the array outside the desired range.

Change your final loop to

for(a=0;a<10;a++){
    printf("valores de vetor: %d \n",par[a]);
}//fim do for

Also, use the variable count instead of a to populate the array. (and remove% unnecessary%)

while(count<10){
   printf("Digite um número: \n");
   scanf("%d",&a);
   if(a%2==0){
     par[count]=a;
      count++;
   }//fim do if
}

The following algorithm works as desired: link

    
08.06.2014 / 00:14