0% found this document useful (0 votes)
11 views

Functions

Uploaded by

cargha440
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Functions

Uploaded by

cargha440
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.

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!

For example, main() is a function, which is used to execute code, and printf() is a
function; used to output/print text to the screen:

Example
#include <stdio.h>

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 {}:

Syntax

Void myFunction() {

// code to be executed

}
Example Explained

myFunction() is the name of the function

void means that the function does not have a return value. You will learn
more about return values later in the next chapter

Inside the function (the body), add code that defines what the function
should do

Call a Function

Declared functions are not executed immediately. They are “saved for later
use”, and will be executed when they are called.

To call a function, write the function’s name followed by two parentheses ()


and a semicolon ;

In the following example, myFunction() is used to print a text (the action),


when it is called:

Example

#include <stdio.h>

// Create a function

Void myFunction() {

Printf(“I just got executed!”);

Int main() {

myFunction(); // call the function

return 0;
}

Calculate the Sum of Numbers

You can put almost whatever you want inside a function. The purpose of the
function is to save the code, and execute it when you need it.

Like in the example below, we have created a function to calculate the sum
of two numbers. Whenever you are ready to execute the function (and
perform the calculation), you just call it:

#include <stdio.h>

// Create a function

Void calculateSum() {

Int x = 5;

Int y = 10;

Int sum = x + y;

Printf(“The sum of x + y is: %d”, sum);

Int main() {

calculateSum(); // call the function

return 0;

Parameters and Arguments

Information can be passed to functions as a parameter. Parameters act as


variables inside the function.
Parameters are specified after the function name, inside the parentheses.
You can add as many parameters as you want, just separate them with a
comma:

Syntax

returnType functionName(parameter1, parameter2, parameter3) {

// code to be executed

#include <stdio.h>

Void myFunction(char name[]) {

Printf(“Hello %s\n”, name);

Int main() {

myFunction(“Liam”);

myFunction(“Jenny”);

myFunction(“Anja”);

return 0;

Multiple Parameters

Inside the function, you can add as many parameters as you want:

#include <stdio.h>
Void myFunction(char name[], int age) {

Printf(“Hello %s. You are %d years old\n”, name, age);

Int main() {

myFunction(“Liam”, 3);

myFunction(“Jenny”, 14);

myFunction(“Anja”, 30);

return 0;

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:

#include <stdio.h>

Int myFunction(int x) {

Return 5 + x;

Int main() {

Printf(“Result is: %d”, myFunction(3));

Return 0;

}
If we consider the “Calculate the Sum of Numbers” example one more time,
we can use return instead and store the results in different variables. This
will make the program even more flexible and easier to control:

Example

#include <stdio.h>

Int calculateSum(int x, int y) {

Return x + y;

Int main() {

Int result1 = calculateSum(5, 3);

Int result2 = calculateSum(8, 2);

Int result3 = calculateSum(15, 15);

Printf(“Result1 is: %d\n”, result1);

Printf(“Result2 is: %d\n”, result2);

Printf(“Result3 is: %d\n”, result3);

Return 0;

C VARIABLE SCOPE

Now that you understand how functions work, it is important to learn how
variables act inside and outside of functions.

In C, variables are only accessible inside the region they are created. This is
called scope.
Local Scope

A variable created inside a function belongs to the local scope of that


function, and can only be used inside that function:

#include <stdio.h>

void myFunction() {

// Local variable that belongs to myFunction

int x = 5;

// Print the variable x

printf("%d", x);

int main() {

myFunction();

return 0;

A local variable cannot be used outside the function it belongs to.

If you try to access it outside the function, an error occurs:

#include <stdio.h>

Void myFunction() {

// Local variable that belongs to myFunction

Int x = 5;
}

Int main() {

myFunction();

// Print the variable x in the main function

Printf(“%d”, x);

Return 0;

Global Scope

A variable created outside of a function, is called a global variable and


belongs to the global scope.

Global variables are available from within any scope, global and local:

#include <stdio.h>

// Global variable x

Int x = 5;

Void myFunction() {

// We can use x here

Printf(“%d\n”, x);

Int main() {
myFunction();

// We can also use x here

Printf(“%d\n”, x);

Return 0;

Naming Variables

If you operate with the same variable name inside and outside of a function,
C will treat them as two separate variables; One available in the global scope
(outside the function) and one available in the local scope (inside the
function):

Example

The function will print the local x, and then the code will print the global x:

#include <stdio.h>

// Global variable x

Int x = 5;

Void myFunction() {

// Local variable with the same name as the global variable

Int x = 22;

Printf(“%d\n”, x); // Refers to the local variable x

Int main() {

myFunction();
printf(“%d\n”, x); // Refers to the global variable x

return 0;

However, you should avoid using the same variable name for both globally
and locally variables as it can lead to errors and confusion.

In general, you should be careful with global variables, since they can be
accessed and modified from any function:

#include <stdio.h>

// Global variable

Int x = 5;

Void myFunction() {

Printf(“%d\n”, ++x); // Increment the value of x by 1 and print it

Int main() {

myFunction();

printf(“%d\n”, x); // Print the global variable x

return 0;

Conclusion
To sum up, use local variables (with good variable names) as much as you
can. This will make your code easier to maintain and better to understand.
However, you may find global variables when working on existing C
programs or while collaborating with others. Therefore, it is good to
understand how the scope works and how to use it effectively to make sure
your code is clear and functional.

Function Declaration and Definition


You have already learned from the previous chapters that you can create and
call a function in the following way:

Example
#include <stdio.h>

// Create a function

Void myFunction() {

Printf(“I just got executed!”);

Int main() {

myFunction(); // call the function

return 0;

}A function consist of two parts:

Declaration: the function’s name, return type, and parameters (if any)

Definition: the body of the function (code to be executed)

Void myFunction() { // declaration

// the body of the function (definition)

}
For code optimization, it is recommended to separate the declaration and the
definition of the function.

You will often see C programs that have function declaration above main(),
and function definition below main().

This will make the code better organized and easier to read:

Example

#include <stdio.h>

// Function declaration

Void myFunction();

// The main method

Int main() {

myFunction(); // call the function

return 0;

// Function definition

Void myFunction() {

Printf(“I just got executed!”);

}
What About Parameters

If we use the example from the function parameters chapter regarding


parameters and return values:

#include <stdio.h>

Int myFunction(int x, int y) {

Return x + y;

Int main() {

Int result = myFunction(5, 3);

Printf(“Result is = %d”, result);

Return 0;

#include <stdio.h>

// Declare two functions, myFunction and myOtherFunction

void myFunction();

void myOtherFunction();

int main() {

myFunction(); // call myFunction (from main)

return 0;

// Define myFunction
void myFunction() {

printf("Some text in myFunction\n");

myOtherFunction(); // call myOtherFunction (from myFunction)

// Define myOtherFunction

void myOtherFunction() {

printf("Hey! Some text in myOtherFunction\n");

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 may be a bit difficult to understand. The best way to figure out
how it works is to experiment with it.

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:

#include <stdio.h>

Int sum(int k);

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;

}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:

Example

Printf(“%f”, sqrt(16));

Round a Number

The ceil() function rounds a number upwards to its nearest integer, and the
floor() method rounds a number downwards to its nearest integer, and
returns the result:

Example

Printf(“%f”, ceil(1.4));
Printf(“%f”, floor(1.4));

Power

The pow() function returns the value of x to the power of y (xy):

Example

Printf(“%f”, pow(4, 3));

Power
The pow() function returns the value of x to the power of y (xy):

Example
printf("%f", pow(4, 3));

You might also like