A few classic examples of for loops
Because the for loop can change the interval of the loop by controlling the initial value of the loop variable and the end condition of the loop, it is relatively easy to use the for loop when sorting or traversal. The following are some summary cases obtained by myself after learning.
1. Application of sorting
1) Exchange sort: by comparing the number taken out with the remaining numbers behind the position of this number one by one, place the largest or smallest number in the first place of a group of numbers, and then place the second largest number in the second place, and then complete all numbers in sequence.
1 for(int i = 0; i < (num.length - 1); i ++)
2 {
3 for(int j = i + 1; j < num.length; j ++)
4 {
5 if(num[i] > num[j])
6 {
7 int temp = num[j];
8 num[i] = num[j];
9 num[j] = temp;
10 }
11 }
12 }
Copy the code
Num is an array containing a large amount of data, and is stored in the first position.
2) Bubble sort: by constantly comparing the size of two adjacent numbers, the large number is constantly swapped and the small number floats towards the top of the array.
1 for (int i = nums.Length - 1; i > 0; i--)
2 {
3 // In the range 0-i, sink the largest number in the range to I
4 for (int j = 0; j < i; j++)
5 {
6 if (nums[j] > nums[j+1])
7 {
8 / / exchange
9 int temp = nums[j];
10 nums[j] = nums[j+1];
11 nums[j+1] = temp;
12 }
13 }
14 }
Copy the code
3) Selection sort: through the way of exchange sort, the minimum number in a range is raised to the first place in the range.
1 for (int i = 0; i < nums.Length - 1; i++)
2 {
3 int index = i; // Assume that the subscript of the smallest number is I
4 for (int j = i + 1; j < nums.Length; j++)
5 {
6 if (nums[j] < nums[index])
7 {
8 index = j;
9 }
10 }
11 int temp = nums[i];
12 nums[i] = nums[index];
13 nums[index] = temp;
14 }
Copy the code
2. Judgment of prime numbers
1 bool isFinnd = false;
2 for (int i = 2; i < num; i++)
3 {
4 if (num % i == 0)
5 {
6 isFinnd = true;
7 break;// If num is divisible by I, num is a composite number, ending the for loop
8 }
9 }
10 if(! isFinnd)If num is a prime number, an error message is displayed
11 {
12 Num is a prime number
13 }
Copy the code
The num of the current code is a concrete integer variable.
In addition to the above cases, of course, there are many application scenarios, we need to continue to summarize their own in the use of time.
Reproduced in: www.cnblogs.com/Mr-Beyond/p…
For circular exercises