SlideShare a Scribd company logo
C Programming : Arrays and Functions
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
20CST11 – Problem Solving and Programming
2/11/2021 3.1 Arrays 2
Syllabus
Contents
1. Arrays
– Declaring and initializing 1D array
– Two dimensional arrays
– Multidimensional arrays
2. Functions
– Basics, The anatomy of a function
– Types of functions based on arguments and return types
– Passing 1D and 2D arrays as arguments to functions
– Calling function from another function
3. Recursive functions
4. Variable scope and lifetime
5. Storage classes.
2/11/2021 3
3.1 Arrays
Introduction
• Variables can’t handle voluminous data because a
hundred data items need a hundred variables to store
them.
• The solution is to use an array, which is an ordered set
of data items stored contiguously in memory.
• Each data item represents an element of the array and
is accessed with an index or subscript.
• For instance, the elements of an array named signal
are accessed as signal[0], signal[1], signal[2], and so
forth.
• The first subscript is 0 and the last subscript is one less
than the size of the array.
2/11/2021 3.1 Arrays 4
Introduction
• The elements of an array have a common
data type (like int, char, etc.).
• An array must be declared with its type and
size to enable the compiler to allocate a
contiguous chunk of memory for all array
elements.
2/11/2021 3.1 Arrays 5
Introduction
• The first element is accessed as signal[0] and the last
element is signal[31] (not 32).
• The subscript is either zero, a positive integer or an
expression that evaluates to an integer value.
• An array element can be assigned to a variable
– (say, int x = signal[2];),
– which means we can use signal[2] wherever we use x.
• By the same logic, &signal[2] is also a valid scanf
argument like &x.
• It is easy to cycle through all array elements by using
the array subscript as a key variable in a loop.
2/11/2021 3.1 Arrays 6
Introduction
• C doesn’t offer bounds checking for arrays, i.e. it doesn’t
validate the index used to access an array element.
• For instance, the compiler will not generate an error if you
attempt to access signal[35] even though the array has 32
elements.
• A negative index (as in signal[-5]) doesn’t generate an
error either.
• C also supports multi-dimensional arrays where an
element is handled with multiple subscripts.
• Since there is virtually no limit to the number of indexes
and dimensions an array can have.
• arrays in C are very powerful data structures that can
easily gobble up a lot of memory.
2/11/2021 3.1 Arrays 7
DECLARING AND INITIALIZING AN ARRAY
• The declaration of an array specifies its name, type and
size, which is normally specified as a constant or
symbolic constant.
• The following statement declares a single-dimensional
array named signal having 32 elements, each of type
int.
• The sizeof operator, when used on an array, returns the
total usage of all elements, so the below definition
allocates 32 × sizeof(int) bytes of memory—typically,
128 bytes.
2/11/2021 3.1 Arrays 8
Layout in Memory of the Array
• months[12] and MONTHS[12] are two
separate arrays.
2/11/2021 3.1 Arrays 9
Initializing During Declaration
• In the first declaration, the number of values matches
the size of the array.
• The second declaration performs a partial initialization
by assigning values to the first three elements only.
When that happens, the remaining values are
automatically initialized to zeroes (NUL for an array of
type char).
• The third declaration uses an empty pair of brackets
([ ]) to implicitly specify the size of the array.
2/11/2021 3.1 Arrays 10
INITIALIZING AND PRINTING ARRAYS
2/11/2021 3.1 Arrays 11
2/11/2021 3.1 Arrays 12
Inserting an Element in an Array
2/11/2021 3.1 Arrays 13
Deleting an Element from an Array
2/11/2021 3.1 Arrays 14
Reversing with Two Arrays
2/11/2021 3.1 Arrays 15
Reversing with a Single Array
2/11/2021 3.1 Arrays 16
SORTING AN ARRAY (SELECTION)
2/11/2021 3.1 Arrays 17
2/11/2021 3.1 Arrays 18
PROGRAM TO SEQUENTIALLY SEARCH AN ARRAY
2/11/2021 3.1 Arrays 19
2/11/2021 3.1 Arrays 20
2/11/2021 3.1 Arrays 21
2/11/2021 3.1 Arrays 22
2/11/2021 3.1 Arrays 23
TWO-DIMENSIONAL (2D) ARRAYS
• A two-dimensional array needs two subscripts
and a three-dimensional array needs three
subscripts.
• Like a single-dimensional array, a multi-
dimensional array occupies a contiguous region
of memory.
• A two-dimensional (2D) array, arr, takes the form
arr[i][j],
– where the subscript i represents the number of rows
and
– j represents the number of columns.
2/11/2021 3.1 Arrays 24
• Internally though, a 2D array can be viewed as
an array of single-dimensional arrays.
• This means that table represents a set of
three single-dimensional arrays of four
elements each.
• Alternatively, it can be considered as three
rows having four columns in each row.
2/11/2021 3.1 Arrays 25
2/11/2021 3.1 Arrays 26
Full Initialization During Declaration
2/11/2021 3.1 Arrays 27
Partial Initialization During Declaration
2/11/2021 3.1 Arrays 28
2/11/2021 3.1 Arrays 29
MULTI-DIMENSIONAL ARRAYS
• Multi-dimensional arrays in C can go beyond two
dimensions.
• Every increase in dimension increases he number of
subscripts by one, with the subscript on the right changing
faster than the one on the left.
• A three-dimensional (3D) array can be treated as an array
of arrays of arrays.
• In this case, only those elements accessed with the right-
most subscript—with the other subscripts remaining
unchanged—occupy consecutive memory cells.
• visualization of an array becomes difficult when the
number of dimensions exceeds three.
2/11/2021 3.1 Arrays 30
2/11/2021 3.1 Arrays 31
USING ARRAYS AS MATRICES
2/11/2021 3.1 Arrays 32
Transposing a Matrix
2/11/2021 3.1 Arrays 33
Adding and Subtracting Two Matrices
2/11/2021 3.1 Arrays 34
2/11/2021 3.1 Arrays 35
Multiplying Two Matrices
2/11/2021 3.1 Arrays 36
2/11/2021 3.1 Arrays 37
Thank you
2/11/2021 3.1 Arrays 38
C Programming : Functions
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Contents
1. Arrays
– Declaring and initializing 1D array
– Two dimensional arrays
– Multidimensional arrays
2. Functions
– Basics, The anatomy of a function
– Types of functions based on arguments and return types
– Passing 1D and 2D arrays as arguments to functions
– Calling function from another function
3. Recursive functions
4. Variable scope and lifetime
5. Storage classes.
2/11/2021 40
3.2 Functions
Introduction
• C programmers decompose a complex task into
independent and manageable modules called
functions.
• A function is a statement that represents a named
body of program code.
• When it is called or invoked, the code associated with
the function is executed.
• A function can optionally
– (i) accept one or more values as arguments, and
– (ii) report the outcome of its action by returning a single
value to the caller.
• A function is called mainly in one of these two ways:
2/11/2021 3.2 Functions 41
Introduction
• A function is easily identified from the matched
pair of parentheses that follow its name.
• A function must be declared and defined before
it is called or invoked.
• The declaration specifies how to invoke the
function correctly.
• The definition provides the implementation, i.e. ,
the body of code that will be executed on
invocation
2/11/2021 3.2 Functions 42
Introduction
• The functions you create can also call other
functions.
• A function can even call itself, a property that
has important applications in the programming
world (like calculating the factorial of a number).
• For all of the functions we have used so far, we
had main as the caller.
• This is a special function that every standalone C
program must have because a program
commences execution by calling main.
2/11/2021 3.2 Functions 43
NO ARGUMENTS, NO RETURN VALUE
2/11/2021 3.2 Functions 44
2/11/2021 3.2 Functions 45
• The return; statement in the function has the same
significance as the one we have all along used in main.
• It terminates the function and returns control to the caller.
• However, this function doesn’t return a value (return; and
not return 0;).
• Even though a return here is not necessary, it’s good
programming practice to include it in every function even
though it may return nothing.
2/11/2021 3.2 Functions 46
THE ANATOMY OF A FUNCTION
• Main attributes of functions:
– Declaration
– definition and
– invocation
2/11/2021 3.2 Functions 47
Declaration, Prototype or Signature of Function
• A declaration is an authentic statement that tells the
compiler how the function is invoked.
• The declaration is also known as prototype or signature.
• Since it is placed before main, the compiler sees it first and
then compares it to the invocation and definition.
• For this comparison, the compiler determines whether the
function
– uses any arguments, and if so, the number of such arguments
along with their data types.
– returns a value, and if so, its data type.
• This creates four possible situations—
– with or without arguments, and
– with or without return value.
2/11/2021 3.2 Functions 48
Declaration, Prototype or Signature of Function
• The first void indicates that the function doesn’t
return a value.
• The second void signifies that the function uses no
arguments.
• An argument can be a variable, constant or expression
2/11/2021 3.2 Functions 49
• The area function accepts two arguments each of type
float and returns a value of type double.
• Since the compiler simply matches the type and
number of arguments in the declaration with those
used in the definition.
• It doesn’t need to know these variable names, and C
lets you omit them.
2/11/2021 3.2 Functions 50
Definition or Implementation
• The function definition or implementation specifies what the
function does when invoked.
• It comprises a header and a body where all the work gets done.
• For a function that accepts arguments and returns a value.
2/11/2021 3.2 Functions 51
• The header (the first line) is virtually identical to the declaration
except that there’s no semicolon as terminator.
• The body is represented by a simple or compound statement that is
compulsorily enclosed within curly braces.
• The return statement transmits the value of expression back to the
caller.
2/11/2021 3.2 Functions 52
Invocation or Call
• The programmer must invoke the function in
a way that enables the program to “see” the
value.
• Typically, the return value is saved in a
variable or used as an argument to another
function.
2/11/2021 3.2 Functions 53
Types of functions based on arguments and
return types
1. Function Without Return Values and Without Arguments.
2. Function Without Return Values and With Arguments.
3. Function With Return Values and Without Arguments.
4. Function With Return Values and With Arguments.
2/11/2021 3.2 Functions 54
Function Without Return Values and Without Arguments.
2/11/2021 3.2 Functions 55
Function Without Return Values and With Arguments.
2/11/2021 3.2 Functions 56
Function With Return Values and Without Arguments.
2/11/2021 3.2 Functions 57
Function With Return Values and With Arguments.
2/11/2021 3.2 Functions 58
Parameter Passing: Arguments and Parameters
• To understand the concept of parameter passing, we need to look
at function arguments from two viewpoints—the caller and called
function.
• When the caller (here, main) invokes a function, it assigns values to
the arguments or actual arguments of the function.
• The called function accepts these values into its parameters or
formal arguments.
• When we invoke c2f as shown above, the value of celsius (the
argument) is assigned to f_celsius (the parameter).
• This transfer of value from argument to parameter is known as
parameter passing.
• argument means the “actual argument” and parameter means the
“formal argument” to a function.
2/11/2021 3.2 Functions 59
2/11/2021 3.2 Functions 60
Passing by Value
• The question is whether arguments are passed by value or
by reference, or whether there is a mix of both.
• In C, all function arguments are passed by value, i.e., they
are copied to their corresponding parameters.
• For Example,
– When c2f is called, the value of celsius is copied to f_celsius.
– Since a parameter resides in its own memory space, celsius and
f_celsius occupy separate memory locations.
– You can’t subsequently change celsius by changing f_celsius,
i.e., you can’t change an argument by changing its copy, the
parameter.
• It is thus not necessary to maintain separate names for
arguments and parameters in the declaration, definition
and invocation
2/11/2021 3.2 Functions 61
Passing by Reference
• Unlike C++, C doesn’t support passing by reference, where
both argument and parameter occupy the same memory
location.
• However, in C, a variable (p) can store the memory address
of another variable (x), and you can use p to indirectly
change the value of x.
• When a function is called, its arguments are copied to the
parameters.
• But if the function changes a parameter, then the change
is not seen in the caller.
• However, if an argument contains the address of a
variable, then the corresponding parameter of the
argument can be used to change that variable.
2/11/2021 3.2 Functions 62
Local Variables
• A function has its own set of local variables that are defined in its
implementation.
• For instance, the c2f function uses a local variable, fheit, to compute the
result it returns to its caller.
• Unlike parameters, local variables cannot be assigned by the caller.
• parameters and local variables have the following features:
– Their names don’t conflict with identical names defined in the caller or any
other function.
– They can be accessed only in the function they are defined in.
– They are neither visible in the caller nor in any other function.
– They last as long as the function is active. This means that they are created
every time the function is called.
• since main is the first function to be called and the last to terminate, its
variables have a longer lifetime compared to variables and parameters of
other functions.
• To reinforce our point, usage of identical variable names (Ex: x, y and
temp) in both calling and called function will create a problem.
2/11/2021 3.2 Functions 63
The “Problem” with Local Variables
2/11/2021 3.2 Functions 64
2/11/2021 3.2 Functions 65
USING ARRAYS IN FUNCTIONS
• Functions also use arrays as arguments.
• You can pass both an individual array element
and the name of an array as argument to a
function.
• The principles of parameter passing apply to
arrays too, but they affect array elements and
entire arrays in opposite ways.
2/11/2021 3.2 Functions 66
Passing an Array as an Argument
2/11/2021 3.2 Functions 67
PASSING A TWO-DIMENSIONAL ARRAY AS ARGUMENT
• A function can also work with the name of a 2D array as an
argument.
• Like with a 1D array, a 2D array is specified differently in the
declaration (and definition) and invocation.
• In the former case, you may drop the first subscript (rows),
but you can’t drop the second subscript (columns).
• Without knowledge of the number of columns, it would be
impossible for the compiler to know when one row ends
and another begins, considering that the rows are placed
next to one another in memory.
2/11/2021 3.2 Functions 68
CALLING A FUNCTION FROM ANOTHER FUNCTION
• Just as main calls a function, a function can
also call another function.
• The called function can in turn call another
function, an
• The remaining functions then return in the
reverse sequence of their invocation.
• Ultimately, the outermost function returns
control to main.
2/11/2021 3.2 Functions 69
2/11/2021 3.2 Functions 70
2/11/2021 3.2 Functions 71
Contents
1. Arrays
– Declaring and initializing 1D array
– Two dimensional arrays
– Multidimensional arrays
2. Functions
– Basics, The anatomy of a function
– Types of functions based on arguments and return types
– Passing 1D and 2D arrays as arguments to functions
– Calling function from another function
3. Recursive functions
4. Variable scope and lifetime
5. Storage classes.
2/11/2021 72
3.2 Functions
RECURSIVE FUNCTIONS
• Loops use the iterative technique to repeatedly update
a set of data with the same set of instructions.
• Repetition can also be achieved by recursion, a form of
cloning that uses instructions to specify themselves.
• In C, a recursive function calls itself, which on return
delivers to its caller its share of the final solution.
• A recursive function must not be allowed to run
forever because the program will eventually run out of
memory.
2/11/2021 3.2 Functions 73
2/11/2021 3.2 Functions 74
RECURSIVE FUNCTIONS
• Because the static variable count is defined and
initialized just once, it can track the number of calls
made to main.
• You are aware that function variables and parameters
are saved in a separate region of memory called the
stack.
• With every recursive call, the stack grows in size, and if
this growth goes unchecked, the stack will eventually
overflow.
• In this program, after main has called itself 523,172
times, stack overflow occurs and terminates the
program with a “segmentation fault.”
• This is not the way recursive functions are meant to
be used.
2/11/2021 3.2 Functions 75
Using a Recursive Function to Compute Factorial
• This is simply the product of all integers from 1 to
the number.
• For instance, 6!, the factorial of 6, is 6 × 5 × 4 × 3
× 2 × 1 = 720.
• But 6! can also be expressed as 6 × 5! in the same
way as 5! is expressed as 5 × 4!.
• We can thus express the factorial of a number in
this manner:
2/11/2021 3.2 Functions 76
2/11/2021 3.2 Functions 77
VARIABLE SCOPE AND LIFETIME
• Apart from having a data type, a variable has space and time
attributes.
• The space attribute signifies the scope or visibility of the variable.
This is actually the region of the program where the variable is
visible and can be accessed.
• A variable may have one of four possible scopes: block, function,
file and program.
– A variable having block scope is visible in the block in which it is
declared.
– A variable having file scope is visible in the entire file.
• The time attribute determines the lifetime of the variable, i.e., its
time of birth and death.
• A variable declared inside a function lives as long as the function is
active. One declared before main is alive for the duration of the
program.
2/11/2021 3.2 Functions 78
Local and Global Variables
• Variables declared inside a function are visible
only in the function. They have local scope, the
reason why they are called local variables.
• Variables declared outside a function are known
as global variables. The scope of a global variable
extends from the point of its declaration to the
rest of the file.
• When a variable is declared before main, it is
truly global across the entire program (which
may be spread across multiple files).
2/11/2021 3.2 Functions 79
Scope of Global and Local Variables
2/11/2021 3.2 Functions 80
Variable Hiding
2/11/2021 3.2 Functions 81
THE STORAGE CLASSES
• The scope, lifetime and initial value of a variable
are determined by its storage class.
• So far, we have used the default storage class for
variables (automatic), but you also need to know
the following storage classes supported by C:
– automatic (auto)
– static (static)
– external (extern)
– register (register)
• The storage class also determines the way the
compiler allocates memory for a variable.
2/11/2021 3.2 Functions 82
2/11/2021 3.2 Functions 83
Static Variables (static)
• If a local variable is assigned the static storage
class, then it will retain its value between
function calls.
• A static variable (keyword: static) is created
and initialized just once, when the function
containing its declaration is executed.
2/11/2021 3.2 Functions 84
External Variables (extern)
• A global or external variable is defined outside a
function and is visible everywhere—even in other files
that constitute the program.
2/11/2021 3.2 Functions 85
Register Variables (register)
• All program variables are stored in primary memory which is faster
than disk but slower then registers directly connected to the CPU.
• The register storage class (keyword: register) permits a variable to
be stored in one of the high-speed CPU registers.
• The compiler will attempt to store the variable x in one of the
registers, failing which it will use primary memory.
• A register normally has a size of one word, not all variables can be
assigned this storage class.
• Generally, register is restricted to char and int variables.
• However, you can’t obtain the address of a register variable using
&x because registers don’t use the addressing system used by
primary memory.
2/11/2021 3.2 Functions 86
Thank you
2/11/2021 3.2 Functions 87
C Programming : Recursive Functions,
Variable Scope and Lifetime and
Storage Classes
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Contents
1. Arrays
– Declaring and initializing 1D array
– Two dimensional arrays
– Multidimensional arrays
2. Functions
– Basics, The anatomy of a function
– Types of functions based on arguments and return types
– Passing 1D and 2D arrays as arguments to functions
– Calling function from another function
3. Recursive functions
4. Variable scope and lifetime
5. Storage classes.
2/11/2021 89
3.3 Recursive Functions
RECURSIVE FUNCTIONS
• Loops use the iterative technique to repeatedly update
a set of data with the same set of instructions.
• Repetition can also be achieved by recursion, a form of
cloning that uses instructions to specify themselves.
• In C, a recursive function calls itself, which on return
delivers to its caller its share of the final solution.
• A recursive function must not be allowed to run
forever because the program will eventually run out of
memory.
2/11/2021 3.3 Recursive Functions 90
2/11/2021 3.3 Recursive Functions 91
RECURSIVE FUNCTIONS
• Because the static variable count is defined and
initialized just once, it can track the number of calls
made to main.
• You are aware that function variables and parameters
are saved in a separate region of memory called the
stack.
• With every recursive call, the stack grows in size, and if
this growth goes unchecked, the stack will eventually
overflow.
• In this program, after main has called itself 523,172
times, stack overflow occurs and terminates the
program with a “segmentation fault.”
• This is not the way recursive functions are meant to
be used.
2/11/2021 3.3 Recursive Functions 92
Using a Recursive Function to Compute Factorial
• This is simply the product of all integers from 1 to
the number.
• For instance, 6!, the factorial of 6, is 6 × 5 × 4 × 3
× 2 × 1 = 720.
• But 6! can also be expressed as 6 × 5! in the same
way as 5! is expressed as 5 × 4!.
• We can thus express the factorial of a number in
this manner:
2/11/2021 3.3 Recursive Functions 93
2/11/2021 3.3 Recursive Functions 94
VARIABLE SCOPE AND LIFETIME
• Apart from having a data type, a variable has space and time
attributes.
• The space attribute signifies the scope or visibility of the variable.
This is actually the region of the program where the variable is
visible and can be accessed.
• A variable may have one of four possible scopes: block, function,
file and program.
– A variable having block scope is visible in the block in which it is
declared.
– A variable having file scope is visible in the entire file.
• The time attribute determines the lifetime of the variable, i.e., its
time of birth and death.
• A variable declared inside a function lives as long as the function is
active. One declared before main is alive for the duration of the
program.
2/11/2021 3.3 Recursive Functions 95
Local and Global Variables
• Variables declared inside a function are visible
only in the function. They have local scope, the
reason why they are called local variables.
• Variables declared outside a function are known
as global variables. The scope of a global variable
extends from the point of its declaration to the
rest of the file.
• When a variable is declared before main, it is
truly global across the entire program (which
may be spread across multiple files).
2/11/2021 3.3 Recursive Functions 96
Scope of Global and Local Variables
2/11/2021 3.3 Recursive Functions 97
Variable Hiding
2/11/2021 3.3 Recursive Functions 98
THE STORAGE CLASSES
• The scope, lifetime and initial value of a variable
are determined by its storage class.
• So far, we have used the default storage class for
variables (automatic), but you also need to know
the following storage classes supported by C:
– automatic (auto)
– static (static)
– external (extern)
– register (register)
• The storage class also determines the way the
compiler allocates memory for a variable.
2/11/2021 3.3 Recursive Functions 99
2/11/2021 3.3 Recursive Functions 100
Static Variables (static)
• If a local variable is assigned the static storage
class, then it will retain its value between
function calls.
• A static variable (keyword: static) is created
and initialized just once, when the function
containing its declaration is executed.
2/11/2021 3.3 Recursive Functions 101
External Variables (extern)
• A global or external variable is defined outside a
function and is visible everywhere—even in other files
that constitute the program.
2/11/2021 3.3 Recursive Functions 102
Register Variables (register)
• All program variables are stored in primary memory which is faster
than disk but slower then registers directly connected to the CPU.
• The register storage class (keyword: register) permits a variable to
be stored in one of the high-speed CPU registers.
• The compiler will attempt to store the variable x in one of the
registers, failing which it will use primary memory.
• A register normally has a size of one word, not all variables can be
assigned this storage class.
• Generally, register is restricted to char and int variables.
• However, you can’t obtain the address of a register variable using
&x because registers don’t use the addressing system used by
primary memory.
2/11/2021 3.3 Recursive Functions 103
Thank you
2/11/2021 3.3 Recursive Functions 104

