C<6>function in C

目录

1,why do we use function?and what is it?

2,the difference between functions and methods.

3,define a function

1,return_type

2,arguments

E.G.

 3,*recursive function


1,why do we use function?and what is it?

to make our program more clear and easy to understand.

A function is a group of statements that together perform a task. and every program at least has a function named"main".

2,the difference between functions and methods.

The C language has no methodsit has only functionswhereas C++ and JAVA have no functionsthey only have methods.

3,define a function

the general form of function defining is below:

return_trpe function_name()
{
body of the function
}

1,return_type

a function may return values or not.

you can set the type of values for

1,int,char,flout...

2,void(if it returns null values)

the value returned from a function need to be same with the function type. 

2,arguments

1,A function has arguments.
2,A function does not have arguments,
void function(void) 
{
 /* some works */
}

3,arguments(实际参数) and parameter(形式参数)

 arguments and parameters should in a  same type

E.G.

#include <stdio.h>
 
/* function declaration */
int max(int num1, int num2);
 
int main () {

   /* local variable definition */
   int a = 100;
   int b = 200;
   int ret;
 
   /* calling a function to get max value */
   ret = max(a, b);
 
   printf( "Max value is : %d\n", ret );
 
   return 0;
}
 
/* function returning the max between two numbers */
int max(int num1, int num2) {

   /* local variable declaration */
   int result; 
 
   if (num1 > num2)
      result = num1;
   else
      result = num2;
 
   return result; 
}

 3,*recursive function

int f(int x)
{
	int y,z;
	z=f(y);	//在执行f函数的过程中又要调用f函数
	return (2*z);
}

有5个学生坐在一起,问第5个学生多少岁,他说比第4个学生大2岁。问第4个学生岁数,他说比第3个学生大2岁。问第3个学生,又说比第2个学生大2岁。问第2个学生,说比第1个学生大2岁。最后问第1个学生,他说是10岁。请问第5个学生多大。

 defined a recursive function

int age(int n) 						//定义递归函数
{	int c; 						//c用作存放函数的返回值的变量
	if(n==1) 						//如果n等于1
		c=10;					//年龄为10
	else 							//如果n不等于1
		c=age(n-1)+2;			//年龄是前一个学生的年龄加2(如第4个学生年龄是第3个学生年龄加2)
	return(c); 					//返回年龄
}

猜你喜欢

转载自blog.csdn.net/weixin_60787500/article/details/127566939