0% found this document useful (0 votes)
42 views19 pages

Unit 3 Topic 2

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

Unit 3 Topic 2

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

Unit III

Topic 2

Functions and Program Structure in 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

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:

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():

 A function can be called multiple times.


 You can also use functions to call other functions.

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

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.

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

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

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

 You can also store the result in a variable:


we can use return instead and store the results in different variables. This
will make the program even more flexible and easier to control.

 If you have many "result variables", it is better to store the results


in an array.
Real-Life Example:

To demonstrate a practical example of using functions, let's create a


program that converts a value from fahrenheit to celsius:

 C Variable Scope

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:
 A local variable cannot be used outside the function it belongs to.

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

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.
 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:

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.


 C Function Declaration and Definition

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.
 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:

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.

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

Power

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

 Structure of program
The basic structure of a C program is divided into 6 parts which makes
it easy to read, modify, document, and understand in a particular
format. C program must follow the below-mentioned outline in order to
successfully compile and execute.
Debugging is easier in a well-structured C program.
Sections of the C Program

There are 6 basic sections responsible for the proper execution of a


program. Sections are mentioned below:
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Program

Documentation:

This section consists of the description of the program, the name of the
program, and the creation date and time of the program. It is specified
at the start of the program in the form of comments. Documentation can
be represented as:
// description, name of the program, programmer name, date, time
etc.
or
/*
description, name of the program, programmer name, date, time
etc.
*/

Anything written as comments will be treated as documentation of the


program and this will not interfere with the given code. Basically, it
gives an overview to the reader of the program.
Preprocessor Section

All the header files of the program will be declared in


the preprocessor section of the program.
Header files help us to access other’s improved code into our code.
A copy of these multiple files is inserted into our program before the
process of compilation.
Example:

#include<stdio.h>
#include<math.h>

Definition

Preprocessors are the programs that process our source code before the
process of compilation. There are multiple steps which are involved in
the writing and execution of the program. Preprocessor directives start
with the ‘#’ symbol. The #define preprocessor is used to create a
constant throughout the program. Whenever this name is encountered
by the compiler, it is replaced by the actual piece of defined code.
Example:
#define long long ll

Global Declaration

The global declaration section contains global variables, function


declaration, and static variables. Variables and functions which are
declared in this scope can be used anywhere in the program.
Example:

int num = 18;


Main() Function

Every C program must have a main function. The main() function of


the program is written in this section. Operations like declaration and
execution are performed inside the curly braces of the main program.
The return type of the main() function can be int as well as void too.
void() main tells the compiler that the program will not return any
value. The int main() tells the compiler that the program will return an
integer value.
Example:
void main()
or
int main()

Sub Programs

User-defined functions are called in this section of the program. The


control of the program is shifted to the called function whenever they
are called from the main or outside the main() function. These are
specified as per the requirements of the programmer.

Example:
int sum(int x, int y)
{
return x+y;
}
 Structure of C Program with example

Example:
Below C program to find the sum of 2 numbers.

// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/

// Link
#include <stdio.h>

// Definition
#define X 20
// Global Declaration
int sum(int y);
// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}
// Subprogram
int sum(int y)
{
return y + X;
}
Output
Sum: 75
 Steps involved in the Compilation and execution of a C
program-

 Program Creation
 Compilation of the program
 Execution of the program
 The output of the program

You might also like