13 Functions
13 Functions
ENGINEERING
LAB NO : 13
TITLE : Functions
SUBMITTED TO : Ms. Maha Intakhab Alam
SUBMITTED BY :
BATCH : Avionics 09
SECTION :
Marks Obtained :
Remarks:
DEADLINE:
DATE OF SUBMISSION:
Table of Contents
1 Functions...................................................................................................4
Predefined Functions....................................................................................4
2 Create a Function......................................................................................4
3 Call a Function...........................................................................................4
4 Parameters and Arguments.......................................................................6
5 Multiple Parameters..................................................................................7
6 Pass Arrays as Function Parameters.........................................................8
7 Return Values............................................................................................8
8 Real-Life Example....................................................................................10
9 Function Declaration and Definition........................................................11
10 Recursion.............................................................................................13
11 Math Functions.....................................................................................14
12 Other Math Functions...........................................................................15
13 TASKS……………………………………………………………………………………..
……………….15
14 PRACTICE
PROBLEMS………………………………………………………………………………16
1 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
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;
}
2 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
3 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;
}
Example
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
output:
// I just got executed!
// I just got executed!
void {
printf("I just got executed!");
}
int main() {
return 0;
}
Syntax
returnType functionName(parameter1, parameter2, paramet
er3) {
// code to be executed
}
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
5 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;
}
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.
6 PASS ARRAYS AS FUNCTION PARAMETERS
You can also pass arrays to a function:
Example
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]).
7 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)
Example
int main() {
printf("Result is: %d", myFunction(5, 3));
return 0;
}
// Outputs 8 (5 + 3)
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)
8 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;
return 0;
}
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)
Example
// Function declaration
void myFunction();
// Function definition
void myFunction() {
printf("I just got executed!");
}
Another Example
If we use the example from the previous chapter regarding function 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)
Example
// Function declaration
int myFunction(int, int);
// Function definition
int myFunction(int x, int y) {
return x + y;
}
10 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:
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.
The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly,
recursion can be a very efficient and mathematically-elegant approach to
programming.
11 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
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:
printf("%f", ceil(1.4));
printf("%f", floor(1.4));
Power
Function Description
TASKS
1. Create separate functions for the following tasks and then call them all in
one program
i. Taking user info (Name, age, gender, reg no, university, city)
ii. Taking user grades (3 subjects and 3 labs)
iii. Check whether the student passes both subjects and course. If F in
course F in lab. If F in lab, F in course.
Integrate and call all functions in one main program and perform
testing.
2. Write a program that calculates the area and perimeter of a rectangular
room in a house. The user will provide the length and width of the room in
meters.
i. Define a function calculate_area that takes the length and width of a
room as parameters and returns its area.
ii. Define a function calculate_perimeter that takes the length and width
of a room as parameters and returns its perimeter.
In the main function, prompt the user to enter the length and width of the
room in meters.
- Call the calculate_area function with the length and width provided by
the user and print the area of the room in square meters.
- Call the calculate_perimeter function with the length and width
provided by the user and print the perimeter of the room in meters.
PRACTICE PROBLEMS:
Convert these programs from lab 10 and 11 to functions. Call them in your
main program and test your code.
1. Write a C program to calculate the sum of all even numbers from 1 to n
using a while loop.
2. Write a C program that logs daily temperatures. The user can enter the
temperature for each day, and the program calculates and displays the
average temperature once the user inputs -1.
3. Write a C program to track the number of steps taken each day. The user
can input the number of steps for each day, and the program should
calculate and display the total number of steps taken until the user inputs
-1.
4. Write a C program that takes coffee orders. The user can enter the type of
coffee they want, and the program will keep a count of each type. The
program stops taking orders when the user inputs "stop".
5. Write a C program to count the number of votes for a candidate in an
election. The program should keep asking for votes until the user inputs a
special character (e.g., 0) to stop.
6. Write a function that replaces all occurrences of a substring in a
paragrapgh specified by the user with another substring also specified by
the user. Both the paragraph, original substring to be replaced and the
new substring will be provided by the user.
7. Write a function that checks if an array is a palindrome (reads the same
forwards and backwards).