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

Unit V Function

Uploaded by

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

Unit V Function

Uploaded by

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

C Functions:-

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
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
Inside main, call myFunction():
// Create a function
void myFunction() {
printf("I just got executed!");
}

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"

A function can be called multiple times:


Example
void myFunction() {
printf("I just got executed!");
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

// I just got executed!


// I just got executed!
// I just got executed!

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

// Outputs The sum of x + y is: 15

C Function Parameters

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
}

In the example below, the function takes a string of characters with name as parameter. When the
function is called, we pass along a name, which is used inside the function to print "Hello" and the
name of each person:
Example
void myFunction(char name[]) {
printf("Hello %s\n", name);
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}

// Hello Liam
// Hello Jenny
// Hello Anja

When a parameter is passed to the function, it is called an argument. So, from the example
above: name is a parameter, while Liam, Jenny and Anja are arguments.

Multiple Parameters
Inside the function, you can add as many parameters as you want:
Example
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;
}

// Hello Liam. You are 3 years old.


// Hello Jenny. You are 14 years old.
// Hello Anja. You are 30 years old.

If we consider the "Calculate the Sum of Numbers" example from the previous page, we can make a
more sustainable program by using function parameters:
Example
void calculateSum(int x, int y) {
int sum = x + y;
printf("The sum of %d + %d is: %d\n", x, y, sum);
}

int main() {
calculateSum(5, 3);
calculateSum(8, 2);
calculateSum(15, 15);
return 0;
}

Notes on Parameters
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.

Pass Arrays as Function Parameters


You can also pass arrays to a function:
Example
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
printf("%d\n", myNumbers[i]);
}
}

int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}

Example Explained
The function (myFunction) takes an array as its parameter (int myNumbers[5]), and loops through
the array elements with the for loop.
When the function is called inside main(), we pass along the myNumbers array, which outputs the
array elements.
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]).

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


Example
int myFunction(int x, int y) {
return x + y;
}

int main() {
printf("Result is: %d", myFunction(5, 3));
return 0;
}

// Outputs 8 (5 + 3)

You can also store the result in a variable:


Example
int myFunction(int x, int y) {
return x + y;
}

int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)

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

Tip: If you have many "result variables", it is better to store the results in an array:
Example
int calculateSum(int x, int y) {
return x + y;
}

int main() {
// Create an array
int resultArr[6];

// Call the function with different arguments and store the results in the array
resultArr[0] = calculateSum(5, 3);
resultArr[1] = calculateSum(8, 2);
resultArr[2] = calculateSum(15, 15);
resultArr[3] = calculateSum(9, 1);
resultArr[4] = calculateSum(7, 7);
resultArr[5] = calculateSum(1, 1);

for (int i = 0; i < 6; i++) {


printf("Result%d is = %d\n", i + 1, resultArr[i]);
}

return 0;
}

Real-Life Example
To demonstrate a practical example of using functions, let's create a program that converts a value
from fahrenheit to celsius:
Example
// Function to convert Fahrenheit to Celsius
float toCelsius(float fahrenheit) {
return (5.0 / 9.0) * (fahrenheit - 32.0);
}

int main() {
// Set a fahrenheit value
float f_value = 98.8;

// Call the function with the fahrenheit value


float result = toCelsius(f_value);

// Print the fahrenheit value


printf("Fahrenheit: %.2f\n", f_value);

// Print the result


printf("Convert Fahrenheit to Celsius: %.2f\n", result);

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:
Example
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:
Example
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:
Example
A variable created outside of a function is global and can therefore be used by anyone:
// Global variable x
int x = 5;

void myFunction() {
// We can use x here
printf("%d", x);
}

int main() {
myFunction();

// We can also use x here


printf("%d", 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:
// Global variable x
int x = 5;

void myFunction() {
// Local variable with the same name as the global variable (x)
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:
Example
Change the value of x from myFunction:
// 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;
}

// The value of x is now 6 (no longer 5)

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.

C Function Declaration and Definition

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
// 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
// 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:
Example
int myFunction(int x, int y) {
return x + y;
}

int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)

It is considered good practice to write it like this instead:


Example
// Function declaration
int myFunction(int x, int y);

// The main method


int main() {
int result = myFunction(5, 3); // call the function
printf("Result is = %d", result);
return 0;
}

// Function definition
int myFunction(int x, int y) {
return x + y;
}

Functions Calling Other Functions


As long as you declare functions first, it is also possible to use functions to call other functions:
Example
Use one function to call another function:
// 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");
}

C 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:
Example
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;
}
}
Try it Yourself »
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.

C Math Functions

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));

You might also like