简体   繁体   中英

last index of array give wrong output in c

I created a program that search the specific number in array and give it position. here's the code.

#include<stdio.h>
#include<conio.h>
void main()
{
    int arr[10], srch, i;
    clrscr();

    printf("Enter elements of array.\n");
    for(i=0;i<10;i++){
        scanf("%d", &arr[i]);
    }

    printf("Enter element to search\n");
    scanf("%d", &srch);

    for(i=0;i<10;i++){
        if(arr[i]==srch){
            printf("%d is at position %d", srch, i+1);
            break;
        }
    }
    //Below statement run when no such number found in array.
    if(srch!=arr[i])
         printf("%d", arr[i]);
  
    getch();
}

Well, I can't understand why am i getting this output. whenever i run this program and entered a value that is in the current array it found its position and give correct answer.

But I have doubt that when i print this array with last value of index which was 10 it give the value of 'srch variable' i don't know why it is giving this as array 10 index.

For example when i enter 11 as value to search which will not be in array print("%d", arr[i]) // It print value of srch

After coming out the second loop in your code the value of i will be equal to 10. And when the if(srch!=arr[i]) gets read by the compiler, it searches for the arr[10] which has not been allocated by you. So theres a garbage value there at that position. That is being printed by printf("%d", arr[i]);

It's garbage value. You are reaching an index which is not created. Out of bonds. So you get a garbage value. It can be anything.

After the loop i is one past the last element, thus you can't access the array at this index.

You need to handle the fact that the value has been found or not, possibly this way:

int found = 0; // value not found
for (i=0; i<10; i++) {
    if (arr[i]==srch) {
        printf("%d is at position %d", srch, i+1);
        found = 1; // value found
        break;
    }
}
if (!found) {
    //Below statements run when no such number found in array.
}

When No element found then from second for loop value of i will be 10. which is out of the bound of the array. since array will have 0,1,2.....9 index and you are trying to access 10th index, It will have garbage value.

to prevent this issue, you can replace i with i-1

 if(srch!=arr[i-1])
     printf("%d", arr[i-1]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM