This is a code I have taken from GeeksForGeeks. I am trying to understand the code.
In the line in the function deleteEle which says if(i==n) return n, how could i become n if it is running for < n times in the for loop just above it?
#include <iostream >
#include <cmath>
using namespace std;
int deleteEle(int arr[], int n, int x)
{
int i = 0;
for(i = 0; i < n; i )
{
if(arr[i] == x)
break;
}
cout << i << endl;
if(i == n)
cout<<i;
return n;
for(int j = i; j < n - 1; j )
{
arr[j] = arr[j 1];
}
return n-1;
}
int main() {
int arr[] = {3, 8, 12, 5, 6}, x = 13, n = 5;
cout<<"Before Deletion"<<endl;
for(int i=0; i < n; i )
{
cout<<arr[I]<<" ";
}
cout<<endl;
n = deleteEle(arr, n, x);
cout<<"After Deletion"<<endl;
for(int i=0; i < n; i )
{
cout<<arr[I]<<" ";
}
}
CodePudding user response:
how could I become
nif it is running for< ntimes in the for loop just above it?
Because it may happen that the if condition arr[i] == x inside the preceding for loop is never satisfied which in turn means that the break is never executed in which case the last iteration will increment i so that i becomes equal to n.
CodePudding user response:
After the last iteration of this loop (if arr[i] != x for all i in range [0, n]):
for(i = 0; i < n; i )
{
if(arr[i] == x)
break;
}
i will equal n if break is not executed.
