Home > Mobile >  What happens to while loop when it starts finding an element from array and the element is not found
What happens to while loop when it starts finding an element from array and the element is not found

Time:08-08

int arr[] = {1,2,3,4,5};
int i = 0;
while(arr[i]<=6){
  i  ;
}

What happens to the while loop if the element is not found in the array.

As in the above example, What will happen to i as 6 is not found in the array should it incresed till infinity or it will stop at the end of array length.

CodePudding user response:

When i==5 and code attempts arr[i] the result is undefined behavior (UB) as code attempts to read beyond that array arr[].

... should it incresed till infinity or it will stop at the end of array length.

No - there is no should. It is undefined behavior (UB).

CodePudding user response:

I got the output but I have some confusion in the while loop where i is incremented.

#include <stdio.h>
void arrayTrasversal(int *arr, int n)
{
    for (int i = 0; i < n; i  )
    {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
void swap(int *a,int *b){
    int temp = *a;
    *a = *b;
    *b = temp;
}
int partition(int *arr, int low, int high)
{
    int pivot = arr[low];
    int i = low   1;
    int j = high;
    do{
        while (arr[i] <= pivot)
        {
            i  ;
        }
        while (arr[j] > pivot)
        {
            j--;
        }
        if(i<j){
            swap(&arr[i],&arr[j]);
        }
    }while (i < j);
    swap(&arr[low],&arr[j]);
    return j;

}
void quickSort(int *arr, int low, int high)
{
    int partitionIndex;
    if (low < high)
    {
        partitionIndex = partition(arr, low, high);
        quickSort(arr, low, partitionIndex - 1);
        quickSort(arr, partitionIndex   1, high);
    }
}
int main()
{
    int arr[] = {2, 4, 3, 9, 1, 4, 8, 7, 5, 6};
    int n = sizeof(arr) / sizeof(int);
    arrayTrasversal(arr, n); // Before sorting
    quickSort(arr, 0, n - 1);
    arrayTrasversal(arr, n);
    return 0;
}

What happens to i in this case if it increases till last indent and not found element greater than pivot

while (arr[i] <= pivot)
        {
            i  ;
        }

Should I use another condition like this

while (arr[i] <= pivot && i<=high)
        {
            i  ;
        }
  • Related