0% found this document useful (0 votes)
13 views46 pages

Module 3 CC

Module 3 discusses the concepts of functions and arrays in C programming, emphasizing the importance of breaking programs into manageable functions for easier coding and testing. It covers function declaration, definition, calling conventions, and the differences between call by value and call by reference. Additionally, it explains variable scope, including block, function, program, and file scope, along with storage classes that define the visibility and lifetime of variables.

Uploaded by

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

Module 3 CC

Module 3 discusses the concepts of functions and arrays in C programming, emphasizing the importance of breaking programs into manageable functions for easier coding and testing. It covers function declaration, definition, calling conventions, and the differences between call by value and call by reference. Additionally, it explains variable scope, including block, function, program, and file scope, along with storage classes that define the visibility and lifetime of variables.

Uploaded by

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

www.acharya.ac.

in

Module 3 – Functions and Arrays


Introduction
• C enables programmers to break up a program into
segments commonly known as functions, each of
which can be written more or less independently of the
others.
• Each function id a program is supposed to perform a
well-defined task.
Dept. of MCA
Click to Edit • Interface is specified by the function name.
• Not necessary that main() can call only one function, it
can call as many functions, as many times as it wants.
Necessity of Functions
• Divides the program into separate well-defined
functions facilities each function to be written and
tested separately.
• Understanding, coding and testing multiple separate
functions is far easier than doing it for one big function.
Dept. of MCA
• Allows programmer to reduce the lines of code in
Click to Edit main().
• Libraries in C contain a set of functions which are pre-
written and tested, and can be used without worrying
the code details.
• Reduces and divided the workload.
• Functions can also be user-defined as per requirements.
Using Functions
• Function f that uses another function g is known as calling
function and g is known as called function.
• Inputs that a function takes are known as arguments/paraments.
• When called function returns some results back to calling
function, it is said to return that result.
• The calling function may or may not pass parameters to the
Dept. of MCA called function. If the called function accepts arguments, the
Click to Edit calling function will pass parameters, else it will not do so.
• Function declaration is declaration statement that identifies a
function with its name, list or arguments that it accepts and the
type of data it returns.
• Function definition consists of function header that identifies the
function, followed by the body of function containing the
executable code for that function.
Function Declaration
• Syntax : return_data_type function_name(data_type
variable1, data_type variable2,….);
Function Declaration Use of the function

Return data type Converts a character to upper case. The function receives
a character as an argument, converts it into upper case
char convert_to_uppercase(char ch); and returns the converted character back to the calling
dunction.
Function name Calculated average if 2 integer numbers a and b received
as argument. The function returns a floating point value.
float avg (int a, int b);
Data type of variable Finds the largest of 3 numbers, a, b,c received as
Dept. of MCA argument. An integer value which is the largest of the three
Click to Edit int find_largest (int a, int b, int c); numbers is returned to the calling function.
Variable 1 Multiplies 2 floating point numbers a and b that are
received as arguments and returns a double value.
double multiply (float a, float b);
void swap (int a, int b); Swaps or interchanges the value of integer variables a and
b received as arguments. The function returns no value,
therefore the return type is void.
void print(void); The function is used to print information on screen. The
function neither accepts any value as arguments nor
returns any value. Therefore, the return type is void and
the argument list contains void data type
Function Definition
• A space is allocated for the function memory when it is defined.
• It comprises two parts:
a. Function Header
b. Function Body
• Syntax:
return_data_type function_name(data_type variable1, data_type
Dept. of MCA variable2, ….)
Click to Edit
{
………
Statements
………
return (variable);
}
Function Definition
• It is an error to place a semicolon after the function
header in the function definition.
• The parameter list in the function definition as well as
function declaration must match.
• A function can either be defined before or after the
Dept. of MCA
main().
Click to Edit
Function Call
• Syntax:
function_name (variable1, variable2,….);
• List of variable used in the function call is known as actual
parameter list. The actual parameter list may contain variable
names, expressions, or constants.
• Function name and number and type of arguments in the
Dept. of MCA
Click to Edit
function call must be same as that of given in function
declaration and function header of function definition.
• If the parameter passed to function more than what it is
specified to accept than the extra arguments will be discarded.
If anything less, then garbage value will be displayed.
• Names (not the types) of variables in function declaration, call
and header of function definition may vary
Function Call
• Arguments may be passed in the form of expressions to
the called function. In such cases, the arguments are
first evaluated and converted to the type of formal
parameter and then the body of the function gets
executed.
• Parameter list must be separated by commas.
Dept. of MCA
Click to Edit • It is an error to use void as the return type when the
function is expected to return a value to the calling
function.
return Statement
• The return Statement terminated the execution of the
called function and returns control to the calling
function.
• When the return statement is encountered, the program
execution resumes in the calling function at the point
immediately following the function call.
• Syntax: return <expression>;
Dept. of MCA
Click to Edit
return Statement
• An error is generated when the function does not retune
data of the specified type.
• A function that does not return any value cannot be
placed on the right side of the assignment operator.

