0% found this document useful (0 votes)
2 views16 pages

13 Functions

The document is a lab guide for a Computer Programming Lab focused on functions in programming. It covers topics such as creating and calling functions, using parameters and arguments, recursion, and predefined math functions. Additionally, it includes exercises and tasks for practical application of the concepts learned.

Uploaded by

eishaahmed17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

13 Functions

The document is a lab guide for a Computer Programming Lab focused on functions in programming. It covers topics such as creating and calling functions, using parameters and arguments, recursion, and predefined math functions. Additionally, it includes exercises and tasks for practical application of the concepts learned.

Uploaded by

eishaahmed17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

DEPARTMENT OF AVIONICS

ENGINEERING

SUBJECT : Computer Programming Lab

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

1. myFunction() is the name of the function


2. void means that the function does not have a return value. You will learn
more about return values later in the next chapter
3. Inside the function (the body), add code that defines what the function
should do

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

// 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;
}
output:
// I just got executed!
// I just got executed!

// I just got executed!rself With Exercises


Exercise:

Create a method named myFunction and call it inside main().

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

int main() {
return 0;
}

4 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, paramet
er3) {
// code to be executed
}

The following function that 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.

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

// Hello Liam. You are 3 years old.


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

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

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]).

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

This example returns the sum of a function with two parameters:

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)

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;

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

9 FUNCTION DECLARATION AND DEFINITION


You just 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!");
}

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)

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

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

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

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

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

To find the square root of a number, use the sqrt() function:

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

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

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

12 OTHER MATH FUNCTIONS


A list of other popular math functions (from the <math.h> library) can be found in
the table below:

Function Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x

asin(x) Returns the arcsine of x

atan(x) Returns the arctangent of x

cbrt(x) Returns the cube root of x

cos(x) Returns the cosine of x

exp(x) Returns the value of Ex

sin(x) Returns the sine of x (x is in radians)

tan(x) Returns the tangent of an angle

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.

3. Add another function to the above program to calculate the cost of


painting the room and integrate it into your main code.
i. Define a function calculate_paint_cost that takes the area of the room
and the cost per square meter of painting as parameters and returns
the total cost of painting the walls.
ii. Call the calculate_paint_cost function with the area of the room and the
cost per square meter of painting provided by the user, and print the
total cost of painting the walls.
4. Write a program which creates separate functions for each part of the
game.
i. Function for menu interface: Write this function to create a menu
interface for a game. Include options such as Start game, Create
character, Enter Score, Show score, Exit, etc. Use a for loop to
continuously display the menu until the user chooses to exit.
ii. Function for character creation: Write this function to implement a
basic character creation system for a game. Prompt the user to enter
their character's name, choose a class (warrior, mage, archer, etc.),
and allocate points to different attributes (strength, intelligence,
agility, etc.). make it so the user is asked to make character every time
until he/she says stop.
iii. Function to keep scoring: Write this function to implement a high score
tracking system for a game. Allow the user to enter their score after
completing a game.
iv. Function for displaying high scores: display the top 10 high scores
using a for loop.
v. In the main program: give the user choice to choose to start the game,
create a character, enter a score, show high scores or exit program. for
each choice, call the relevant function in your main program.

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

You might also like