Classic Case Collection of C for Cycle

  • 2021-12-13 09:05:41
  • OfStack

Because for loop can change the traversal interval by controlling the initial value of loop variables and the end condition of loop, it is relatively simple to use for loop when sorting or traversing. The following are some summary cases obtained after my study.

1. Application of sorting

1) Exchange sorting: By comparing the extracted number with other numbers remaining after the number position one by one, the largest or smallest number is placed at the first place of a group of numbers, and then the second largest number is placed at the second place, and all the numbers are arranged in turn.


for(int i = 0; i < (num.length - 1); i ++)
{
  for(int j = i + 1; j < num.length; j ++)
  {
     if(num[i] > num[j])
      {
        int temp = num[j];
        num[i] = num[j];
        num[j] = temp;
      }
  }
}

The above code is to realize the minimum value in the array num from i-num. length, and there is the first position, where num is an array with a large amount of data.

2) Bubble sorting: By continuously comparing the size of two adjacent numbers, the large numbers are continuously exchanged to the back position, and the small numbers float to the top position of the array.


for (int i = nums.Length - 1; i > 0; i--)
{
  // In  0-i  Within the range, sink the largest number in the range to i
  for (int j = 0; j < i; j++)
  {
    if (nums[j] > nums[j+1])
    {
      // Exchange 
      int temp = nums[j];
      nums[j] = nums[j+1];
      nums[j+1] = temp;
    }
  }
}

3) Selective sorting: By means of exchange sorting, the minimum number in a certain range is mentioned to the first place in the range.


for (int i = 0; i < nums.Length - 1; i++)
{
  int index = i; // Let's assume that the subscript of the minimum number is i
  for (int j = i + 1; j < nums.Length; j++)
  {
    if (nums[j] < nums[index])
    {
      index = j;
    }
  }
  int temp = nums[i];
  nums[i] = nums[index];
  nums[index] = temp;
}

2. Judgment of prime numbers


bool isFinnd = false;
for (int i = 2; i < num; i++)
{
  if (num % i == 0)
  {
    isFinnd = true;
    break;// When found 1 Number  i  Be divisible  num  Explain the current  num  Yes 1 Composition number , Ends the current for Cycle 
  }
}
if (!isFinnd)// If  num  Yes 1 If there are prime numbers, an error prompt will be reported 
{
  // Judge the current num Is a prime number 
}

The num of the current code is a concrete integer variable.

In addition to the above cases, of course, there are many application scenarios, which need to be summarized by everyone when using them.


Related articles: