0% found this document useful (0 votes)
6 views13 pages

UNIT 3 C Programming

UNIT 3 C Programming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
6 views13 pages

UNIT 3 C Programming

UNIT 3 C Programming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

1

UNIT-III
FUNCTIONS AND POINTERS
Functions And Pointers Introduction to functions: Function prototype, function definition,
function call - Parameter passing: Pass by value, Pass by reference – Recursion – Pointers –
Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers –– Pointer to
pointers – pointer to strings.

FUNCTION:
A large C program is divided into basic building blocks called C function. C function contains
set of instructions enclosed by “{ }” which performs specific operation in a C program.
Benefits of using function in C
 Function provides modularity.
 Function provides reusable code.
 In large programs, debugging and editing tasks is easy with the use of functions.
 The program can be modularized into smaller parts.
 Separate function independently can be developed according to the needs.

There are two types of functions in C


 Built in(Library) Functions
o These functions are provided by the system and stored in library, therefore it is
also called „Library Functions„.
e.g. scanf(), printf(), strcpy, strlwr, strcmp, strlen, strcat etc.
o To use these functions, we need to include the appropriate C header files.
 User Defined Functions These functions are defined by the user at the time of writing
the program.

ELEMENTS OR PARTS OF FUNCTION:


A function is a group of statements that together perform a task. The function contains
the following elements:
 Function declaration(or Function prototype)
 Function definition
 Function call
1) Function prototype
A function prototype is simply the declaration of a function that specifies function's name,
parameters and return type. It doesn't contain function body. A function prototype gives
information to the compiler that the function may later be used in the program.
Syntax of function prototype:
returnType functionName(type1 argument1, type2 argument2,...);
For example, float square ( float x ); is the function prototype which provides following
information to the compiler:
1. name of the function is square()
2. return type of the function is float
3. one argument of type float is passed to the function
The function prototype is not needed if the user-defined function is defined before the main()
function.
2

2) Function Call:
Control of the program is transferred to the user-defined function by calling it.
Syntax of function call:
functionName(argument1, argument2, ...);
In the above example, function call is made using square ( m ) ; statement inside the main().

Example to call a function:


1. hello();//calls function that doesn't return a value
2. int value=get();//calls function that returns value
3. int value2=add(10,20);//calls parameterized function by passing 2 values
3) Function definition
Function definition contains the block of code to perform a specific task i.e. in this case, squaring
one float number and returning it.
Syntax of function definition:
returnType functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
}
When a function is called, the control of the program is transferred to the function definition.
And, the compiler starts executing the codes inside the body of a function.
#include<stdio.h>
// function prototype, also called function declaration
float square ( float x );
// main function, program starts from here
void main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}

float square ( float x ) // function definition


{
float p ;
p=x*x;
return ( p ) ;
}
Output:
Enter some number for finding square
2
Square of the given number 2.000000 is 4.000000
3

TYPES OF FUNCTIONS:
All C functions can be called either with arguments or without arguments in a C
program. These functions may or may not return values to the calling function. C Function
types are listed below:
1. C function with arguments (parameters) and with return value.
2. C function with arguments (parameters) and without return value.
3. C function without arguments (parameters) and without return value.
4. C function without arguments (parameters) and with return value.

1. Function without argument and without return value:


In this method, we won‟t pass any arguments to the function while defining,
declaring or calling the function. This type of functions will not return any value when we call
the function from main() or any sub function. In the example program, we are going to
calculate the Sum of 2 integer values and print the output from the user defined function itself.
#include<stdio.h>
void Addition();
void main()
{
Addition();
}
void Addition()
{
int Sum, a = 10, b = 20;
Sum = a + b;
printf("\n Sum of a = %d and b = %d is = %d", a, b, Sum);
}

2. Function without arguments and with return value:


