Home > Article > Backend Development > Example analysis of for loop in C#
This article mainly introduces the classic cases about forloop, which has a good reference value. Let’s take a look with the editor below
Since the for loop can change the traversed interval by controlling the initial value of the loopvariable and the loop end condition, so when sorting or traversing, It is relatively simple to use a for loop. The following are some summary cases I got after studying.
1. Application of sorting
#1) Exchange sorting: compare the number taken out one by one with the remaining numbers after the number position , put the largest or smallest number first in a group of numbers, then put the second largest number second, and finish all the numbers in sequence.
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 find out the minimum value in arraynum from i - num.length and exist in the first position, where num is An array that stores a large amount of data.
2) Bubble sort: By continuously comparing the size of two adjacent numbers, the larger number is continuously exchanged to the later position, and the smaller number is continuously exchanged. The number floats towards the top position of the array.
for (int i = nums.Length - 1; i > 0; i--) { //在 0-i 范围内,将该范围内最大的数字沉到i for (int j = 0; j < i; j++) { if (nums[j] > nums[j+1]) { //交换 int temp = nums[j]; nums[j] = nums[j+1]; nums[j+1] = temp; } } }
3)Selection sort: By exchanging sorting, the smallest number in a range is mentioned in the range The first one.
for (int i = 0; i < nums.Length - 1; i++) { int index = i; //先假设最小数的下标是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. Determination of prime numbers
bool isFinnd = false; for (int i = 2; i < num; i++) { if (num % i == 0) { isFinnd = true; break;//当找到一个数 i 能够整除 num 时,说明当前的 num 是一个合数,结束当前的for循环 } } if (!isFinnd)//如果 num 是一个质数,则报错提示 { //判断出当前的num是质数 }The num of the current code is a specific 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.
The above is the detailed content of Example analysis of for loop in C#. For more information, please follow other related articles on the PHP Chinese website!