0
Can anyone tell me what’s wrong with this algorithm?
Make a program where the user enters with N values and stores the first 10 even numbers in a vector called even. 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’s happening is the following, at the time of printing the even numbers of the first vector up to the ninth, it’s okay, 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"...
Felipe still the final result gave problem, at the time of printing the results on the screen, he is printing the tenth number 11 instead of 10, if you can copy the code and make a test yourself...
– Adrian Roger
@Adrianroger Here you are running normal. I used the following interface to test: http://www.compileonline.com/compile_cpp11_online.php
– Felipe Fonseca
And if you notice, there is no need to modify my print loop as 'a' starts in '1' and ends in less than or equal to '10'.
– Adrian Roger
Here always prints wrong value for the tenth part of the vector, it’s like adding 1 to the number typed.
– Adrian Roger
@Adrianroger There is a need to change the final loop, otherwise you will ignore the first position of the vector ( that is 0, not 1 ) and access a non-existent ( the last position is 9, not 10 )
– Felipe Fonseca
Still it is printing 11 for the last value of the vector, at first the condition is that it is even to accept, it counts, but when printing it adds 1 to the last number, because that?
– Adrian Roger
I’m sorry, but I can’t reproduce the error. The original algorithm has problems, fixed in the algorithm I suggested. Are you sure you are compiling the code I passed? On the site informed it works
– Felipe Fonseca