More Related Content

PPTX
Inheritance in java
PPTX
Polymorphism and its types
PPTX
Polymorphism Using C++
PPTX
Circular link list.ppt
PPSX
Data Types & Variables in JAVA
PPTX
Loops in C# for loops while and do while loop.
PPTX
Classes and objects1
PPT
Structure in c
Inheritance in java
Polymorphism and its types
Polymorphism Using C++
Circular link list.ppt
Data Types & Variables in JAVA
Loops in C# for loops while and do while loop.
Classes and objects1
Structure in c

What's hot (20)

PPTX
classes and objects in C++
PDF
C++ OOPS Concept
PDF
Breadth First Search Algorithm In 10 Minutes | Artificial Intelligence Tutori...
PDF
Module 05 Preprocessor and Macros in C
PPT
Data abstraction and object orientation
PPTX
C vs c++
PPTX
Java abstract class & abstract methods
PPTX
Constructor overloading & method overloading
PPTX
C functions by ranjan call by value and reference.pptx
PDF
Operator overloading C++
PPT
Event+driven+programming key+features
PPTX
JAVA FEATURES
PPTX
Member Function in C++
PPTX
Double Linked List (Algorithm)
PPTX
Functions in c++
PPTX
Searching and sorting
PDF
Object oriented concepts ppt
PPTX
linked list in data structure
PPT
Elementary data organisation
PDF
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
classes and objects in C++
C++ OOPS Concept
Breadth First Search Algorithm In 10 Minutes | Artificial Intelligence Tutori...
Module 05 Preprocessor and Macros in C
Data abstraction and object orientation
C vs c++
Java abstract class & abstract methods
Constructor overloading & method overloading
C functions by ranjan call by value and reference.pptx
Operator overloading C++
Event+driven+programming key+features
JAVA FEATURES
Member Function in C++
Double Linked List (Algorithm)
Functions in c++
Searching and sorting
Object oriented concepts ppt
linked list in data structure
Elementary data organisation
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
Ad

