Vector error(one-dimensional matrix)

Asked

Viewed 140 times

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"...

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 fill the array. ( and remove the a++ unnecessary )

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

Follows algorithm working as desired: http://ideone.com/7LOOBg

  • 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...

  • 1

    @Adrianroger Here you are running normal. I used the following interface to test: http://www.compileonline.com/compile_cpp11_online.php

  • 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'.

  • Here always prints wrong value for the tenth part of the vector, it’s like adding 1 to the number typed.

  • @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 )

  • 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?

  • 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

Show 2 more comments

Browser other questions tagged

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