Programming C: Posts 8 – Functions in C
Content
- 1. At the beginning of the function
- 2. The operating principle of the function
- 3. The structure of the jaw
- 4. Examples of functions
- Example 1: The function does not return value
- Example 2: Valuable function returns
- Example 3: Function test
- Example 4: These functions call each other
- Example 5: Function declaration before the function definition
- Example 6: Recursive function
- Example 7: Use the navigation #define to define a simple function
1. At the beginning of the function
Enter and run 2 examples, observe the results and comments.
Example 1:
// e.g 1 about function in C - code by nguyenvanquan7826 #include <stdio.h> void loiKhuyen() { printf("Neu hoc nghiem tuc va cham chi thi ban se thay:\n"); printf("Khong co viec gi kho\n"); printf("Chi so long khong ben\n"); printf("Dao nui va lap bien\n"); printf("Quyet chi at lam nen\n"); printf("\n"); } int main() { printf("Hoc bai nay kho qua!\n"); loiKhuyen(); printf("Hoc C kho qua!\n"); loiKhuyen(); return 0; }
Result:
Lessons learned through this warehouse!
Neu serious study and hard work, you will see:
Nothing warehouse
Chi ben so long khong
Lap great dao va bien
Determined at nen lamHoc C storage over!
Neu serious study and hard work, you will see:
Nothing warehouse
Chi ben so long khong
Lap great dao va bien
Determined at nen lam
Example 2:
// e.g 2 about function in C - code by nguyenvanquan7826 #include <stdio.h> void vechu(char chu, int soluong) { int i; for (i = 0; i < soluong; i++) { printf("%c", chu); } printf("\n"); } int main() { vechu('h', 20); vechu('a', 30); vechu('h', 12); vechu('a', 5); vechu('p', 10); return 0; }
Result:
gggggggggggggggggg
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
hhhhhhhhhhhh
AAAAA
pppppppppp
If the program has a number of command, or jobs that have the same or similar form to repeated several times in different positions, to avoid wasting time and effort to copy the command sequence that we should organize and build it into a piece of command, where the program needs to do the job that they just call that command only segment. The paragraph that called the function command.
Ham is a piece of implementing a block command job is repeated several times while running the program, or use a separate block specific work to support complex programs.
In the example 1: Have 2 program, 1 main program: main and 1 additional programs: loiKhuyen no parameters and returns no value to the data type of the function is declared as void. Both the main and loiKhuyen are called function. The main function is the function executed and run our entire program. Ham loiKhuyen done some work (output 5 the words above). In the main function we have 2 place call loiKhuyen();
In the example 2: Similar examples 1, it includes 2 jaw, 1 The main function is main and 1 subroutine, but subroutine is Vecht(chu char, int soluong); have 2 parameter form is cycle of type char and soluong of type int. Ham vechu no return value data type of the function should be declared as void. In the main function we have 3 vechu function calls with parameters actually turn as the program on.
2. The operating principle of the function
- When the machine meets function calls anywhere in the function that is performed starting, will immediately leave the area to go to the function is called.
- If the function parameters, the machine will perform real communication parameters for the corresponding formal parameter in the function.
- Machine began performing in turn the statements in the function body until reuturn order or check } of the jaw, stop escape function returns the program to call it and make statements of this program.
- If the function returns a value, the value of the expression in the function's return value of the function.
Noted: The function declaration void vechu(chu char, int soluong) then cycle and quantity parameters form, even when calling Vecht(‘h’, 20); then ‘h’ and 20 parameters really.
3. The structure of the jaw
We have structured the following function declaration:
KieuTraVe TenHam(Cac tham so) { ThanHam; }
The function name is set in the variable naming rules.
4. Examples of functions
Example 1: The function does not return value
Above we have 2 for example the opening are not a function returns a value and declared return type is void.
Example 2: Valuable function returns
Construction of functions n! and few expressions factorial. know n! = 1.2.3…n
// e.g about function in C - code by nguyenvanquan7826 #include <stdio.h> long giaiThua(int n) { long gt = 1; int i; for (i = 2; i <= n; i++) { gt *= i; // <=> gt = gt * i } return gt; } int main() { printf("5! = %ld \n", giaiThua(5)); printf("6! + 1 = %ld \n", giaiThua(6) + 1); return 0; }
Result:
5! = 120
6! + 1 = 721
Do n! can be a fairly large integer function returns a value of type long (greater than type int – Review the data types in C). Order return gt ie variable returns gt, gt must have the same type of data with the data type of the function (and the dragon).
In this example giaiThua function returns the factorial of the number n is passed on so it can be considered as 1 variables and used in the expression, always used to print the results. When meeting functions anywhere, it will transmit 1 parameters corresponding to the function and returns the return value of the last command.
Example 3: Function test
Building inspection function there are some nice some not? Beautiful number is the number divisible 2 and divisible 5.
To do this, we need to determine is this function check a number is something, therefore, we need to return the correct value (1) or wrong (0). So the function returns integer.
// e.g about function in C - code by nguyenvanquan7826 #include <stdio.h> int kiemTraChiaHet(int n) { if(n % 2 == 0 && n % 5 == 0) { return 1; } return 0; } int main() { int x; printf("Nhap x = "); scanf("%d", &x); if( kiemTraChiaHet(x) == 0) { printf("day khong phai so dep @@\n"); } else { printf("day la so dep !!!\n"); } return 0; }
In function kiemTraChiaHet, when n is divisible 2 and 5, it will execute the command return 1, While executing this function ie end, do not do anything in this function again whether or not the command left behind. If the number n is not divisible 2 and 5 it will execute the command return 0.
Example 4: These functions call each other
// e.g about function in C - code by nguyenvanquan7826 #include <stdio.h> int max2(int a, int b) { return a > b ? a : b; } int max3(int a, int b, int c) { return max2( max2(a, b), c); } int main() { int a = 7, b = 13, c = 4; printf("So lon nhat la %d \n", max3(a, b, c)); return 0; }
Result:
Highest 13
In this example we build 2 function to find the largest number of 2 number and 3 number. In MAX2 function we use Conditional operators to find the largest number of 2 number. In MAX3 function was to call MAX2 2 time to find the largest number in a, b and took some finding was compared to c find the largest number.
Attention: The function declaration after the function is called before it was declared, but the function is not declared before calling the function declarations. Ie in the example above, if we build MAX2 function in later levels, the machine will error MAX3. To remedy this we usually declare the function in the program then we define functions anywhere in the program are an example to us:
Example 5: Function declaration before the function definition
// e.g about function in C - code by nguyenvanquan7826 #include <stdio.h> // khai bao cac ham max2, max3, max4 int max2(int a, int b); int max3(int a, int b, int c); int max4(int a, int b, int c, int d); int max3(int a, int b, int c) { return max2( max2(a, b), c); } int max2(int a, int b) { return a > b ? a : b; } int main() { int a = 7, b = 13, c = 4, d = 16; printf("So lon nhat trong a, b, c la %d\n", max3(a, b, c)); printf("So lon nhat trong a, b, c, d la %d\n", max4(a, b, c, d)); return 0; } int max4(int a, int b, int c, int d) { return max2( max2(a, b), max2(c, d) ); }
Result:
The largest number in a, b, the c 13
The largest number in a, b, c, of the 16
When working we should declare the function like this before, and define the following. Thus we will avoid some errors when we want to use the functions in each.
I already know the function can call each other and function can also call itself, that we use recursive function.
Example 6: Recursive function
I knew the formula n! = 1.2.3…n. However one can also write n! = (A-1)!.n. In this notation to calculate n! we need calculation (A-1)!. So it could be called the expression and function recursively, too, callback function itself is called a recursive function.
// e.g about function in C - code by nguyenvanquan7826 #include <stdio.h> int giaiThua(int n) { if(n == 0) return 1; // dieu kien dung return giaiThua(n-1) * n; // loi goi chinh no } int main() { int n = 5; printf("%d! = %d",n, giaiThua(n)); return 0; }
Noted in recursive functions always 2 factor is the condition stops and calls itself.
Example 7: Use the navigation #define to define a simple function
#include <stdio.h> #define tong(x, y) x + y int main() { int a = 5, b = 8; printf("%d + %d = %d",a, b, tong(a, b)); return 0; }
At this point we have the basic understanding of the function, but there are many more things to say about the function, especially concerning the function arrays and pointers. We will continue to find out them in the next post with arrays and pointers.
Exercise
- Write a function to sum S = 1 + 2 +….+n.
- Write the check function primes, perfect number.
- Enter a sequence of n numbers and announcements should primes, perfect number or not.
He asked me as I have written above”In the program 1: Have 2 program, 1 main program: main and 1 additional programs: loiKhuyen no parameters and no return value data type of the function should be declared as void.
But in program 2, vechu functions have parameters declared as void star still ạ
I thank
parameters and return value is 2 the entirely different and unrelated to one another you ah
did you see many of them declaring the function as ri is why he :
node * searchnode(tree T , float k)
The function returns the pointer type of note
function declaration also gave him pointers on dc ak
Putting your okay.
I asked the site ad for recursive function, return stop condition 1 sir la star? I thought return 1 it returns a value 1 word?
It is true that it returns a value 1. But the order is stop condition of the recursion, ie you want to stop, they must stop in that TH.
ad can explain is not it better. return 1 so why not get the value function giaithua a sir? e thank
It only returns 1 when n = 0 only you. If n is still> 0 it still called itself but with reduced n.
Vd n = 4 we have the process done.
B1: do n > 0 should return giaithua(3)*4
B2. it will return the same giaithua(2)*3*4
B3, return giaithua(1)*2*3*4
B4. Return giaithua(0)*1*2*3*4
B5. At this stage it counted giaithua(0) and see it return n = 0 1 ie giaithua(0) = 1. and the results have
1*1*2*3*4
he asked me that wants to define bh min max function 1 n where n chain of typing it as tn ????
Min max definition of the string is why you.
return giaiThua(A-1) * n; // loi calls itself
Waiter, This song why it became 4!*5 is that sir.
With n = 5 then n – 1 = 4, giaiThua(A-1) was 4!.
cho em hoi return returns as return gt , Thus gt – and giaithua unrelated to each other co sir ,
stars at the main function call giaithua out , while the return value is the return gt ?
expect a period like for you
giaithua the function name, GT is also variable contains the value to be calculated should we pay for severance.
E ask: Want to use the functions we need to do?
Just call it out loud.
Let me ask: I saw the writing function, such as people passed: int a, int &the, int a, How different it, and how using ạ
int a function argument is an integer normal, int &is a function argument is the address of an integer variable. int a function with the value of a non-save when out of function, but int &a, the value of a can be saved after off function. You can refer to this post for more: https://cachhoc.net/2018/01/20/ham-hoan-vi-trong-c/#4_Ham_hoan_vi_trong_C
int main() {
int n = 5;
printf(“%d! = %d”,n, giaiThua(n));
return 0;
}
stars to return 0 more admin
At all 1 his article also says Gone. But more about why we use return 0, or return a certain value at the end of the main function()?
The answer is simple: most cases, it is not necessary!
But if you are interested in this question is concerned with the deeper meaning of it a little nhé:
To return a value for the main function, ie, your program will tell the Operating System on the status of your program, such programs when running within a certain error.
By default OS, when the value 0 returned from main(), program will never encounter any bugs. Contrary, when a non-zero value is returned to the main function, it will signal that an error has occurred.
Example, program can not open a file that has been specified by a command line. The true value is returned from the program and what they mean for the program indicated that: they are defined by the programmer of that program.
Source: http://diendan.congdongcviet.com/threads/t4057::su-dung-return-0-o-cuoi-ham-main-co-y-tenet-gi.cpp
he can explain #defind not you help me that paragraph you have not misread sir thank you
This is the definition 1 constant or a function that f fast.
I do not get seats recursive function , stars with formula (A-1)*n it can work out 5 = 120 Therefore a , and for e asked exclamation point behind mean anything sir , thank you
It denotes the factorial. 5! = 1*2*3*4*5 = 120.
KieuTraVe have(The parameters)
{
ThanHam;
}
Waiter, these parameters themselves to be not his function in the body, eg : parameters are “int n”
, his offering the “int n” This function is not in him, its parameters still empty
But sometimes we need to pass on the new user is nhé.
passed is why he
You can review the theory and examples in order to visualize easier.
Let me ask the ” ? the : b ” trong return a > b ? the : b; What is sir ?
It's like if else that. Study carefully not anything. See here while. https://cachhoc.net/2014/12/11/lap-trinh-c-bai-5-cau-truc-re-nhanh-if-else-switch-case-trong-c/#24_Toan_tu_dieu_kien_8211_If_else_rut_gon
Sir Hi.Em many thanks!
#include
int nguyento (int n) {
if (n/1==0&&n/2!=0){
return 1;}
return 0;}
int sohoanhao (int n){
int s=1;
for (int i=2;in>=n;i ) {
if (n/i!=0) {continue;}
else if (n/i==0) {s+=i;}
else if (s==n+n){return 1 ;}
else{return 0;}}
}
int main(){
int n=1;
while (n>0){
printf(“Enter the :”);
scanf(“%d”,&n);
if (nguyento(n)==1) {
printf(“so %d la nguyen to n”,n);}
else if (sohoanhao(n)==1){
printf(“% d so it slides so iron / n”,n);
}
}
return 0;
}
program runs only to the introduction of (n) ko ma vegetarian at? ì ;ae households through brain
may number you enter is not a prime number, is also not perfect number.
let me ask int main(void) and various void main ntn sir
#include
int snt(int m)
{
int j;
if(m<2) return 0;
else
{
for(j=2;j<(m/2+1);j )
if(m%j==0 && m!= 2) return 0;
}
return 1;
}
int main()
{
int n,in;
scanf("% D",&n);
int a[n];
for(i=0;in<n;i )
{
scanf("% D",the[in]);
if(snt(the[in])==1) printf("% D",the[in]);
}
return 0;
}
Why do I code it to stopworking ???
entry a[in] that's wrong.