Similar to C Programming : Arrays and Functions (20)

PPTX
C concepts and programming examples for beginners
PPS
C programming session 04
PPTX
Arrays & Strings
PPTX
C language 3
PPTX
PPTX
Unit 3
DOCX
C UNIT-3 PREPARED BY M V B REDDY
PPTX
Array and its operation in C programming
PDF
Arrays In C
PPTX
Arrays 1D and 2D , and multi dimensional
PPTX
Module 4- Arrays and Strings
PDF
Programming Fundamentals Arrays and Strings
PPTX
Ch8 Arrays
PPTX
Unit 3
PPS
C programming session 05
PDF
Array and its types and it's implemented programming Final.pdf
PPTX
Array.pptx Array.pptxArray.pptx Array.pptxArray.pptxArray.pptx
PDF
Arrays In C- Logic Development Programming
PPTX
Programming in c Arrays
C concepts and programming examples for beginners
C programming session 04
Arrays & Strings
C language 3
Unit 3
C UNIT-3 PREPARED BY M V B REDDY
Array and its operation in C programming
Arrays In C
Arrays 1D and 2D , and multi dimensional
Module 4- Arrays and Strings
Programming Fundamentals Arrays and Strings
Ch8 Arrays
Unit 3
C programming session 05
Array and its types and it's implemented programming Final.pdf
Array.pptx Array.pptxArray.pptx Array.pptxArray.pptxArray.pptx
Arrays In C- Logic Development Programming
Programming in c Arrays
Ad