Dept. of MCA
Click to Edit
Passing parameters to functions
• When a function is called, the calling function may
have to pass some values to the called function.
• There are 2 ways in which arguments/parameters can be
passed to function:
i. Call by Value in which values of variable are
Dept. of MCA
passed by the calling function to the called function.
Click to Edit
ii. Call by reference in which address of variables are
passed by the calling function to the called function.
Call by Value
• The called function creates new variables to store the
value of the arguments passed to it. The called function
uses a copy of the actual argument to perform its
intended task.

Dept. of MCA
Click to Edit
Call by Reference
• When calling function passes an argument to the called
function using call-by-value method, the only way to
return the modified value of the argument to the caller
is explicitly using the return statement. A better option
when a function wants to modify the value of the
argument is to pass arguments using call-by-reference
Dept. of MCA technique.
Click to Edit
• We declare the function parameters as references rather
then normal variables. When this is done any changes
made by function to the arguments it receives are
visible in the calling function.
Call by Reference
• To indicate an argument is passed using call by
reference, an asterisk (*) is placed after the type in the
parameter list. This way the changes made to the
parameter in called function will then be reflected in the
calling function.
• In call-by-reference method, a function receives an
Dept. of MCA
Click to Edit
implicit reference to the argument, rather then a copy of
its value.
• The function can modify the value of the variable and
the change will be reflected in the calling function as
well.
Advantages and Disadvantages
Advantages Disadvantages

Since arguments are not copied into new


variables, it provides greater time and space
efficiency
The side-effect of using this technique is that
The called function can change the value od the when and argument is passed using call by
argument and the change is reflected in the address, it becomes difficult to tell whether that
calling function argument is meant for input, output or both.

Dept. of MCA A return statement can return only one value. In


Click to Edit case we need to return multiple values, pass those
arguments by reference
Call By Value Call By Reference
Differences While calling a function, instead of passing the
While calling a function, we pass the values of
values of variables, we pass the address of
variables to it. Such functions are known as “Call
variables(location of variables) to the function
By Values”.
known as “Call By References.

In this method, the value of each variable in the In this method, the address of actual variables in
calling function is copied into corresponding the calling function is copied into the dummy
dummy variables of the called function. variables of the called function.

With this method, the changes made to the


