C language branch and loop classic examples (for beginners)

1. Calculate the factorial of n

First of all, we see this topic and analyze it from a mathematical point of view
. For example: 5! =1×2×3×4×5=120
will have 5 sequential numbers from 1 to 5, so we inevitably think of cycles
. Therefore

#include <stdio.h>
int main()
{
    
    
	//n的阶乘
	int i, n;
	scanf("%d", &n);
	int ret = 1;//ret是阶乘的最终得数,因为1×任何数=任何数
	for (i = 1; i <= n; i++)
	{
    
    
		ret = ret * i;
	}
	printf("%d的阶乘为:%d",n , ret);
	return 0;
}

2. Calculate 1!+2!+3!+...+10!

After taking down the appetizer just now, let’s look at this question again.
It’s the addition of factorials
. We already know
how to calculate the factorial of n. So how to calculate the addition of sequential
factorials? In the previous question, we can calculate whose factorial is whatever n is,
then we can In a nested loop, n is the loop variable

int main()
{
    
    
	int i, n;
	int sum = 0;
	int ret = 1;
	for (n = 1; n <= 5; n++)
	{
    
    
		for (i = 1; i <= n; i++)
		{
    
    
			ret = ret * i;
		}
		sum = sum + ret;//for循环嵌套中要注意表达式的位置噢,万万不可搞错循环体

	}
	printf("%d",sum);
	return 0;
}

In this way
we are done
————————————————————————————————————————————————————————————————————————— —————————————————————————————————————————————————————————————————————————
_ When you code,
you will find that the result is wrong
and debug it ( press F10, enter the monitoring during debugging, enter ret and sum to view )
insert image description here

, find the reason is that ret does not change to 1 every time it enters the second for, resulting in abnormally high data, then we need to add ret=1
in the first for loop ; after modification, we get

int main()
{
    
    
	int i, n;
	int sum = 0;
	int ret = 1;
	for (n = 1; n <= 5; n++)
	{
    
    
	    ret = 1for (i = 1; i <= n; i++)
		{
    
    
			ret = ret * i;
		}
		sum = sum + ret;//for循环嵌套中要注意表达式的位置噢,万万不可搞错循环体

	}
	printf("%d",sum);
	return 0;
}

to get the correct answer

3. Find the subscript of a specific number n in an ordered array. (binary search)

Note : it is an ordered array! ! ! ! !
First of all, we need to understand the basic principles. I believe that many people have not been in touch with the binary search. Let’s first briefly understand that according to the
2 in the binary search, it can be simply imagined. This is to search from the middle, and one search can exclude half of the data. The search is carried out The operation is relatively simple
Schematic diagram of binary search

int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	int left = 0;
	int right = (sizeof(arr) / sizeof(arr[0]))-1;//数组下标从0开始
	int input;//你要查找的数字
	int flag = 0;//一个标志,用来判断是否找到数字
	scanf("%d", &input);
	while (left <= right)
	{
    
    
		int mid = (left + right) / 2;
		if (arr[mid] < input)
		{
    
    
			left = mid+1;
		}
		else if (arr[mid] > input)
		{
    
    
			right = mid-1;
		}
		else
		{
    
    
			printf("congratulations,下标是%d\n", mid);
			break;
			int flag = 1;
		}
	}
	if (flag == 0)
	{
    
    
		printf("找不到");
	}
	return 0;
}

4. Guess the number game

The main event, the important event, the important event, the important thing is said three times
. With the above foundation, I believe we can already write a simple mini-game.
Since we are writing a mini-game, we must have a design idea

Design ideas

First, you need to create a menu for selection. After you choose to enter the game, you need a random number to compare with the number we entered.
So we divide it into 3 modules for design: menu, random number, comparison.

menu

The design of the menu does not require complicated operations. You know, the road is as simple as possible, so
I designed a function
insert image description here
. I believe that novices are stunned. How should I continue writing?

It is known that we are going to choose the number to perform the corresponding operation next

Then we can write a branch statement so that 1 and 0 correspond to the corresponding programs.
insert image description here
In this way, we only need to write the function game to basically complete the mini game.

But before that, we need to improve the connection between the menu and the switch. At the same time, we need to improve the switch.
It is known that the player cannot only input once, sometimes they make mistakes, and sometimes they want to continue playing.
A loop is needed to solve the problem. Do while can perfectly solve the problem

void menu()
{
    
    
    printf("********************\n");
	printf("******1.play  ******\n");
	printf("********************\n");
	printf("******0.exit  ******\n");
	printf("********************\n");
}
void game()
{
    
    
   
}
int main()
{
    
    
    int input;
    do
    {
    
    
      menu();
      scanf("%d",&input);
      switch (input)
		{
    
    
		case 1:
			game();
			break;//switch中的break用来跳出switch
		case 0:
			printf("您已退出游戏\n");
			break;
		default:
			printf("输入错误,请重新输入\n");
			break;
		}
	} while (input);//input为0时,直接跳出循环
	return 0}

So you can start writing the game function

design of game()

Since it is a number guessing game, it must be inseparable from random numbers

Random number generation (link)
After reading the content of the link, I believe everyone has understood it. It doesn’t matter if you don’t. You can remember how to use it first, and I will explain it later.
The code in the figure below is the core of random number generation

srand((unsigned)time(NULL));//strsnd理解为种子,rand从中调用种子
int ret=rand()%100+1;//这里我们选用随机数范围是1到100,模100是因为任何数模100结果为0到99,故+1

In the end, we are only one judgment away from guessing the number.

	int guess;
	while (1)
	{
    
    
		printf("输入猜的数字\n");
		scanf("%d", &guess);
		if (guess > ret)
		{
    
    
			printf("猜大了\n");
		}
		else if (guess < ret)
		{
    
    
			printf("猜小了\n");
		}
		else
		{
    
    
			printf("猜对了\n");
			break;
		}
     }
}

full code

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void menu()
{
    
    
	printf("********************\n");
	printf("******1.play  ******\n");
	printf("********************\n");
	printf("******0.exit  ******\n");
	printf("********************\n");
}
void game()
{
    
    
	//1.设置随机数;
	int ret=rand()%100+1;//利用随机数种子创建1到100的随机数,因为任何数模100结果为0到99.
	//2.进行比较;
	int guess;
	while (1)
	{
    
    
		printf("输入猜的数字\n");
		scanf("%d", &guess);
		if (guess > ret)
		{
    
    
			printf("猜大了\n");
		}
		else if (guess < ret)
		{
    
    
			printf("猜小了\n");
		}
		else
		{
    
    
			printf("猜对了\n");
			break;
		}
     }
}
int main()
{
    
    
	srand((unsigned)time(NULL));//随机数种子,strand在主函数中是语法规则哦,不用过于深究
	//猜数字
	int input;//不能设置在循环内部,否则为局部变量,while出现未定义标识符
	do
	{
    
    
		menu();//打印菜单

		scanf("%d", &input);
		switch (input)
		{
    
    
		case 1:
			game();
			break;
		case 0:
			printf("您已退出游戏\n");
			break;
		default:
			printf("输入错误,请重新输入\n");
			break;
		}
	} while (input);
	return 0;
}

If there is an error, please point out

Guess you like

Origin blog.csdn.net/2301_78636079/article/details/131815754