Explanation of C language classic examples (output diamond, drink soda)

Table of contents

1. Output rhombus

2. The problem of drinking soda

Method 1: Step by step 

 Method 2: Apply the formula directly


 

1. Output rhombus

The output is a diamond shape similar to the image below: 

 

Through analysis: 1. First divide the output into upper and lower parts 

                  2. Output spaces before output

                  3. Find the law to output

It can be seen that the first half of the line can be made, and the lower half is the line-1 line.

The law of finding spaces: when the line is 7, there are 6 spaces in the first line, 5 in the second line...there is no space in the seventh line

The starting point is line-1 and the ending point is 0

Find * rule: When line is 7, there is 1 * in the first line, 3 in the second line... 13 in the seventh line

The rule is: line*2-1

int main()
{
	int line = 0;
	scanf("%d", &line);
	//开始输出上半部分
	for (int i = 1; i <= line; i++)
	{
		//先输出空格
		for (int j = 1; j <= line - i; j++)
		{
			printf(" ");
		}

		for (int j = 1; j <= 2 * i-1; j++)
		{
			printf("*");
		}
		printf("\n");
	}
	return 0;
}

Start outputting the second half:

int main()
{
	int line = 0;
	scanf("%d", &line);
	//开始输出上半部分
	for (int i = 1; i <= line; i++)
	{
		//先输出空格
		for (int j = 1; j <= line - i; j++)
		{
			printf(" ");
		}

		for (int j = 1; j <= 2 * i-1; j++)
		{
			printf("*");
		}
		printf("\n");
	}

	//开始输出下半部分
	for (int i = 1; i <= line - 1; i++)
	{
		for (int j = 1; j <= i; j++)
		{
			printf(" ");
		}

		for (int j = 1; j <= (line - i) * 2 - 1; j++)
		{
			printf("*");
		}
		printf("\n");
	}
	return 0;
}


Summary: We should pay attention to find the quantitative relationship between the number of spaces and * in each line and the number of lines 

2. The problem of drinking soda

Drink soda, 1 bottle of soda is 1 yuan, 2 empty bottles can be exchanged for a bottle of soda, given n yuan, how many bottles of soda can you drink 

Method 1: Step by step 

int main()
{
	int n = 0;
	int total = 0;
	scanf("%d", &n);//自己输入钱数
	total = n;
	int bottle = n;//一开始剩的瓶子数是钱数
	while (bottle >= 2)
	{
		total = total + bottle / 2;
		bottle = bottle / 2 + bottle % 2;
	}
	printf("%d", total);
	return 0;
}

It should be noted that bottle = bottle / 2 + bottle % 2; when n=10, after drinking 10 bottles, change to 5 bottles. 5 bottles can be exchanged for 2 more bottles, and one empty bottle left is +bottle % 2

 Method 2: Apply the formula directly

After you try a few more groups, you can easily see that the total number of bottles you drink in the end is twice your money minus one

2*n-1 can be printed directly; 


 This is the first topic, and I will continue to share it in the future. If you have any doubts, you can ask me at any time. 

Guess you like

Origin blog.csdn.net/qq_74415153/article/details/132193988