当前位置:网站首页>C language function review (pass value and address [binary search], recursion [factorial, Hanoi Tower, etc.))
C language function review (pass value and address [binary search], recursion [factorial, Hanoi Tower, etc.))
2022-07-25 15:13:00 【GracefulBlack】
function
Function call by value
The formal and actual parameters of a function occupy different code blocks , Modifying the formal parameter does not change the value of the argument
Address calling of function
Addressing call refers to a call method that passes the memory address created outside the function to the function parameter
This parameter transfer method can operate variables outside the function inside the function
practice
Two points search
#include<stdio.h>
int binary_2(int arr[] , int k,int len);
int main() {
int arr[ ] = {
1,2,3,4,5,6,7,8,9,10 };
int len = sizeof(arr) / sizeof(arr[0]);
int element ;
printf(" Please enter the element you want to find ");
scanf("%d", &element);
int ret;
ret = binary_2(arr ,element,len);
if (ret == -1) {
printf(" The specified element was not found \n");
}
else {
printf(" eureka , The subscript of the element is %d\n",ret);
}
return 0;
}
int binary_2(int arr[] , int k,int len) {
//int len = sizeof(arr) / sizeof(arr[0]);
int left = 0;
int right = len - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] < k) {
left = mid + 1;
}
else if (arr[mid] > k) {
right = mid - 1;
}
else {
return mid;
}
}
return -1;
}
Be careful :
1) One is function len To be in main Function to calculate internally , Because if you calculate inside a function ,size(arr) The value of is actually 4 , Why? , Because what is passed in is a pointer variable , Points to the address of the first element , The calculated size is int* size
#include<stdio.h>
int main() {
The subscript of a prime is %d\n",ret);
printf("%d\n", sizeof(arr));//40
printf("%d\n", sizeof(arr[0]));//4
return 0;
}
2) The second thing to note is , The parameter passed in int arr[] Why pointer variables , int arr[] Equivalent to int * arr, The two are the same
Modular use of functions
From a source file A To another source file B in , Want to add the source file A Use source files in B The function in ,
1) First, in the source file A Add #include “ The function name you want to use ”
- Create a new and... In the header file B Header file with the same name (.h) ending
For example :
Source file A, The name is str.c :
#include<stdio.h>
#include"add.h"
int main2() {
int x = 1, y = 4;
int sum = Add(x, y);
printf("%d", sum);
return 0;
}
Source file B, The name is add.c :
#include<stdio.h>
int Add(int x, int y) {
return x + y;
}
Header files to be actively added C, The name is add.h( This is generally the same as the header file ) :
#ifndef __ADD_H_// if not define __XX_X_
#define __ADD_H_
int Add(int x, int y);// Here is the declaration of the function
#endif
This is the format , To understand the : The first line finds that there is no definition , If defined , You don't have to define , Avoid repeated definitions
Recursion of a function
What is recursion
A programming skill of function call itself (recursion)
The main thinking : Turn big into small , Layer by layer dialing
I think it can be imagined as an inverted pyramid , The bottom floor is open , The upper layers have permissions and cannot be opened , The process of recursion is the process of unlocking upward
practice 1:
Write functions to print out numbers one by one “1234” Medium 1 , 2, 3,4
#include<stdio.h>
void print(int i) {
if (i > 9)
{
print(i/10);
}
printf("%d\n", i%10);
}
int main() {
unsigned int i = 1234;
// Customize by calling print Function to complete 1,2,3,4 Output
/* For the first time 1234 Divide into “123” and 4 Continue to divide “12" and ”3“”4“ Go on ”1“2”3“4” This is the programming idea of "from big to small" */
print(i);
return 0;
}
Their thinking :
From big to small , Set the permissions , Layer by layer recursion !
practice 2:
Written by myself my_strlen Play a strlen The role of , Number of output strings , In two ways
Tips : One is to create temporary variables , One does not create
#include<stdio.h>
int my_strlen1(char * );
int my_strlen2(char *);
int main() {
char arr[] = "superzkx";
int len1 = my_strlen1(arr);// This is a function obtained through temporary variables
int len2 = my_strlen2(arr);// This is the second way
printf("%d\n", len1);
printf("%d\n", len2);
return 0;
}
int my_strlen1(char* arr) {
// The idea is to save a temporary variable
int coust = 0;
while (*arr != '\0') {
*arr++;
coust++;
}
return coust;
}
int my_strlen2(char* arr) {
// This is the pointer pointing back one by one , The first step turns into 1+"uperzkx"...
if (*arr != '\0') {
return 1 + my_strlen2(arr + 1);
}
return 0;
}
thus it can be seen , Recursion converts the original while Instead of if, Among them return In fact, it plays a role while The role of
practice 3:
Function calculation n! Value
#include<stdio.h>
int main() {
int n;
int sum1, sum2;
printf(" Please enter the number of factorials to be calculated ");
scanf("%d", &n);
sum1 = factorial_1(n);
sum2 = factorial_2(n);
printf("sum1==%d,sum2==%d", sum1, sum2);
return 0;
}
int factorial_1(int n) {
// Circular approach
int i;
int sum = 1;
for (i = 1; i <= n; i++) {
sum = sum * i;
}
return sum;
}
int factorial_2(int n) {
// Recursive method
if (n == 1)
return 1;
else if (n > 1) {
return n * factorial_2(n - 1);
}
}
It can be seen that loop and recursive In fact, they can express each other
practice 4:
Calculating Fibonacci series ( Not stack overflow )
#include<stdio.h>
int Fibo1(int n);
int Fibo2(int n);
int main() {
int n;
int sum1, sum2;
printf(" Please enter to calculate Fibo Number of numbers ");
scanf("%d", &n);
sum1 = Fibo1(n);
sum2 = Fibo2(n);
printf("sum1== %d,sum2== %d", sum1, sum2);
return 0;
}
// Ordinary recursive method
int Fibo1(int n) {
if (n == 1)
return 1;
else if (n == 2)
return 1;
else
return Fibo1(n - 1) + Fibo2(n - 2);
}
int Fibo2(int n) {
int a = 1;
int b = 1;
int c = 0;
if (n == 1) {
return a;
}
if (n == 2) {
return b;
}
while (n > 2) {
c = a + b;
a = b;
b = c;
n--;
}
return c;
//1 1 2 3 5 8 13 21 34
//a b c
// a b c
}
Classical recursion problem :
Hanoi
#include<stdio.h>
void Hanoi(int n, char A, char B, char C);
int main() {
int n =0;
char A = 'A';
char B = 'B';
char C = 'C';
printf(" Please enter the number of floors of Hanoi tower ( The goal is to A The column moves to C column )\n");
scanf("%d", &n);
Hanoi(n,A,B,C);
return 0;
}
void Hanoi(int n,char A, char B ,char C ) {
if (n == 1) {
printf(" take %c-->%c\n",A,C);
}
else {
Hanoi(n - 1, A, C, B);// Before the n-1 individual from A adopt C All moved to B
printf("%c-->%c\n",A,C);// then A The last big one arrives C
Hanoi(n - 1, B, A, C);// Last B adopt A To C
}
}
The main idea :n>=2 when (n>=3) More obvious when , The former n-1 Doughnuts as a whole , In fact, the repetition is n=2 Time operation
Namely !
Before the n-1 individual from A adopt C All moved to B
then A The last big one arrives C
Last B adopt A To C
A simple KO!
边栏推荐
- 万能通用智能JS表单验证
- Tasks, micro tasks, queues and scheduling (animation shows each step of the call)
- 延迟加载源码剖析:
- Handle Oracle deadlock
- RedisCluster搭建和扩容
- Share a department design method that avoids recursion
- [Nacos] what does nacosclient do during service registration
- MySql的安装配置超详细教程与简单的建库建表方法
- Spark002---spark任务提交,传入json作为参数
- Meanshift clustering-01 principle analysis
猜你喜欢

