Section 37 Loop Nesting

1. Loop nesting

1.A loop body contains another complete loop structure, called the nesting of loops.

2.The nested loop can also be nested in the embedded loop, which is a multi-layer loop.

3. The three loop statements can be nested in each other.

2. Loop nested examples

Find 1 1 +2 2 +3 3 +4 4 +5 5 +6 6

Solution 1: for nesting

#include <stdio.h>
int main()
{
    
    
	int t = 1, sum = 0,j;
	for (int i = 1; i <= 6; i++)
	{
    
    
		for (j = 1,t=1; j <= i; j++)
		//写成int j=1,t=1等于新定义一个局部变量t,会出错
		{
    
    
			t *= i;
		}
		sum += t;
	}
	printf("sum=%d\n", sum);
}

Solution 2: while nesting

#include <stdio.h>
int main()
{
    
    
	int t = 1, sum = 0,i=1,j;
	while (i<=6)
	{
    
    
		t = 1;
		j = 1;
		while (j<=i)
		{
    
    
			t *= i;
			++j;
		}
		++i;
		sum += t;
	}
	
	printf("sum=%d\n", sum);
}

3. Focus on efficiency

Review the solution of 1!+2!+3!+…+20!

Solution one: loop nesting

#include <stdio.h>
int main()
{
    
    
	int t = 1, sum = 0, i = 1, j;
	while (i <= 20)
	{
    
    
		t = 1;
		j = 1;
		while (j <= i)
		{
    
    
			t *= j;
			++j;
		}
		++i;
		sum += t;
	}

	printf("sum=%d\n", sum);
}

Solution 2: Iterative solution

#include <stdio.h>
int main()
{
    
    
	int t = 1, sum = 0, i = 1;
	while (i <= 3)
	{
    
    
		t *= i;
		sum += t;
		++i;
	}
	printf("sum=%d\n", sum);
}

Summary:
1. Iterative solution efficiency is much higher;
2. There are increasing rules for the two before and after, try the iterative method;
3. Use the best strategy according to the situation;
① There is no iterative relationship problem, nested loop solution
1 1 +2 2 +3 3 +4 4 +5 5 +6 6
②The problem of iterative relationship can be found, and the iterative method can solve
1! + 2! + 3! +… + 20!

Guess you like

Origin blog.csdn.net/m0_51439429/article/details/115290390
37