unit-4
unit-4
UNIT-4
INTRODUCTION
The programs written in C language are highly dependent on functions. The C program is nothing but
the combination of one or more number of functions. Every C program starts with the user defined function
main(). The main() calls other functions to share the work. ‘C’ programmers to break-up a program into
segments commonly known as functions. Every function in the program is supposed to perform a well-
defined task.
main()
{
func1( )
…………
{
…………
Statementblock;
func1();
………… }
…………
return0;
}
Form the diagram, main () calls the func1.Therefore, main () is known as the calling function and func1 is
known as the called function.
Definition of the function:
The function is a sub program or sub routine or self contained block of one or more executable statement, which
performs a well defined task. We have two types of functions.
1. Standard/Pre Defined/Library Functions.
2. User Defined Functions.
Need for functions:
Divide the program into separate well-defined functions facilitates each function to be written and
tested separately.
From the diagram main( ) calls other functions for dividing the entire code into smaller functions.
This approach is referred to as ‘top down approach’.
Main function
Function B1 Function B2
Understanding, coding and testing multiple separate functions are far easier than doing the same for
one huge function.
It is big program has to be developed without the use of any function other than main( ), then there
will be countless lines in the main( ) and maintaining this program will be very difficult. A large
program size is a serious issue in micro computers where memory space is limited.
SEMESTER I::Problem Solving in C Page 1
KUMAR NAGISETTI
All the libraries in ‘C’ contain a set of functions that the programmers are free to use in their
programs. These functions have been pre-written and pre-tested, so the programmers can use them
without worrying about their code details.
When a big program is broken into smaller functions then different programmers working on that
project can divide the workload by writing different functions.
Similar to C libraries, programmers can from different points in the main program or any other
program that needs its functionalities.
Using functions:
In C program, the operating system calls the main() of the program which marks then try point for the
execution. When the program is executed, main( ) returns some value to the operating system.
Using functions we will be using the following terminologies.
A function f()that uses another function g(), is known as the calling function.
The inputs that the function takes are known as arguments or parameters.
When the called function returns some result back to the calling function. It is said to return that result.
The calling function mayor may not pass parameters to the called function. If the called function accepts
arguments, the calling function will pass parameters.
Function declaration is a declaration statement that identifies a function with its name, a list of arguments
that it accepts, and the type of data it returns.
Function definition consists of a function header that identifies the function followed by the body of the
function containing the executable code for that function
**********************************************************************************
Types of functions:
There are two types of functions in C:
1. Library Functions
2. User Defined Functions
Parameters
Formal parameters are the parameters declared in the brackets in function definition after the function
name. When any function is being called from the main program, the parameters used in the calling are
called the actual parameters, which are individually declared in the main program. These actual parameters
are converted to formal parameters when the control goes to the function.
Ex: main()
{
f1(10,20.8,‘g’)/*AP*/
}
f1(int x, float y, char ch’)/*FP*/
{
……………..
………….....
}
return statement: A function can return value by return statement. A function can return more than one
value from the function.
Syntax:
return(value/expression/variable);
return;
Ex:
1. return 25;
25is return to function call.
2. return;
nothing is returned(void function)
The following program gives a brief explanation on user defined functions.
Aim: To write a C program to illustrate the user defined functions in C
#include<stdio.h>
int sum(int, int);
void main()
{
int a, b, c;
printf("\n Enter two
integers:"); scanf("%d %d",
&a, &b); c=sum(a, b);
printf("\n The sum is %d",
c);
}
int sum(int x, int y)
{
int z;
z=x+y;
return z;
}
****************************************************************************
SEMESTER I::Problem Solving in C Page 4
KUMAR NAGISETTI
In this category no data is transferred from calling function to called function, hence
called function cannot receive any values.
In the above example, no arguments are passed to user defined function add().
Hence no parameter is defined in function header.
When the control is transferred from calling function to called function a, and b values
are read, they are added, the result is printed on monitor.
When return statement is executed, control is transferred from called function/add to calling
function/main.
Example:
#include<stdio.h> OUTPUT:
void swap(int x, int y) Before function call: a = 10, b = 20
{ Inside function (after swap): x = 20, y = 10
int temp = x; After function call: a = 10, b = 20
x = y;
y = temp;
printf("Inside function (after swap): x = %d, y = %d\n", x, y);
}
void main()
{
int a = 10, b = 20;
printf("Before function call: a = %d, b = %d\n", a, b);
swap(a, b);
printf("After function call: a = %d, b = %d\n", a, b); // No change in values
}
Execution starts from function main() and we will read the values for variables a and b,
assume we are reading 10 and 20 respectively.
We will print the values before swapping it will print 10 and 20.
The function swap() is called with actual parameters a=10and b=20.
In the function header of function swap(),the formal parameters x and y receive the
values 10 and20.
In the function swap(), the values of x and y are exchanged.
But, the values of actual parameters a and b in function main() have not been exchanged.
The change is not reflected back to calling function.
Call by Address:
In Call by Address, when a function is called, the addresses of actual parameters are sent.
In the called function, the formal parameters should be declared as pointers with the same
type as the actual parameters.
The addresses of actual parameters are copied into formal parameters.
Using these addresses the values of the actual parameters can be changed.
This way of changing the actual parameters indirectly using the addresses of actual
parameters is known as pass by address.
Example:
#include <stdio.h>
void swap(int *x, int *y) OUTPUT:
{ Before swapping: a = 10, b = 20
int temp = *x; After swapping: a = 20, b = 10
*x = *y;
*y = temp;
}
void main()
{
int a = 10, b = 20;
printf("Before swapping: a = %d, b = %d\n", a, b);
swap(&a, &b); // Passing addresses of a and b
printf("After swapping: a = %d, b = %d\n", a, b); // Values are swapped
return 0;
}
static
This storage class is used to declare static variables that have the property of preserving their value even after they
are out of their scope! Hence, static variables preserve the value of their last use in their scope.
Properties of static Storage Class
Scope: Local
Default Value: Zero
Memory Location: RAM
Lifetime: Till the end of the program
#include <stdio.h>
void counter()
{ Output
static int count = 0; Count = 1
count++; Count = 2
printf("Count = %d\n", count);
}
int main()
{
counter();
counter();
return 0;
}
Explanation: The static variable count retains its value between function calls. Unlike local variables, which are
reinitialized each time the function is called, static variables remember their previous value.
register
This storage class declares register variables that have the same functionality as that of the auto variables. The only
difference is that the compiler tries to store these variables in the register of the microprocessor if a free register is
available making it much faster than any of the other variables.
Properties of register Storage Class Objects
Scope: Local
Default Value: Garbage Value
Memory Location: Register in CPU or RAM
Lifetime: Till the end of its scope
Note: The compiler may ignore the suggestion based on available registers.
#include <stdio.h>
int main() { Output
register int i; 01234
for (i = 0; i < 5; i++) {
printf("%d ", i);
}
return 0;
}
Explanation: The register keyword suggests storing the variable in a register for faster access, but the compiler may
not always honor this request based on available CPU registers.
extern
Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is
used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different
block as well.
Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its
declaration/definition in any function/block.
Properties of extern Storage Class Objects
SEMESTER I::Problem Solving in C Page 9
KUMAR NAGISETTI
Scope: Global
Default Value: Zero
Memory Location: RAM Output
Lifetime: Till the end of the program. 20
For example, the below file contains a global variable.
#include <stdio.h>
int a = 20;
int main()
{
extern int a;
printf("%d",a);
}
Discuss about scope of variables?
In C. all constants and variables have a defined scope. By scope we mean the accessibility and visibility of the
variables at different points in the program. A variable or a constant in C has four types of scope:
1) Block scope,
2) Function scope,
3) Program scope,
4) File scope
Block scope:We know that a statement block is a group of statements enclosed within opening and closing
braces({}). If a variable is declared within a statement block then, as soon as the control exists that block, the
variable will cease to exist. Such a variable, also known as a local variable, is said to have a block scope.
For example, if we declare an integer x inside a function, then that variable is unknown to the rest of the
program (i.e., outside that function).
#include <stdio.h>
int main() { Output
int x = 10, i = 0; // Outer x = 10 The value inside the while loop is 0
while (i < 3) { The value inside the while loop is 1
int x = i; // Local x (shadows outer x) The value inside the while loop is 2
printf("\n The value inside the while loop is %d", x); The value of x outside the while loop is 10
i++;
}
printf("\n The value of x outside the while loop is %d", x);
return 0;
}
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. In other words function scope is applicable only with goto
label names. This means that the programmer cannot have the same label name inside a function.
#include <stdio.h>
void func(int a) { // a is local to func()
Output
printf("Inside func: a = %d\n", a);
} Inside func: a = 5
int main() {
int x = 5;
func(x); // Passing x to func()
return 0;
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 last statement in the function in which they are
declared and are re-created each time the function is called.
SEMESTER I::Problem Solving in C Page 10
KUMAR NAGISETTI
However, if you want this function to access some variables which are not passed to them 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.
Example:
#include <stdio.h>
int x = 10;
void print();
int main() {
printf("\n The value of global x in main() = %d", x); Output
int x = 2; The value of global x in main() = 10
printf("\n The value of local x in main() = %d", x); The value of local x in main() = 2
print(); The value of global x in print() = 10
return 0;
}
void print()
{
printf("\n The value of global x in print() = %d", x); // Uses global x
}
File scope: When 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 its data type, as
shown:
static int x = 10;
A global static variable can be used anywhere from the file in which it is declared but it is not accessible by
any other files. Such variables are useful when the programmer writes his/her own header files.
Difference Between Local and Global Variables in C
Feature Local Variable Global Variable
Scope Inside the function/block where it is declared Entire program (all functions)
Lifetime Created when function is called, destroyed Exists throughout the program execution
when function exits
Memory Storage Stored in stack memory Stored in data segment (global/static
memory)
Access Only accessible inside the function/block Accessible from any function in the program
Default Value Garbage value (if uninitialized) Zero (0) (if uninitialized)
Declaration Inside a function or block Outside all functions
Location
Usage Used for temporary, function-specific data Used for data that needs to be shared across
multiple functions
#include <stdio.h>
int globalVar = 10;
void function() {
int localVar = 20; // Local variable (only inside function)
printf("Inside function: Local Variable = %d\n", localVar);
printf("Inside function: Global Variable = %d\n", globalVar);
} Output
void main() { Inside main: Local Variable = 5
int localVar = 5; // Local to main() Inside main: Global Variable = 10
printf("Inside main: Local Variable = %d\n", localVar); Inside function: Local Variable = 20
printf("Inside main: Global Variable = %d\n", globalVar); Inside function: Global Variable = 10
function();
}
SEMESTER I::Problem Solving in C Page 11
KUMAR NAGISETTI
Types of recursion?
Recursion is a technique that breaks a problem into one or more sub-problems that are similar to the original
problem. Any recursive function can be characterized based on the following:
1. Direct Recursion: A function is said to be directly recursive if it explicitly calls itself. For example,
int func (int n)
{
if (n=0)
return n;
return (func(n-1));
}
Here, the function func() calls itself for all positive values of n, so it is said to be a directly recursive function.
2. Indirect Recursion: A function is said to be indirectly recursive if it contains a call to another function which
ultimately calls it. Look at the functions given. below. These two functions are indirectly recursive as they both call
each other.
Program:
void main (){
int x=10, Output
int *ptr; Value of x is 10
ptr = &x; 10 is stored at addr 4104
printf("Value of x is %d\n\n", x); x value =10
printf("%d is stored at address %u\n", x, &x); Now x = 25
printf("x value =%d", *ptr),
*ptr = 25;
printf("\n Now x = %d\n", x);
}
Write short notes on pointer expressions and pointer Arithmetic?
Pointer expressions: Similar to other variables, pointer variables can also be used in expressions. For
example, if ptr1 and ptr2 are pointers, then the following statements are valid.
int num1 = 2, num2 = 3, sum=0, mul = 0,
int *ptr1, *ptr2;
ptr1 = &numl;
ptr2 = &num2;
sum = *ptr1 + *ptr2;
mul = sum * *ptr1;
Pointer Arithmetic: As a pointer holds the memory address of a variable, some arithmetic operations can be
performed with pointers.
C supports four arithmetic operators that can be used with pointer, such as
Addition +
Substraction -
Incrementation ++
Decrementation --
Pointers are variables. They are not integers, but they can be displayed as unsigned integers. The conversion
specifier for a pointer is added and subtracted. For example,
ptr + + causes the pointer to be incremented, but not by 1.
Ptr-- causes the pointer to be decremented, but not by 1.
SEMESTER I::Problem Solving in C Page 15
KUMAR NAGISETTI
If we declare p as an integer pointer, then we can make the pointer p to point to the array x by the following
assignment :
int*p;
p = x;
This is equivalent to p = &x[0];
Now, we can access every value of x using p++ to move from one element to another.
A program to read and display an array of n integers.
#include <stdio.h>
void main()
{
int i, n;
int arr[10], *parr = arr; Output
printf("\n Enter the number of elements: "); Enter the number of elements: 5
scanf ("%d", &n); Enter the elements: 12345
printf("\n Enter the elements : "); The elements entered are: 12345
for (i=0; i<n; i++)
scanf("%d", (parr+i));
printf("\n The elements entered are: ");
for (i=0; i<n; i++)
printf("\t%d", *(parr+i));
}
Briefly explain array of pointers?
1. Array of integer pointers: Pointers may be arrayed like any other data type.
An array of pointers can be declared as
int *ptr[5];
The above statement declares an array of 5 pointers where each of the pointer points to an integer variable.
For example, look at the following code:
#include <stdio.h>
void main ()
{
int *ptr[3],i;
int a=10, b=20, c=30; Output
ptr[0]=&a; a, b, and c values are:
ptr[1]=&b; 10 20 30
ptr[2]=&c;
printf("a,b and c values are \n");
for (i=0; i<3; i++)
printf("%d\t", *ptr[i]);
}
2. Array of character pointers:
Now, consider an array of character pointers that is pointed to the strings.
char *ptr[3];
In the ptr array, each element is a character pointer. Initialize an array of characters with three strings can be
given as, char *ptr [3] = {"Rohan", "Raj", "Sree"};
Here ptr[0] is Rohan, ptr[1] is Raj and ptr[2] is sree. The memory layout of ptr can be given as shown in
figure below.
#include <stdio.h>
void main() { OUTPUT:
char *ptr[] = {"Rohan", "Raj", "Sree"}; Rohan
int i; Raj
for (i = 0; i < 3; i++) { Sree
printf("%s\n", ptr[i]);
}
}
Explain about passing an array to function using pointers?
An array can be passed to a function using pointers. For this, a function that excepts an array can declare the formal
parameter in either of the two following ways.
func(int arr[ ]); or func (int *arr);
When we pass the name of the array to a function, the address of the 0th element of the array is copied to the local
pointer variable in the function.
Program: A program to read and print an array of n numbers:
#include <stdio.h>
void read_array (int *arr, int n);
void print_array (int *arr, int n);
void main()
{
int a [10], n; OUTPUT:
printf("\n Enter the size of the array:"); Enter the size of the array: 5
scanf("%d", &n); Enter the array elements: 1 2 3 4 5
read_array (a, n); The array elements are: 1 2 3 4 5
print_array(a, n);
}
void read_array(int *arr, int n)
{
int i;
printf("\n Enter the array elements: ");
for (i=0; i<n; i++)
scanf("%d", &arr[i]);
}
void print_array (int *arr, int n)
{
int i;
printf("\n The array elements are: ");
for (i=0; i<n; i++)
printf("\t%d", arr[i]);
}
Write about drawbacks of pointers?
Some common errors encountered when using pointers.
1. Error un-initialized pointer: px is pointing to an unknown memory location.
Hence it will overwrite that location's contents and store 10 in it. Such a pointer is called a wild pointer. A
pointer which is not initialized with any address is called a wild pointer. It may contain any garbage address and
thus dereferencing a wild pointer can be dangerous.
int x, *px;
x = 10;
px = x;
ERROR: it should be px = &x;
SEMESTER I::Problem Solving in C Page 18
KUMAR NAGISETTI
2. Memory leak: Memory leakage occurs when memory is allocated but not released when it is no longer required.
This causes an application to unnecessarily consume memory thereby reducing the memory available for other
applications. Although in small programs it is not a big concern but when dealing with large projects, memory
leakage may result in slowing down the application or crashing the application when the computer memory
resource limits are reached.
3. Dangling pointer: Dangling pointers arise when an object is deleted or de-allocated, without modifying the
value of the pointer.
Dangling pointer problem occurs when the pointer still points to the same location in memory even though the
reference has been deleted and may now be used for other purpose.
Consider the following code which illustrates dangling pointer problem.
char *ptr1;
char *ptr2 = (char*) malloc (size of (char));
ptr1 = ptr2;
free (ptr2);
Now ptr1 becomes a dangling pointer.
4. Memory corruption: Memory corruption often occurs when due to programming errors, the contents of a
memory location gets modified unintentionally.
Memory corruption errors can be broadly classified into following categories.
i) Using un-initialized memory: An un-initialized memory contains garbage value.
ii) Using un-owned memory: A common programming mistake to use pointers for accessing and modifying
memory that is not owned by the program. This situation may arise when the pointer happens to be a null pointer or
a dangling pointer. Using such a pointer to write to a memory location is a serious programming flaw as it may lead
to crash another program or even the operating system.
iii) Using beyond allocated memory (buffer overflow): If the elements of the array are accessed in a loop, with
incorrect terminating condition, memory beyond the array bounds may be manipulated. Buffer overflow is a
common programming flaw exploited by computer viruses causing serious threat to computer security.
iv) Faulty de-allocation of memory: Memory leaks and freeing un-allocated memory can also result in memory
corruption.