Award winning interaction | 7.19 database upgrade plan practical Summit: industry leaders gather, why do they come?

System.AccessViolationException: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏

Docker上运行redis以配置文件方式启动,连接客户端报错Error: Server closed the connection

在win10系统下使用命令查看WiFi连接密码

从 join on 和 where 执行顺序认识T-sql查询执行顺序

Spark提交参数--files的使用

Leetcode combination sum + pruning

Raft of distributed consistency protocol

Spark AQE

spark分区算子partitionBy、coalesce、repartition
随机推荐
Universal smart JS form verification
深入:微任务与宏任务
SublimeText-win10光标跟随问题
node学习
VS2010 add WAP mobile form template
pl/sql 创建并执行oralce存储过程,并返回结果集
dpdk 收发包问题案例:使用不匹配的收发包函数触发的不收包问题定位
Fast-lio: fast and robust laser inertial odometer based on tightly coupled IEKF
Scala111-map、flatten、flatMap
打开虚拟机时出现VMware Workstation 未能启动 VMware Authorization Service
Solve the error caused by too large file when uploading file by asp.net
Cmake specify opencv version
Promise object and macro task, micro task
Unable to start web server when Nacos starts
Es5 thinking of writing inheritance
ESXI6.7.0 升级到7.0U3f(2022年7月12 更新)
瀑布流布局
浏览器工作流程(简化)
【JS高级】js之正则相关函数以及正则对象_02
给VS2010自动设置模板,加头注释