With this method, using addresses we would
dummy variables in the called function have no
have access to the actual variables and hence we
effect on the values of actual variables in the
would be able to manipulate them.
calling function.
Dept. of MCA
Click to Edit In call-by-values, we cannot alter the values of In call by reference, we can alter the values of
actual variables through function calls. variables through function calls.
Values of variables are passed by the Simple Pointer variables are necessary to define to store
technique. the address values of variables.
This method is preferred when we have to pass This method is preferred when we have to pass a
some small values that should not change. large amount of data to the function.
Call by value is considered safer as original data Call by reference is risky as it allows direct
is preserved modification in original data
Scope of Variables
• In C, all constants and variables have a defined scope,
which means the accessibility and visibility of the
variables at different points in the program.
• A variable or constant in C has 4 types of scope:
1. Block
Dept. of MCA
2. Function
Click to Edit 3. Program
4. File
Block Scope
• A statement block is a group of statements enclosed within
opening and closing of curly brackets { }.
• If a variable is declared within a statement block then as soon as
the control exits that block, the variable will cease to exist.
• Such a variable also known as Local Variable is said to have a
block scope.
• It is an error to use the name of function argument as the name of
local variable.
Dept. of MCA
Click to Edit
• Block statements may be placed one after the other in a program;
such blocks that are placed at the same level are known as Parallel
Blocks.
• A program may also contain a nested block, like a while loop
inside main(). If an integer x is declared and initialized in main(),
and then re-declared and re-initialized in a while loop, then the
integer variable x will occupy different memory slots and will be
considered as different variables.
Block Scope
• A statement block is a group of statements enclosed within
opening and closing of curly brackets { }.
• If a variable is declared within a statement block then as soon as
the control exits that block, the variable will cease to exist.
• Such a variable also known as Local Variable is said to have a
block scope.
• It is an error to use the name of function argument as the name of
local variable.
Dept. of MCA
Click to Edit
• Block statements may be placed one after the other in a program;
such blocks that are placed at the same level are known as Parallel
Blocks.
• A program may also contain a nested block, like a while loop
inside main(). If an integer x is declared and initialized in main(),
and then re-declared and re-initialized in a while loop, then the
integer variable x will occupy different memory slots and will be
considered as different variables.
Block Scope
• Variables declared with the same name as those in outer block
mask the outer block variables while executing the inner block.
• In nested blocks, variables declared outside the inner blocks are
accessible to the nested blocks, provided these variables are not
re-declared within the inner block.
• Try to avoid variable names that hides variable in outer scope.
Dept. of MCA • In order to avoid error, a programmer must use different names
Click to Edit
for variables not common to inner as well as outer blocks.
Function Scope
• Function scope indicates that a variable is active and visible
from the beginning to the end of a function.
• In C, only the goto label has function scope.
• Function scope is applicable only with goto label names. This
means that the programmer cannot have the same label names
inside a function.
Dept. of MCA • Using goto statement is not recommended as it is not considered
Click to Edit
to be a good programming practice.
Function Scope
int main()
{
.
.
loop: //A goto label has function scope
.
.
Dept. of MCA
goto label; //The goto statement
Click to Edit .
.
return 0;
}
• The label loop is visible from the beginning to the end of main()
function.
• There should not be more than one label having the same name within
the main() function.
Program Scope
• Local variables also known as Internal Variables are
automatically created when they are declared in the function
and are usable only within that function. The local variables
are unknown to other functions in the program. Such variables
cease to exist after the function in which they are declared is
exited are re-declared each time the function is called.
Dept. of MCA
• If you want a function to access some variables which are not
Click to Edit passed to it as arguments, then declare those variables outside
any function blocks. Such variables are commonly known as
Global Variables and can be accessed from any point in the
program.
Program Scope
• Lifetime: Global variables are created at the beginning of
program executing and remain in existence throughout the
period of execution of the program. Global variables are not
limited to a particular function so they exist even when a
function calls another function. These variables retain their
value so that they can be used from every function in the
program.
Dept. of MCA
Click to Edit • Place of Declaration: The global variables are declared
outside all the functions including main(). Although there is no
specific rule that states that the global variable mist be
declared, it is always recommended to declare them on top of
the program codes.
Program Scope
• Name Conflict: if a variable declared in a function that has
the same name as that of the global variable, then the function
will use the local variable declared within it and ignore the
global variable. The programmer must not use names of global
variables as the names of local variables as this may lead to
confusion and erroneous result.
Dept. of MCA
Click to Edit
File Scope
• A global variable is accessible until the end of the file, the
variable is said to have file scope. To allow a variable to have
file scope, declare that variable with the static keyword before
specifying the data type:

static int x = 10;


Dept. of MCA
Click to Edit
• A global static variable can be used anywhere from the file in
which it is declared but it is not accessible by any other file.
Such variables are useful when the programmer writes its own
header files.
Storage Classes
• Storage Classes defines the scope (visibility) and lifetime of t
variables and/or functions declared within a C program.
• They help manage memory and trace variable existence during
runtime.
• Types of Storage Classes:
 auto
Dept. of MCA
 extern
Click to Edit
 static
 register
auto Storage Class
• Default storage class for variables declared inside a function/block.
• Scope: Local to the block.
• Lifetime: Ends when the block exits.
• Initialized with: Garbage value.
• Example:
void example()
Dept. of MCA {
Click to Edit
auto int x = 10; // Local variable
}
extern Storage Class
• Used for variables defined elsewhere, typically global variables.
• Scope: Accessible across multiple files/functions.
• Lifetime: Till program termination.
• Example:
extern int y; // Declared in another file

Dept. of MCA
Click to Edit
static Storage Class
• Scope: Local to the function or globally, depending on declaration.
• Lifetime: Preserves value across function calls till program termination.
• Initialized with: 0 by default.
• Example:
void counter()
{
Dept. of MCA static int count = 0; // Retains value across calls
Click to Edit
count++;
}
register Storage Class
• Scope: Local to the block.
• Lifetime: Ends when the block exits.
• Faster than auto as stored in CPU registers.
• Address cannot be obtained using pointers.
• Example:
void example()
Dept. of MCA {
Click to Edit
register int fast_var = 5; // Frequent usage variable
}
Storage classes
Storage Class Scope Lifetime Initialized With Key Feature

Local to Ends when block Default for local


auto Garbage value
block/function exits variables.

Till program Shared across


extern Global/Across files Defined externally
termination multiple files.