In this method, we won‟t pass any arguments to the function while defining, declaring or
calling the function. This type of functions will return some value when we call the function
from main() or any sub function. Data Type of the return value will depend upon the return type
of function declaration. In this program, we are going to calculate the multiplication of 2 integer
values using the user defined function without arguments and return keyword.
#include<stdio.h>
int Multiplication();
void main()
{
int Multi;
Multi = Multiplication();
printf("\n Multiplication of a and b is = %d \n", Multi );
}
int Multiplication()
{
int Multi, a = 20, b = 40;
Multi = a * b;
return Multi;
4

3. Function with arguments and without return value


This method allows to pass the arguments to the function while calling the function. But,
This type of functions will not return any value when we call the function from main () or any
sub function. This program allows the user to enter 2 integer values and then, We are going to
pass those values to the user defined function to calculate the sum.

#include<stdio.h>
void Addition(int, int);
void main()
{
int a, b;
printf("\n Please Enter two integer values \n");
scanf("%d %d",&a, &b);
Addition(a, b);
}
void Addition(int a, int b)
{
int Sum;
Sum = a + b;
printf("\n Additiontion of %d and %d is = %d \n", a, b, Sum);
}
4. Function with arguments and with return value
This method allows to pass the arguments to the function while calling the function. This
type of functions will return some value when we call the function from main () or any sub
function. Data Type of the return value will depend upon the return type of function declaration.
This type of user defined functions are called as fully dynamic function means, it provide
maximum control to the end user.
This program allows the user to enter 2 integer values and then, We are going to pass
those values to the user defined function to multiply those values and return the value using
return keyword.
#include<stdio.h>
int Multiplication(int, int);
void main()
{
int a, b, Multi;

printf("\n Please Enter two integer values \n");


scanf("%d %d",&a, &b);
Multi = Multiplication(a, b);
printf("\n Multiplication of %d and %d is = %d \n", a, b, Multi);
}
int Multiplication(int a, int b)
{
int Multi;
5

Multi = a * b;
return Multi;
}

CALL BY VALUE and CALL BY REFERENCE:

There are two types of arguments are supported in C functions. Such as


1. Actual parameter – This is the argument which is used in function call.
2. Formal parameter – This is the argument which is used in function definition
While calling a function, the arguments can be passed to a function in two ways, Call by value
and call by reference.

Call By value:

When we pass the actual values of parameters while calling a function then this is
known as function call by value. New memory area created for the passed parameters, can be
used only within the function. In this case the values of actual parameters are copied to the
formal parameters. Thus operations performed on the formal parameters don’t reflect in the
actual parameters. Function call by value is the default way of calling a function in C
programming. Consider the function swap() definition as follows.
#include <stdio.h>
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
void main() {
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
}
It shows that there are no changes in the values, though they had been changed inside the
function.

call by reference:
The call by reference method of passing arguments to a function copies the address of
an argument into the formal parameter. Inside the function, the address is used to access the
actual argument used in the call. It means the changes made to the formal parameter affect
the actual argument.
6

#include <stdio.h>
void swap(int *x, int *y) {
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void main() {
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
}
Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
It shows that the change has reflected outside the function as well, unlike call by value
where the changes do not reflect outside the function.

RETURN STATEMENT
The return statement terminates the execution of a function and returns a value to the calling
function. The program control is transferred to the calling function after return statement. In the
above example, the value of variable result is returned to the variable sum in the main() function.
7

Syntax of return statement


return (expression);
For example,
return a;
return (a+b);
The type of value returned from the function and the return type specified in function prototype
and function definition must match.

RECURSION IN C
When function is called within the same function, it is known as recursion in C. The
function which calls the same function, is known as recursive function. Let's see a simple
example of recursion.
void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}
The recursion continues until some condition is met to prevent it.

Example of recursion in C
Let's see an example to print factorial number using tail recursion in C language.

#include<stdio.h>
#include<conio.h>
int factorial (int n)
{
if ( n < 0)
return -1; /*Wrong value*/
if (n == 0)
return 1; /*Terminating condition*/
8

return (n * factorial (n -1));


}

void main(){
int fact=0;
clrscr();
fact=factorial(5);
printf("\n factorial of 5 is %d",fact);
}
Output
factorial of 5 is 120

Advantages and Disadvantages of Recursion


 Recursion makes program elegant and cleaner. All algorithms can be defined recursively
which makes it easier to visualize and prove.
 If the speed of the program is vital then, we should avoid using recursion. Recursions use
more memory and are generally slow. Instead, we can use loop.

Fibonacci Series using recursion(Another Example)


The following example generates the Fibonacci series for a given number using a recursive
function −
#include <stdio.h>
int fibonacci(int i) {

if(i == 0) {
return 0;
}

if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}

void main() {
int i;
9

for (i = 0; i < 10; i++) {


printf("%d\t\n", fibonacci(i));
}
}

POINTERS:
 Pointers in C language is a variable that stores/points the address of another variable. A
Pointer in C is used to allocate memory dynamically i.e. at run time. The pointer variable
might be belonging to any of the data type such as int, float, char, double, short etc.
 Pointer Syntax : data_type *var_name;
 Example : int *p;
char *p;
Where, * is used to denote that “p” is pointer variable.
Reference operator (&) and Dereference operator (*)
 & is called reference operator. It gives the address of a variable.
 dereference operator (*):gets the value from the address

An example of using pointers printing the address and value is given below.

Here, pointer variable stores the address of number variable i.e. fff4. The value of number
variable is 50. But the address of pointer variable p is aaa3. By the help of * (indirection
operator), we can print the value of pointer variable p.
#include <stdio.h>
#include <conio.h>
void main()
{
int number=50;
int *p;
clrscr();
p=&number;//stores the address of number variable
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of p variable is %d \n",*p);
}
Output
Address of number variable is fff4
Address of p variable is fff4
10

Value of p variable is 50

Benefits of using Pointers in C


 Pointers allows passing of arrays and strings to functions more efficiently.
 Pointers makes possible to return more than one value from the function.
 Pointers reduce the length and complexity of program.
 Pointers increase the processing speed.
 Pointers save the memory.

NULL Pointer
A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have
any address to be specified in the pointer at the time of declaration, you can assign NULL value.
It will a better approach.
int *p=NULL;

C POINTER TO POINTER
In C pointer to pointer concept, a pointer refers to the address of another pointer.
In c language, a pointer can point to the address of another pointer which points to the address of
a value. Let's see the syntax of pointer to pointer.
int **p2;
Let's see an example where one pointer points to the address of another pointer.

In the above figure, p2 contains the address of p (fff2) and p contains the address of number
variable (fff4).
#include <stdio.h>
#include <conio.h>
void main()
{
int number=50;
int *p; //pointer to int
int **p2; //pointer to pointer
p=&number; //stores the address of number variable
p2=&p;
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of *p variable is %d \n",*p);
printf("Address of p2 variable is %x \n",p2);
printf("Value of **p2 variable is %d \n",**p);
11

Output
Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

POINTER ARITHMETIC IN C
In C pointer holds address of a value, so there can be arithmetic operations on the pointer
variable. Following arithmetic operations are possible on pointer in C language:
 Increment
 Decrement
 Addition
 Subtraction
 Comparison

1. Incrementing Pointer in C
Incrementing a pointer is used in array because it is contiguous memory location.
Moreover, we know the value of next location. Increment operation depends on the data type of
the pointer variable. The formula of incrementing pointer is given below:
new_address= current_address + i * size_of(data type)
2. Decrementing Pointer in C
Like increment, we can decrement a pointer variable. The formula of decrementing pointer is
given below:
1. new_address= current_address - i * size_of(data type)

Let's see the example of incrementing and decrementing pointer variable on 32 bit OS.
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable

printf("Address of p variable is %u \n",p);


p=p+1;
printf("After increment: Address of p variable is %u \n",p);
p=p-1;
printf("After decrement: Address of p variable is %u \n",p);
}
Output
Address of p variable is 3214864300
After increment: Address of p variable is 3214864302
After decrement: Address of p variable is 3214864300
12

3. C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is given
below:
new_address= current_address + (number * size_of(data type))
4. C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. The formula of
subtracting value from pointer variable is given below:
new_address= current_address - (number * size_of(data type))

#include <stdio.h>
void main(){
int number=50;
int *p; //pointer to int
p=&number; //stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
}
Output
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864306
After subtracting 3: Address of p variable is 3214864300

Here, we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value
occupies 2 byte memory in 32 bit OS.

ARRAY OF POINTERS
Following is the declaration of an array of pointers to an integer −
int *ptr[MAX];
It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds a pointer to
an int value. The following example uses three integers, which are stored in an array of pointers,
as follows −

#include <stdio.h>
const int MAX = 3;
void main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
13

}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

You can also use an array of pointers to character to store a list of strings as follows −
#include <stdio.h>
const int MAX = 4;
void main () {
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};

int i = 0;
for ( i = 0; i < MAX; i++) {
printf("Value of names[%d] = %s\n", i, names[i] );
}
}
When the above code is compiled and executed, it produces the following result −
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali

You might also like