More from Selvaraj Seerangan (20)

PDF
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
PDF
Unit 5 _ Fog Computing .pdf
PDF
CAT III Answer Key.pdf
PPTX
END SEM _ Design Thinking _ 16 Templates.pptx
PPTX
Design Thinking _ Complete Templates.pptx
PPTX
CAT 3 _ List of Templates.pptx
PPTX
[PPT] _ Unit 5 _ Evolve.pptx
PPTX
[PPT] _ Unit 4 _ Engage.pptx
PPTX
[PPT] _ Unit 3 _ Experiment.pptx
PPTX
CAT 2 _ List of Templates.pptx
PPTX
Design Thinking - Empathize Phase
PDF
CAT-II Answer Key.pdf
PDF
PSP LAB MANUAL.pdf
PDF
18CSL51 - Network Lab Manual.pdf
PDF
DS LAB MANUAL.pdf
PPTX
CAT 1 _ List of Templates.pptx
PPTX
[PPT] _ UNIT 1 _ COMPLETE.pptx
DOC
CAT-1 Answer Key.doc
PPTX
Unit 3 Complete.pptx
PDF
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 5 _ Fog Computing .pdf
CAT III Answer Key.pdf
END SEM _ Design Thinking _ 16 Templates.pptx
Design Thinking _ Complete Templates.pptx
CAT 3 _ List of Templates.pptx
[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 3 _ Experiment.pptx
CAT 2 _ List of Templates.pptx
Design Thinking - Empathize Phase
CAT-II Answer Key.pdf
PSP LAB MANUAL.pdf
18CSL51 - Network Lab Manual.pdf
DS LAB MANUAL.pdf
CAT 1 _ List of Templates.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx
CAT-1 Answer Key.doc
Unit 3 Complete.pptx
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf

Recently uploaded (20)

PDF
Insiders guide to clinical Medicine.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Pre independence Education in Inndia.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
master seminar digital applications in india
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Lesson notes of climatology university.
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
Insiders guide to clinical Medicine.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
01-Introduction-to-Information-Management.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Pre independence Education in Inndia.pdf
Sports Quiz easy sports quiz sports quiz
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
TR - Agricultural Crops Production NC III.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Supply Chain Operations Speaking Notes -ICLT Program
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
master seminar digital applications in india
Complications of Minimal Access Surgery at WLH
Lesson notes of climatology university.
Final Presentation General Medicine 03-08-2024.pptx
Anesthesia in Laparoscopic Surgery in India
STATICS OF THE RIGID BODIES Hibbelers.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Microbial disease of the cardiovascular and lymphatic systems

C Programming : Arrays and Functions

  • 1. C Programming : Arrays and Functions By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India
  • 2. 20CST11 – Problem Solving and Programming 2/11/2021 3.1 Arrays 2 Syllabus
  • 3. Contents 1. Arrays – Declaring and initializing 1D array – Two dimensional arrays – Multidimensional arrays 2. Functions – Basics, The anatomy of a function – Types of functions based on arguments and return types – Passing 1D and 2D arrays as arguments to functions – Calling function from another function 3. Recursive functions 4. Variable scope and lifetime 5. Storage classes. 2/11/2021 3 3.1 Arrays
  • 4. Introduction • Variables can’t handle voluminous data because a hundred data items need a hundred variables to store them. • The solution is to use an array, which is an ordered set of data items stored contiguously in memory. • Each data item represents an element of the array and is accessed with an index or subscript. • For instance, the elements of an array named signal are accessed as signal[0], signal[1], signal[2], and so forth. • The first subscript is 0 and the last subscript is one less than the size of the array. 2/11/2021 3.1 Arrays 4
  • 5. Introduction • The elements of an array have a common data type (like int, char, etc.). • An array must be declared with its type and size to enable the compiler to allocate a contiguous chunk of memory for all array elements. 2/11/2021 3.1 Arrays 5
  • 6. Introduction • The first element is accessed as signal[0] and the last element is signal[31] (not 32). • The subscript is either zero, a positive integer or an expression that evaluates to an integer value. • An array element can be assigned to a variable – (say, int x = signal[2];), – which means we can use signal[2] wherever we use x. • By the same logic, &signal[2] is also a valid scanf argument like &x. • It is easy to cycle through all array elements by using the array subscript as a key variable in a loop. 2/11/2021 3.1 Arrays 6
  • 7. Introduction • C doesn’t offer bounds checking for arrays, i.e. it doesn’t validate the index used to access an array element. • For instance, the compiler will not generate an error if you attempt to access signal[35] even though the array has 32 elements. • A negative index (as in signal[-5]) doesn’t generate an error either. • C also supports multi-dimensional arrays where an element is handled with multiple subscripts. • Since there is virtually no limit to the number of indexes and dimensions an array can have. • arrays in C are very powerful data structures that can easily gobble up a lot of memory. 2/11/2021 3.1 Arrays 7
  • 8. DECLARING AND INITIALIZING AN ARRAY • The declaration of an array specifies its name, type and size, which is normally specified as a constant or symbolic constant. • The following statement declares a single-dimensional array named signal having 32 elements, each of type int. • The sizeof operator, when used on an array, returns the total usage of all elements, so the below definition allocates 32 × sizeof(int) bytes of memory—typically, 128 bytes. 2/11/2021 3.1 Arrays 8
  • 9. Layout in Memory of the Array • months[12] and MONTHS[12] are two separate arrays. 2/11/2021 3.1 Arrays 9
  • 10. Initializing During Declaration • In the first declaration, the number of values matches the size of the array. • The second declaration performs a partial initialization by assigning values to the first three elements only. When that happens, the remaining values are automatically initialized to zeroes (NUL for an array of type char). • The third declaration uses an empty pair of brackets ([ ]) to implicitly specify the size of the array. 2/11/2021 3.1 Arrays 10
  • 11. INITIALIZING AND PRINTING ARRAYS 2/11/2021 3.1 Arrays 11
  • 13. Inserting an Element in an Array 2/11/2021 3.1 Arrays 13
  • 14. Deleting an Element from an Array 2/11/2021 3.1 Arrays 14
  • 15. Reversing with Two Arrays 2/11/2021 3.1 Arrays 15
  • 16. Reversing with a Single Array 2/11/2021 3.1 Arrays 16
  • 17. SORTING AN ARRAY (SELECTION) 2/11/2021 3.1 Arrays 17
  • 19. PROGRAM TO SEQUENTIALLY SEARCH AN ARRAY 2/11/2021 3.1 Arrays 19
  • 24. TWO-DIMENSIONAL (2D) ARRAYS • A two-dimensional array needs two subscripts and a three-dimensional array needs three subscripts. • Like a single-dimensional array, a multi- dimensional array occupies a contiguous region of memory. • A two-dimensional (2D) array, arr, takes the form arr[i][j], – where the subscript i represents the number of rows and – j represents the number of columns. 2/11/2021 3.1 Arrays 24
  • 25. • Internally though, a 2D array can be viewed as an array of single-dimensional arrays. • This means that table represents a set of three single-dimensional arrays of four elements each. • Alternatively, it can be considered as three rows having four columns in each row. 2/11/2021 3.1 Arrays 25
  • 27. Full Initialization During Declaration 2/11/2021 3.1 Arrays 27
  • 28. Partial Initialization During Declaration 2/11/2021 3.1 Arrays 28
  • 30. MULTI-DIMENSIONAL ARRAYS • Multi-dimensional arrays in C can go beyond two dimensions. • Every increase in dimension increases he number of subscripts by one, with the subscript on the right changing faster than the one on the left. • A three-dimensional (3D) array can be treated as an array of arrays of arrays. • In this case, only those elements accessed with the right- most subscript—with the other subscripts remaining unchanged—occupy consecutive memory cells. • visualization of an array becomes difficult when the number of dimensions exceeds three. 2/11/2021 3.1 Arrays 30
  • 32. USING ARRAYS AS MATRICES 2/11/2021 3.1 Arrays 32
  • 34. Adding and Subtracting Two Matrices 2/11/2021 3.1 Arrays 34
  • 39. C Programming : Functions By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India
  • 40. Contents 1. Arrays – Declaring and initializing 1D array – Two dimensional arrays – Multidimensional arrays 2. Functions – Basics, The anatomy of a function – Types of functions based on arguments and return types – Passing 1D and 2D arrays as arguments to functions – Calling function from another function 3. Recursive functions 4. Variable scope and lifetime 5. Storage classes. 2/11/2021 40 3.2 Functions
  • 41. Introduction • C programmers decompose a complex task into independent and manageable modules called functions. • A function is a statement that represents a named body of program code. • When it is called or invoked, the code associated with the function is executed. • A function can optionally – (i) accept one or more values as arguments, and – (ii) report the outcome of its action by returning a single value to the caller. • A function is called mainly in one of these two ways: 2/11/2021 3.2 Functions 41
  • 42. Introduction • A function is easily identified from the matched pair of parentheses that follow its name. • A function must be declared and defined before it is called or invoked. • The declaration specifies how to invoke the function correctly. • The definition provides the implementation, i.e. , the body of code that will be executed on invocation 2/11/2021 3.2 Functions 42
  • 43. Introduction • The functions you create can also call other functions. • A function can even call itself, a property that has important applications in the programming world (like calculating the factorial of a number). • For all of the functions we have used so far, we had main as the caller. • This is a special function that every standalone C program must have because a program commences execution by calling main. 2/11/2021 3.2 Functions 43
  • 44. NO ARGUMENTS, NO RETURN VALUE 2/11/2021 3.2 Functions 44
  • 46. • The return; statement in the function has the same significance as the one we have all along used in main. • It terminates the function and returns control to the caller. • However, this function doesn’t return a value (return; and not return 0;). • Even though a return here is not necessary, it’s good programming practice to include it in every function even though it may return nothing. 2/11/2021 3.2 Functions 46
  • 47. THE ANATOMY OF A FUNCTION • Main attributes of functions: – Declaration – definition and – invocation 2/11/2021 3.2 Functions 47
  • 48. Declaration, Prototype or Signature of Function • A declaration is an authentic statement that tells the compiler how the function is invoked. • The declaration is also known as prototype or signature. • Since it is placed before main, the compiler sees it first and then compares it to the invocation and definition. • For this comparison, the compiler determines whether the function – uses any arguments, and if so, the number of such arguments along with their data types. – returns a value, and if so, its data type. • This creates four possible situations— – with or without arguments, and – with or without return value. 2/11/2021 3.2 Functions 48
  • 49. Declaration, Prototype or Signature of Function • The first void indicates that the function doesn’t return a value. • The second void signifies that the function uses no arguments. • An argument can be a variable, constant or expression 2/11/2021 3.2 Functions 49
  • 50. • The area function accepts two arguments each of type float and returns a value of type double. • Since the compiler simply matches the type and number of arguments in the declaration with those used in the definition. • It doesn’t need to know these variable names, and C lets you omit them. 2/11/2021 3.2 Functions 50
  • 51. Definition or Implementation • The function definition or implementation specifies what the function does when invoked. • It comprises a header and a body where all the work gets done. • For a function that accepts arguments and returns a value. 2/11/2021 3.2 Functions 51 • The header (the first line) is virtually identical to the declaration except that there’s no semicolon as terminator. • The body is represented by a simple or compound statement that is compulsorily enclosed within curly braces. • The return statement transmits the value of expression back to the caller.
  • 53. Invocation or Call • The programmer must invoke the function in a way that enables the program to “see” the value. • Typically, the return value is saved in a variable or used as an argument to another function. 2/11/2021 3.2 Functions 53
  • 54. Types of functions based on arguments and return types 1. Function Without Return Values and Without Arguments. 2. Function Without Return Values and With Arguments. 3. Function With Return Values and Without Arguments. 4. Function With Return Values and With Arguments. 2/11/2021 3.2 Functions 54
  • 55. Function Without Return Values and Without Arguments. 2/11/2021 3.2 Functions 55
  • 56. Function Without Return Values and With Arguments. 2/11/2021 3.2 Functions 56
  • 57. Function With Return Values and Without Arguments. 2/11/2021 3.2 Functions 57
  • 58. Function With Return Values and With Arguments. 2/11/2021 3.2 Functions 58
  • 59. Parameter Passing: Arguments and Parameters • To understand the concept of parameter passing, we need to look at function arguments from two viewpoints—the caller and called function. • When the caller (here, main) invokes a function, it assigns values to the arguments or actual arguments of the function. • The called function accepts these values into its parameters or formal arguments. • When we invoke c2f as shown above, the value of celsius (the argument) is assigned to f_celsius (the parameter). • This transfer of value from argument to parameter is known as parameter passing. • argument means the “actual argument” and parameter means the “formal argument” to a function. 2/11/2021 3.2 Functions 59
  • 61. Passing by Value • The question is whether arguments are passed by value or by reference, or whether there is a mix of both. • In C, all function arguments are passed by value, i.e., they are copied to their corresponding parameters. • For Example, – When c2f is called, the value of celsius is copied to f_celsius. – Since a parameter resides in its own memory space, celsius and f_celsius occupy separate memory locations. – You can’t subsequently change celsius by changing f_celsius, i.e., you can’t change an argument by changing its copy, the parameter. • It is thus not necessary to maintain separate names for arguments and parameters in the declaration, definition and invocation 2/11/2021 3.2 Functions 61
  • 62. Passing by Reference • Unlike C++, C doesn’t support passing by reference, where both argument and parameter occupy the same memory location. • However, in C, a variable (p) can store the memory address of another variable (x), and you can use p to indirectly change the value of x. • When a function is called, its arguments are copied to the parameters. • But if the function changes a parameter, then the change is not seen in the caller. • However, if an argument contains the address of a variable, then the corresponding parameter of the argument can be used to change that variable. 2/11/2021 3.2 Functions 62
  • 63. Local Variables • A function has its own set of local variables that are defined in its implementation. • For instance, the c2f function uses a local variable, fheit, to compute the result it returns to its caller. • Unlike parameters, local variables cannot be assigned by the caller. • parameters and local variables have the following features: – Their names don’t conflict with identical names defined in the caller or any other function. – They can be accessed only in the function they are defined in. – They are neither visible in the caller nor in any other function. – They last as long as the function is active. This means that they are created every time the function is called. • since main is the first function to be called and the last to terminate, its variables have a longer lifetime compared to variables and parameters of other functions. • To reinforce our point, usage of identical variable names (Ex: x, y and temp) in both calling and called function will create a problem. 2/11/2021 3.2 Functions 63
  • 64. The “Problem” with Local Variables 2/11/2021 3.2 Functions 64
  • 66. USING ARRAYS IN FUNCTIONS • Functions also use arrays as arguments. • You can pass both an individual array element and the name of an array as argument to a function. • The principles of parameter passing apply to arrays too, but they affect array elements and entire arrays in opposite ways. 2/11/2021 3.2 Functions 66
  • 67. Passing an Array as an Argument 2/11/2021 3.2 Functions 67
  • 68. PASSING A TWO-DIMENSIONAL ARRAY AS ARGUMENT • A function can also work with the name of a 2D array as an argument. • Like with a 1D array, a 2D array is specified differently in the declaration (and definition) and invocation. • In the former case, you may drop the first subscript (rows), but you can’t drop the second subscript (columns). • Without knowledge of the number of columns, it would be impossible for the compiler to know when one row ends and another begins, considering that the rows are placed next to one another in memory. 2/11/2021 3.2 Functions 68
  • 69. CALLING A FUNCTION FROM ANOTHER FUNCTION • Just as main calls a function, a function can also call another function. • The called function can in turn call another function, an • The remaining functions then return in the reverse sequence of their invocation. • Ultimately, the outermost function returns control to main. 2/11/2021 3.2 Functions 69
  • 72. Contents 1. Arrays – Declaring and initializing 1D array – Two dimensional arrays – Multidimensional arrays 2. Functions – Basics, The anatomy of a function – Types of functions based on arguments and return types – Passing 1D and 2D arrays as arguments to functions – Calling function from another function 3. Recursive functions 4. Variable scope and lifetime 5. Storage classes. 2/11/2021 72 3.2 Functions
  • 73. RECURSIVE FUNCTIONS • Loops use the iterative technique to repeatedly update a set of data with the same set of instructions. • Repetition can also be achieved by recursion, a form of cloning that uses instructions to specify themselves. • In C, a recursive function calls itself, which on return delivers to its caller its share of the final solution. • A recursive function must not be allowed to run forever because the program will eventually run out of memory. 2/11/2021 3.2 Functions 73
  • 75. RECURSIVE FUNCTIONS • Because the static variable count is defined and initialized just once, it can track the number of calls made to main. • You are aware that function variables and parameters are saved in a separate region of memory called the stack. • With every recursive call, the stack grows in size, and if this growth goes unchecked, the stack will eventually overflow. • In this program, after main has called itself 523,172 times, stack overflow occurs and terminates the program with a “segmentation fault.” • This is not the way recursive functions are meant to be used. 2/11/2021 3.2 Functions 75
  • 76. Using a Recursive Function to Compute Factorial • This is simply the product of all integers from 1 to the number. • For instance, 6!, the factorial of 6, is 6 × 5 × 4 × 3 × 2 × 1 = 720. • But 6! can also be expressed as 6 × 5! in the same way as 5! is expressed as 5 × 4!. • We can thus express the factorial of a number in this manner: 2/11/2021 3.2 Functions 76
  • 78. VARIABLE SCOPE AND LIFETIME • Apart from having a data type, a variable has space and time attributes. • The space attribute signifies the scope or visibility of the variable. This is actually the region of the program where the variable is visible and can be accessed. • A variable may have one of four possible scopes: block, function, file and program. – A variable having block scope is visible in the block in which it is declared. – A variable having file scope is visible in the entire file. • The time attribute determines the lifetime of the variable, i.e., its time of birth and death. • A variable declared inside a function lives as long as the function is active. One declared before main is alive for the duration of the program. 2/11/2021 3.2 Functions 78
  • 79. Local and Global Variables • Variables declared inside a function are visible only in the function. They have local scope, the reason why they are called local variables. • Variables declared outside a function are known as global variables. The scope of a global variable extends from the point of its declaration to the rest of the file. • When a variable is declared before main, it is truly global across the entire program (which may be spread across multiple files). 2/11/2021 3.2 Functions 79
  • 80. Scope of Global and Local Variables 2/11/2021 3.2 Functions 80
  • 82. THE STORAGE CLASSES • The scope, lifetime and initial value of a variable are determined by its storage class. • So far, we have used the default storage class for variables (automatic), but you also need to know the following storage classes supported by C: – automatic (auto) – static (static) – external (extern) – register (register) • The storage class also determines the way the compiler allocates memory for a variable. 2/11/2021 3.2 Functions 82
  • 84. Static Variables (static) • If a local variable is assigned the static storage class, then it will retain its value between function calls. • A static variable (keyword: static) is created and initialized just once, when the function containing its declaration is executed. 2/11/2021 3.2 Functions 84
  • 85. External Variables (extern) • A global or external variable is defined outside a function and is visible everywhere—even in other files that constitute the program. 2/11/2021 3.2 Functions 85
  • 86. Register Variables (register) • All program variables are stored in primary memory which is faster than disk but slower then registers directly connected to the CPU. • The register storage class (keyword: register) permits a variable to be stored in one of the high-speed CPU registers. • The compiler will attempt to store the variable x in one of the registers, failing which it will use primary memory. • A register normally has a size of one word, not all variables can be assigned this storage class. • Generally, register is restricted to char and int variables. • However, you can’t obtain the address of a register variable using &x because registers don’t use the addressing system used by primary memory. 2/11/2021 3.2 Functions 86
  • 87. Thank you 2/11/2021 3.2 Functions 87
  • 88. C Programming : Recursive Functions, Variable Scope and Lifetime and Storage Classes By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India
  • 89. Contents 1. Arrays – Declaring and initializing 1D array – Two dimensional arrays – Multidimensional arrays 2. Functions – Basics, The anatomy of a function – Types of functions based on arguments and return types – Passing 1D and 2D arrays as arguments to functions – Calling function from another function 3. Recursive functions 4. Variable scope and lifetime 5. Storage classes. 2/11/2021 89 3.3 Recursive Functions
  • 90. RECURSIVE FUNCTIONS • Loops use the iterative technique to repeatedly update a set of data with the same set of instructions. • Repetition can also be achieved by recursion, a form of cloning that uses instructions to specify themselves. • In C, a recursive function calls itself, which on return delivers to its caller its share of the final solution. • A recursive function must not be allowed to run forever because the program will eventually run out of memory. 2/11/2021 3.3 Recursive Functions 90
  • 91. 2/11/2021 3.3 Recursive Functions 91
  • 92. RECURSIVE FUNCTIONS • Because the static variable count is defined and initialized just once, it can track the number of calls made to main. • You are aware that function variables and parameters are saved in a separate region of memory called the stack. • With every recursive call, the stack grows in size, and if this growth goes unchecked, the stack will eventually overflow. • In this program, after main has called itself 523,172 times, stack overflow occurs and terminates the program with a “segmentation fault.” • This is not the way recursive functions are meant to be used. 2/11/2021 3.3 Recursive Functions 92
  • 93. Using a Recursive Function to Compute Factorial • This is simply the product of all integers from 1 to the number. • For instance, 6!, the factorial of 6, is 6 × 5 × 4 × 3 × 2 × 1 = 720. • But 6! can also be expressed as 6 × 5! in the same way as 5! is expressed as 5 × 4!. • We can thus express the factorial of a number in this manner: 2/11/2021 3.3 Recursive Functions 93
  • 94. 2/11/2021 3.3 Recursive Functions 94
  • 95. VARIABLE SCOPE AND LIFETIME • Apart from having a data type, a variable has space and time attributes. • The space attribute signifies the scope or visibility of the variable. This is actually the region of the program where the variable is visible and can be accessed. • A variable may have one of four possible scopes: block, function, file and program. – A variable having block scope is visible in the block in which it is declared. – A variable having file scope is visible in the entire file. • The time attribute determines the lifetime of the variable, i.e., its time of birth and death. • A variable declared inside a function lives as long as the function is active. One declared before main is alive for the duration of the program. 2/11/2021 3.3 Recursive Functions 95
  • 96. Local and Global Variables • Variables declared inside a function are visible only in the function. They have local scope, the reason why they are called local variables. • Variables declared outside a function are known as global variables. The scope of a global variable extends from the point of its declaration to the rest of the file. • When a variable is declared before main, it is truly global across the entire program (which may be spread across multiple files). 2/11/2021 3.3 Recursive Functions 96
  • 97. Scope of Global and Local Variables 2/11/2021 3.3 Recursive Functions 97
  • 98. Variable Hiding 2/11/2021 3.3 Recursive Functions 98
  • 99. THE STORAGE CLASSES • The scope, lifetime and initial value of a variable are determined by its storage class. • So far, we have used the default storage class for variables (automatic), but you also need to know the following storage classes supported by C: – automatic (auto) – static (static) – external (extern) – register (register) • The storage class also determines the way the compiler allocates memory for a variable. 2/11/2021 3.3 Recursive Functions 99
  • 100. 2/11/2021 3.3 Recursive Functions 100
  • 101. Static Variables (static) • If a local variable is assigned the static storage class, then it will retain its value between function calls. • A static variable (keyword: static) is created and initialized just once, when the function containing its declaration is executed. 2/11/2021 3.3 Recursive Functions 101
  • 102. External Variables (extern) • A global or external variable is defined outside a function and is visible everywhere—even in other files that constitute the program. 2/11/2021 3.3 Recursive Functions 102
  • 103. Register Variables (register) • All program variables are stored in primary memory which is faster than disk but slower then registers directly connected to the CPU. • The register storage class (keyword: register) permits a variable to be stored in one of the high-speed CPU registers. • The compiler will attempt to store the variable x in one of the registers, failing which it will use primary memory. • A register normally has a size of one word, not all variables can be assigned this storage class. • Generally, register is restricted to char and int variables. • However, you can’t obtain the address of a register variable using &x because registers don’t use the addressing system used by primary memory. 2/11/2021 3.3 Recursive Functions 103
  • 104. Thank you 2/11/2021 3.3 Recursive Functions 104