AwesomeToast
AwesomeToast

Reputation: 3

Garbage Result in my code

Hey guys so I was working on this code that finds the same numbers and display them and so far the result is just random numbers I need help.

int main(void){
int arr[10] = {1, 2, 3, 4, 5, 4, 8 ,8, 9, 10};
int i;
int j;
int same[10];
int ctr = 0;

for(i = 0; i < 10; i++){
    for(j = 10; j > 0;j--){
        if(arr[i] == arr[j]){
            same[ctr++] = arr[i];//store the similar numbers
        }
    }
}

for(i = 0; i < 10; i++){
    printf("%d", same[i]);
}
getch();
return 0;}

Upvotes: 0

Views: 64

Answers (3)

Jaskirat Singh
Jaskirat Singh

Reputation: 82

I ran your code on codechef compiler, it was giving a run time error. Because in your ctr++ step , value of ctr exceeded the size of the array same[].

Moreover, in your code you are comparing one element with itself so every number will be printed in the list(since i==j may be a possible case)

It will be better if you include a condition i!=j with it or iterate j from i+1 to 9 so that no self comparisons are done. The following is a working snippet of the same code(your for loop) :-

for(i = 0; i < 10; i++){
    for(j = 10; j > 0;j--){
        if(arr[i] == arr[j] && i!=j){
            same[ctr] = arr[i];//store the similar numbers
            ctr++;
            cout<<ctr<<" ";
        }
    }
} 

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134316

You're contradicting yourself. For the same array, you're using two different indexing scheme!!

  • In outer loop (ascending index), you're indexing from 0 to 9
  • In inner loop (decending index), you're indexing 10 from 1.

The inner loop indexing is off-by-one, thereby accessing out of bound memory, which is invalid. This causes undefined behavior.

You need to make it

for(j = 9; j >= 0;j--)

After that, you're attempting to print the values of all elements in the same array, whereas all (or none) the element values may not be assigned a value, actually. You left the automatic variable uninitialized, thereby containing indeterminate values. Since the variable has never its address taken, attempting to use the value will again cause UB.

That said, once a match is found, you can use continue to jump to the outer loop.

Upvotes: 1

Michael Albers
Michael Albers

Reputation: 3779

Start your second loop (the j loop) at 9 and go to 0.

Upvotes: 0

Related Questions