[英]This is a question from GFG. I am trying to analyse and understand this code
This is a code I have taken from GeeksForGeeks.这是我从 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?在 function
deleteEle
的行中,它说if(i==n) return n
,如果它在它上面的for
循环中运行< n
次, i
怎么会变成n
呢?
#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]<<" ";
}
}
how could I become
n
if it is running for< n
times in the for loop just above it?如果它在它上面的 for 循环中运行
< n
次,我怎么能变成n
呢?
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
.因为可能会发生前面 for 循环中的 if 条件
arr[i] == x
永远不会满足,这反过来意味着break
永远不会执行,在这种情况下,最后一次迭代将递增i
以便 i 变得等于n
。
After the last iteration of this loop ( if arr[i],= x for all i in range [0, n]
):在这个循环的最后一次迭代之后(
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.如果不执行
break
, i
将等于n
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.