Course Introduction to Programming
Example of Functions
In this lesson, we will see several examples of functions. We will go through the following topics:
- Function sum of int
- Function sum of float
- Function min int
- Function average float
Function sum int
In this topic, we will create a function that gives us the sum of two integers.
#include <stdio.h>
/*
Type of return: int -> because the sum of two integers is an integer
Name: sum
Parameters: int a, int b -> the two parts of our sum
Code: a + b
*/
int sum(int a, int b){
int s = a + b;
return s;
}
int main(){
int x = sum(2, 3); // x receives the value returned by the function sum with the parameters 2 and 3
printf("%d\n", x);
}
/* Output:
5
*/
In our "sum" function, declared in the above code, we have the return command. This command indicates that the function must return a certain value which, in this case, is the
Therefore, our program will start with the main function and will assign the value of "sum(2, 3)" to
Function sum float
In this topic, we will create a function that provides the sum of two floats.
#include <stdio.h>
/*
Type of return: float -> because the sum of two reals is a real
Name: sum
Parameters: float a, float b -> the two parts of our sum
Code: a + b
*/
float sum(float a, float b){
float s = a + b;
return s;
}
int main(){
float x, y;
scanf("%f %f", &x, &y);
printf("%.1f\n", sum(x, y));
}
Our code above defines a "sum" function that receives two real numbers and returns the sum of them, which is also a real number.
In the main function, two real numbers
Function min int
In this topic, we will create a function that gives us the smallest of two integers.
#include <stdio.h>
/*
Type of return: int -> because the smallest of two integers is an integer
Name: min
Parameters: int a, int b -> the two integers to be analyzed
Code: an if-else structure
*/
int min(int a, int b){
if(a < b){ // checks if a is lower than b
return a;
}
else{ // otherwise
return b;
}
}
int main(){
int x, y;
scanf("%d %d", &x, &y);
printf("%d\n", min(x, y));
}
Note that in the above code, unlike what has been seen so far, there are two return commands.
When the function is called, it checks if the value of
However, if
Note also that if
Function average float
In this topic, we will create a function that gives us the average between two real numbers.
#include <stdio.h>
float average(float a, float b){
return (a+b)/2.0;
}
int main(){
float x, y;
scanf("%f %f", &x, &y);
printf("%.2f\n", average(x, y));
}
As an incentive, try to interpret the operation of the above code yourself. After that, use your creativity to create your own functions, using all the knowledge acquired so far.
During this topic, it is important that you try to solve all the next exercises using functions ๐.
Until the next lesson!