C Functions
C Functions
Predefined Functions
So it turns out you already know what a function is. You have
been using it the whole time while studying this tutorial!
int main() {
printf("Hello World!");
return 0;
}
Create a Function
To create (often referred to as declare) your own function,
specify the name of the function, followed by parentheses ()
and curly brackets {} :
Call a Function
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
Example :
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
Syntax :
Example :
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Hello Liam
// Hello Jenny
// Hello Anja
Multiple Parameters
Inside the function, you can add as many parameters as you
want.
Example :
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
Note that when you are working with multiple parameters, the
function call must have the same number of arguments as there
are parameters, and the arguments must be passed in the same
order.
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
Example Explained
Note that when you are working with multiple parameters, the
function call The function (myFunction) takes an array as its
parameter (int myNumbers[5]), and loops through the array
elements with the for loop.
Note that when you call the function, you only need to use the
name of the array when passing it as an argument
myFunction(myNumbers). However, the full declaration of the
array is needed in the function parameter (int myNumbers[5]).
have the same number of arguments as there are parameters,
and the arguments must be passed in the same order.
Return Values
The void keyword, used in the previous examples, indicates that
the function should not return a value. If you want the function
to return a value, you can use a data type (such as int or float,
etc.) instead of void, and use the return keyword inside the
function :
int myFunction(int x) {
return 5 + x;
}
int main() {
printf("Result is: %d", myFunction(3));
return 0;
}
// Outputs 8 (5 + 3)
This example returns the sum of a function with two
parameters :
int main() {
printf("Result is: %d",
myFunction(5, 3));
return 0;
}
// Outputs 8 (5 + 3)
int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)
Function Declaration and Definition
You just learned that you can create and call a function in the
following way :
Example
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
// Function declaration
void myFunction();
// Function definition
void myFunction() {
printf("I just got executed!");
}
Another Example
int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)
For code optimization, it is recommended to separate the
declaration and the definition of the function.
// Function declaration
void myFunction();
// Function definition
void myFunction() {
printf("I just got executed!");
}
Another Example
int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)
Recursion
Recursion is the technique of making a function call itself. This
technique provides a way to break complicated problems down
into simple problems which are easier to solve.
Recursion Example
Adding two numbers together is easy to do, but adding a range
of numbers is more complicated. In the following example,
recursion is used to add a range of numbers together by
breaking it down into the simple task of adding two numbers :
int main() {
int result = sum(10);
printf("%d", result);
return 0;
}
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
Example Explained
When the sum() function is called, it adds parameter k to the
sum of all numbers smaller than k and returns the result. When
k becomes 0, the function just returns 0. When running, the
program follows these steps :
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program
stops there and returns the result.
Math Functions
There is also a list of math functions available, that allows you
to perform mathematical tasks on numbers.
To use them, you must include the math.h header file in your
program :
#include <math.h>
Square Root
To find the square root of a number, use the sqrt() function :
printf("%f", sqrt(16));
Output : 4.000000
Round a Number
printf("%f", ceil(1.4));
printf("%f", floor(1.4));
Output : 2.000000
1.000000
Power
The pow() function returns the value of x to the power of y
(xy) :
Output : 64.000000
Other Math Functions
A list of other popular math functions (from the <math.h>
library) can be found in the table below :
Function Description
sin(x)
Returns the sine of x (x is in radians)
FILE *fptr
fptr = fopen(filename, mode);
Parameter Description
w - Writes to a file
a - Appends new data to a file
r - Reads from a file
Create a File
To create a file, you can use the w mode inside the fopen()
function.
Example
FILE *fptr;
// Create a file
fptr = fopen("filename.txt", "w");
This will close the file when we are done with it.
It is considered as good practice, because it makes sure that :
Write To a File
Let's use the w mode from the previous chapter again, and
write something to the file we just created.
The w mode means that the file is opened for writing. To insert
content to it, you can use the fprint() function and add the
pointer variable (fptr in our example) and some text.
Example
FILE *fptr;
Note : If you write to a file that already exists, the old content is
deleted, and the new content is inserted. This is important to
know, as you might accidentally erase existing content.
For example :
fprintf(fptr, "Hello World!");
Example
FILE *fptr;
Note : Just like with the w mode; if the file does not exist,
the a mode will create a new file with the "appended"
content.
Read a File
Earlier we wrote a file using w and a modes inside the fopen()
function.
.
To read from a file, you can use the r mode
Example
FILE *fptr;
FILE *fptr;
Example
Now, we can print the string, which will output the content of
the file.
To read every line of the file, you can use a while loop.
Example
FILE *fptr;
Good Practice
If you try to open a file for reading that does not
exist, the fopen() function will return NULL.
Note : As a good practice, we can use an if statement to test
for NULL, and print some text instead (when the file
does not exist).
Example
FILE *fptr;
Create a Structure
You can create a structure by using the struct keyword and
declare each of its members inside curly braces :
struct myStructure {
int myNum;
char myLetter;
};
int main() {
struct myStructure s1;
return 0;
}
Access Structure Members
To access members of a structure, use the dot syntax (.) :
Example
int main() {
// Create a structure variable of myStructure called
s1
struct myStructure s1;
// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);
return 0;
}
s2.myNum = 20;
s2.myLetter = 'C';
Example
struct myStructure {
int myNum;
char myLetter;
char myString[30]; // String
};
int main() {
struct myStructure s1;
return 0;
}
An error will occur :
However, there is a solution for this! You can use the strcpy()
function and assign the value to s1.myString, like this :
Example
struct myStructure {
int myNum;
char myLetter;
char myString[30]; // String
};
int main() {
struct myStructure s1;
return 0;
}
Example
// Create a structure
struct myStructure {
int myNum;
char myLetter;
char myString[30];
};
int main() {
// Create a structure variable and assign values to
it
struct myStructure s1 = {13, 'B', "Some text"};
// Print values
printf("%d %c %s", s1.myNum, s1.myLetter,
s1.myString);
return 0;
}
Note : The order of the inserted values must match the order
of the variable types declared in the structure (13 for
int, 'B' for char, etc).
Copy Structures
You can also assign one structure to another.
Example
s2 = s1;
Modify Values
If you want to change/modify a value, you can use the dot
syntax (.).
int main() {
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};
// Modify values
s1.myNum = 30;
s1.myLetter = 'C';
strcpy(s1.myString, "Something else");
// Print values
printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);
return 0;
}
Modifying values are especially useful when you copy structure
values :
Example
// Copy s1 values to s2
s2 = s1;
// Change s2 values
s2.myNum = 30;
s2.myLetter = 'C';
strcpy(s2.myString, "Something else");
// Print values
printf("%d %c %s\n", s1.myNum, s1.myLetter, s1.myString);
printf("%d %c %s\n", s2.myNum, s2.myLetter, s2.myString);
Example
struct Car {
char brand[50];
char model[50];
int year;
};
int main() {
struct Car car1 = {"BMW", "X5", 1999};
struct Car car2 = {"Ford", "Mustang", 1969};
struct Car car3 = {"Toyota", "Corolla", 2011};
return 0;
}
enum Level {
LOW,
MEDIUM,
HIGH
};
The assigned value must be one of the items inside the enum
(LOW, MEDIUM or HIGH) :
By default, the first item (LOW) has the value 0, the second
(MEDIUM) has the value 1, etc.
int main() {
// Create an enum variable and assign a value to it
enum Level myVar = MEDIUM;
return 0;
}
Output : 1
Change Values
As you know, the first item of an enum has the value 0. The
second has the value 1, and so on.
To make more sense of the values, you can easily change them.
enum Level {
LOW = 25,
MEDIUM = 50,
HIGH = 75
};
printf("%d", myVar); // Now outputs 50
Output : 50
Note that if you assign a value to one specific item, the next
items will update their numbers accordingly :
enum Level {
LOW = 5,
MEDIUM, // Now 6
HIGH // Now 7
};
Output : 6
Enum in a Switch Statement
enum Level {
LOW = 1,
MEDIUM,
HIGH
};
int main() {
enum Level myVar = MEDIUM;
switch (myVar) {
case 1:
printf("Low Level");
break;
case 2:
printf("Medium level");
break;
case 3:
printf("High level");
break;
}
return 0;
}
Use enums when you have values that you know aren't going to
change, like month days, days, colors, deck of cards, etc.