Dept. of MCA
Click to Edit static Local or Global
Till program
0 (default)
Retains value
termination across calls.

Ends when block Faster access


register Local to block None
exits using CPU register.
Recursive Functions
• 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.
• Every Recursion has 2 major cases:
 Base Case, in which the problem is simple enough to be solved directly
without making any further calls to the same function
 Recursive Case, in which first the problem at hand is divided into simpler
Dept. of MCA sub-parts. Second the function calls itself bit the sub-parts of the problem
Click to Edit obtained in the first step. Third, the result is obtained by combining the
solutions of simpler sub-parts.
www.acharya.ac.in

Module 3 – Arrays
Arrays
• An array is a collection of data items or similar elements of the
same type that are stored in contiguous memory locations.
Arrays are used in computer programming to organize data.
• An array is a data structure consisting of a collection of elements
(values or variables), of same memory size, each identified by at
least one array index or key. An array is stored such that the
position of each element can be computed from its index tuple by
Dept. of MCA
Click to Edit
a mathematical formula.
Declaring of Arrays
• An array must be declared before being used. Declaring an
array means specifying three thing:
Data type : int, char, float, double,…
Name : to identify the array
Size : maximum number of values that the array can hold
• Arrays are declared as follows :

Click to Edit
type name [size]
Eg. int marks[10];
• To declare and define an array, you must specify its name,
type and size.
• The number within brackets indicates the size of the array, i.e,
maximum number of elements that can be stored in array.
Declaring of Arrays

• C does not allow declaring an array whose number of


elements is not known at the compile time therefore, the
following array declarations are illegal in C.
int arr[]
Click to Edit int n, arr[n]
• Generally it is not good programming practice to define the
size of an array as a symbolic constant : #define N 100
• The size of the array can be specified using an expression.
The components of the expression must be available for
evaluation of the expression when program is compiled.
Accessing the elements of an array
• To access a single element from array, one must use array
subscript. Eg: to access the 4th element on array, one must
write arr[3]. The subscript/index must be an integral value
or an expression that evaluated to an integral value.
• To access all the elements of the array, one must use a
loop. There is no single statement that can do that work.
• There is no single statement that can read, access or print
Click to Edit all the elements of the array. To do this, we have to do it
using a for / while / do-while loop to execute the same
statement with different index value.
Storing value in arrays
• When we declare an array, we are just allocating space for
the elements; no values are stored in the array. There are
three ways to store values in an array:
 To initialize the array elements at the time of declaration;
 To input value for every individual element at the run time.
 To assign values to the individual elements.

Click to Edit Initialize the elements


during declaration

Input values for the elements


Store values in from the keyboard
array

Assign values to individual


elements
Initializing Arrays during Declaring
• Elements of the array can also be initialized at the time of
declaration as other variables.
• When an array is initialized we need to provide a value for
every element in array.
• The value are written within curly brackets and every value is
separated by a comma. It is a compiler error to specify more
number of values than the umber of elements in the array.
Click to Edit type array_name[size] = {list of values}
int marks[5] ={90, 82, 78, 95, 88}
• If we have more initializers that the declared size of the array,
then an compile time error will be generated. Eg;
int marks [3] ={1, 2, 3, 4}
Inputting values from the keyboard
• An array can be filled by inputting values from the
keyboard. In this method, while / do-while / for loop is
executed to input the value for each element of the array.
• Eg:
int i, marks[10];
for(i=0;i<10;i++)
Click to Edit scanf(“%d”, &marks[i]);
Operations on Arrays
• The operation on arrays that can be performed are:
1. Traversing an array
2. Inserting an element in an array
3. Deleting an element from the array
4. Searching an element in array
5. Sorting an array in ascending or descending order
Dept. of MCA
Click to Edit
Traversing an array
• Traversing means accessing each and every element of the array for a specific
purpose.
• If A is an array of homogenous data elements, then traversing the data
elements can include printing every element, counting the total number of
elements, or performing any process on these elements.
• Any array is a linear data structure (because all its elements form a sequence),
traversing its elements is very simple and straightforward.
Dept. of MCA
Click to Edit
Inserting, Deleting and Searching an
element in an array
• Inserting an element means adding a new data element to an already existing
array.
• Deleting an element from an array means removing a data element from an
already existing array.
• Searching means to find whether a particular value is present in the array or
not.
Dept. of MCA
Click to Edit
Passing arrays to functions
• Like variables of other data types, we can also pass an array to function. In
some situation, one may pass an element one-by-one, or even an entire array.

Dept. of MCA
Click to Edit

You might also like