0% found this document useful (0 votes)
26 views52 pages

C Programming: Functions and Pointers

C unit 3

Uploaded by

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

C Programming: Functions and Pointers

C unit 3

Uploaded by

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

UNIT III

UNIT III FUNCTIONS AND POINTERS


Modular programming - Function prototype, function definition, function call, Built-in functions
(string functions, math functions) – Recursion, Binary Search using recursive functions – Pointers –
Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Parameter passing:
Pass by value, Pass by reference.

INTRODUCTION TO FUNCTIONS
Structured programming is a programming technique in which a larger program is divided
into smaller subprograms. These subprograms are easy to understand, easy to implement. The
structured programming enables code reusability. Code reusability is a method of writing
code once and using it many times.
In C, the structured programming can be designed using functions concept. Using functions
concept, we can divide larger program into smaller subprograms and these subprograms are
implemented individually. Program is divided into multiple functions.

Fig. Dividing of main program


Every C program starts with the user-defined function main(). The C language supports two
types of functions.
1. Library functions
 Library functions are pre-defined set of functions.
 These are called as system defined functions or Pre-Defined Functions.
 printf(), scanf(), sqrt() are examples of library functions User-defined functions
2. User-defined functions
 User-defined functions have to be developed by the user at the time of writing the
program.
 main() is an example of user-defined functions.

Programming in C CSE@AVCCE
UNIT III

Functions
 A function is a block of statements that together perform a specific task.
 Every C program has at least one function, which is main().
 A function can also be referred as a method or a sub-routine or a procedure, etc.
Uses of C Functions
 Using functions, larger program can be divided into smaller modules.
 Modular programming is implemented using functions.
 Main advantages of C functions are, re-usability, dividing a big task into small pieces to
achieve the functionality and to improve understandability.
 It is easy to track when the program is divided into functions.
 Once a function is created it can be used many times (code reusability).
Every function in C has the following.
i. Function Declaration (Function Prototype)
ii. Function Definition
iii. Function Call

Function Declaration
 The function declaration informs the compiler about function name, datatype of the
return value and number of arguments.
 The function declaration is also called as function prototype.
 The function declaration is performed before main function or inside main function or
inside any other function.
Syntax:
returnType functionName(parameters);
 returnType specifies the datatype of the value which is sent as a return value from the
function definiton.
 functionName is a user defined name used to identify the function uniquely.
 parametersList is the data values that are sent to the function definition.
Example:
//function name = display, receives a character as argument and returns nothing
void display(char);
//function name = sum, receives two integers as argument and returns an integer
int sum(int, int);

Programming in C CSE@AVCCE
UNIT III

Function Definition
 The function definition provides the actual code of that function. The function
definition is also known as body of the function.
 The actual instructions of a function are written inside the braces "{ }".
 The function definition is performed before main function or after main function.
Syntax:
returnType functionName(parameters)
{
//Function body
}
 Function body is the collection of statements.

Example:
int sum (int x, int y)
{
// Function body has 2 statements
int s = x+y;
return s;
}

Function Call
 Function call statement calls the function by matching its name and arguments.
 A function call can be made by using function name and providing the required
parameters.
Syntax:
functionName (parameters);
or
variable = functionName(parameters);

Example:
display(a);
or
s = sum(x,y);

Programming in C CSE@AVCCE
UNIT III

Fig. Working of a C - function


Example
/* Simple C program using Functions */
void message(); //Function prototype
void main()
{
message(); //Function call
}
void message ( ) // Function Definition
{
printf("Hello World");
}
Output:
Hello World

/* C program to explain Multiple Functions in a program*/


void biology();
void maths();
void commerce(); //Function prototypes
void main()
{
biology(); //Function call 1
maths(); //Function call 2
commerce (); //Function call 3
}
void biology() //Function Definition 1
{
printf("I am Biology Student\n");
}

Programming in C CSE@AVCCE
UNIT III

void maths() //Function Definition 2


{
printf("I am maths Student\n");
}
void commerce() //Function Definition 2
{
printf("I am commerce Student\n");
}
Output:
I am Biology Student
I am maths Student
I am commerce Student

In the concept of functions, the function call is known as "Calling Function" and the
function definition is known as "Called Function".
When we make a function call, the execution control jumps from calling function to called
function. After executing the called function, the execution control comes back to calling
function from called function.
The data values transferred from calling function to called function are called as Parameters
and the data value transferred from called function to calling function is called Return value.

Programming in C CSE@AVCCE
UNIT III

/*C Program to add integers and display sum in main() function */


#include <stdio.h>
int addNumbers(int a, int b); //function declaration
void main()
{
int sum;
sum = addNumbers(10, 20); //function call
printf("sum of two numbers =%d", sum);
}
int addNumbers(int a, int b) // function definition
{
int add;
add=a+b;
return add; // return statement of function
}
Output:
sum of two numbers = 30

FUNCTION PROTOTYPES
Based on the data flow between the calling function and called function, the functions are
classified.
1. Functions with no arguments and no return value.
2. Functions with no arguments and with return value.
3. Functions with arguments and no return value.
4. Functions with arguments and with return value.

Classification of Functions
1. Functions with no arguments and no return value
 In this type of functions there is no data transfer between calling function and called
function.
 The execution control jumps from calling function to called function and executes
called function, and finally comes back to the calling function.

Programming in C CSE@AVCCE
UNIT III

Fig. No arguments and no return values

Program
/* C program to explain functions with no arguments and no return value */
#include <stdio.h>
void main()
{
void addition(); // function declaration
addition(); // function call
}
void addition() // function definition
{
int num1, num2;
printf("Enter any two integer numbers : ");
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2);
}
Input:
Enter any two integer numbers: 20 30
Output:
Sum = 50
2. Functions with no arguments and with return value
 In this type of functions there is no data transfer from calling function to called
function (parameters) but there is data transfer from called function to calling function
(return value).
 The execution control jumps from calling function to called function and executes
called function, and finally comes back to the calling function along with a return
value.

Programming in C CSE@AVCCE
UNIT III

Fig. - No arguments and with return values


Program
/* C program to explain functions with no arguments and with return value */
#include <stdio.h>
void main()
{
int result;
int addition(); // function declaration
result = addition(); // function call
printf("Sum %d", result);
}
int addition () // function definition
{
int num1, num2;
printf("Enter any two integer numbers: ");
scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}
Input:
Enter any two integer numbers: 20 30
Output:
Sum = 50
3. Functions with arguments and no return value
 In this type of functions there is data transfer from calling function to called function
(parameters) but there is no data transfer from called function to calling function
(return value).

Programming in C CSE@AVCCE
UNIT III

 The execution control jumps from calling function to called function along with the
parameters and executes called function, and finally comes back to the calling
function.

Fig. - With arguments and no return values


Program
/* C program to explain functions with arguments and no return value */
#include <stdio.h>
void main()
{
int num1, num2;
void addition(int, int); // function declaration
printf("Enter any two integer numbers : ");
scanf("%d%d", &num1, &num2);
addition(num1, num2); // function call
}
void addition (int a, int b) // function definition
{
printf("Sum = %d", a+b );
}
Input:
Enter any two integer numbers: 20 30
Output:
Sum = 50

4. Functions with arguments and return value


 In this type of functions there is data transfer from calling function to called function
(parameters) and also from called function to calling function (return value).

Programming in C CSE@AVCCE
UNIT III

 The execution control jumps from calling function to called function along with
parameters and executes called function, and finally comes back to the calling
function along with a return value.

Fig. - With arguments and with return values


Program
/* C program to explain functions with arguments and with return value */
#include <stdio.h>
void main()
{
int num1, num2, result;
int addition (int, int); // function declaration
printf("Enter any two integer numbers : ");
scanf("%d%d", &num1, &num2);
result = addition (num1, num2); // function call
printf("Sum = %d", result);
}
int addition (int a, int b) // function definition
{
return (a+b);
}
Input:
Enter any two integer numbers: 20 30
Output:
Sum = 50

Programming in C CSE@AVCCE
UNIT III

Fig. - Functions with arguments Vs Functions without arguments


Parameters
When the execution control is transferred from calling function to called function it may
carry one or more number of data values. These data values are called as parameters.
Parameters are the data values that are passed from calling function to called function..
In C, there are two types of parameters and they are as follows:
i) Actual Parameters
 The actual parameters are the parameters that are specified in calling function.
ii) Formal Parameters
 The formal parameters are the parameters that are declared at called function. When a
function gets executed, the copy of actual parameters is copied to the formal
parameters.

Programming in C CSE@AVCCE
UNIT III

Fig – Formal and Actual Parameters


There are two methods to pass parameters from calling function to called function and they
are as follows.
1. Call by Value (or) Pass by value
2. Call by Reference (or) Pass by Reference

Fig. - Call by Value Vs Call by Reference


1. Call by Value
 In call by value parameter passing method, the copy of actual parameter values are
copied to formal parameters.
 The changes made on the formal parameters have no effect on the actual parameters.
 That means, after the execution control comes back to the calling function, the actual
parameter values remains same.

Programming in C CSE@AVCCE
UNIT III

/* C program to swap two numbers using call by value */

#include<stdio.h>
void main()
{
int num1, num2;
void swap (int, int); // function declaration
num1 = 10;
num2 = 20;
printf("\nBefore swap: num1= %d, num2 = %d",num1, num2);
swap(num1, num2); // calling function
printf("\n After swap:num1 =%d \n num2 = %d",num1, num2);
}
void swap(int a, int b) // called function
{
int temp;
temp = a ;
a = b;
b = temp;
}
Output:
Before Swap: num1 = 10, num2 = 20
After Swap: num1 = 10, num2 = 20
Here, num1 and num2 are called actual parameters, a and b are called formal parameters.
num1 is copied to a and num2 is copied to b. Changes makes on a and b have no effect on
num1 and num2.

2. Call by Reference
 In Call by Reference parameter passing method, the address of the memory location
address is copied to formal parameters. The address of the actual parameters is passed
to the called function and is received by the formal parameters (pointers).
 Hence changes made on the formal parameters have effect on the actual parameters
also.

Programming in C CSE@AVCCE
UNIT III

Program
/* C program to swap two numbers using call by reference */
#include <stdio.h>
void main()
{
int num1, num2 ;
void swap (int*,int*); // function declaration
num1 10;
num2 = 20;
printf("\nBefore swap: num1=%d, num2 = %d", num1, num2
swap (&num1, &num2); // calling function
printf("\nAfter swap: num1= %d, num2 = %d", num1, num2);
}
void swap(int *a, int *b) // called function
{
int temp;
temp = *a ;
*a = *b;
*b = temp;
}
Output:
Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10
Here, the addresses num1 and num2 are copied to a and b. Hence, changes made on the
pointer variables a and b have effect on the actual parameters too.

Nesting of Functions
A function calling another function is known as a nested function.

Fig. - Nested Functions

Programming in C CSE@AVCCE
UNIT III

Example
/* one Function calling another Function in a C program*/
void message(); //Function prototype
void say(); //Function prototype
void main()
{
message(); //Function call
}
void message() // Function Definition
{
say();
printf("Hello World");
}
void say()
{
printf("This will be executed first\n");
}
Output:
This will be executed first
Hello World

BUILT-IN FUNCTIONS
The standard library functions are built-in functions in C programming to handle tasks such
as mathematical computations, I/O processing, string handling etc. The various built-in
functions along with the header files are displayed in the following table.
Standard Functions
Table - Header files and standard functions
Header File Purpose Example
stdio.h Provides functions to perform
printf(), scanf()
standard I/O operations
conio.h Provides functions to perform console
clrscr(), getch()
I/O operations
string.h Provides functions to handle string
strlen(), strcpy()
data values
stdlib.h Provides functions to perform general
calloc(), malloc()
functions
math.h Provides functions to perform sqrt(), pow()

Programming in C CSE@AVCCE
UNIT III

mathematical operations
time.h Provides functions to perform
time(), localtime()
operations on time and date
graphics.h Provides functions to draw graphics circle(), rectangle()

Math Functions
"math.h" header file supports all the mathematical related functions in C language. All the
mathematical functions used in C language are given below
Table - Math Functions
Function Description Example Output
abs() Returns the positive absolute value of an abs(200) 200
integer. abs(-400) 400
floor() Returns the nearest integer. floor(5.1) 5
floor(5.9) 5
floor(-5.4) -6
round() Returns the nearest integer value round(5.4) 5
round(5.9) 6
round(-5.4) 5
ceil() Returns nearest integer value which is greater ceil(5.4) 6
than or equal to the value passed ceil(5.9) 6
sin() Returns sine value. sin(0.314) 0.3088
cos() Returns cosine value. cos(0.314) 0.9511
tan() Returns tangent value. tan(0.314) 0.3247
sinh() Returns hyperbolic sine value. sinh(0.25) 0.2526
cosh() Returns hyperbolic cosine value. cosh(0.25) 1.0314
tanh() Returns hyperbolic tangent value. tanh(0.25) 0.2449
exp() Returns the exponential "e" value exp(6.25) 518.01
log() Returns natural logarithm value. log(6.25) 1.8326
log10() Returns base 10 logarithm values. log10(6.25) 0.7959
sqrt() Returns the square root of a number. sqrt(16) 4
sqrt(2) 1.141
pow() Returns the power of a number. pow(2,4) 16
pow(5,3) 125
trunc() Truncates the decimal value from floating trunc(16.99) 16
point value and return integer value. trunc(20.1) 20

Programming in C CSE@AVCCE
UNIT III

String Functions
"string.h" header file supports all the string functions in C language. All the string functions
are given below.
Table - String Functions
Function Description Example Output
strcat() Concatenates s2 at the end of s1 = "World" World of C
sl s2 = "of C"
strcat (s1,s2)
printf("%s",s1)
strncat() Appends a portion of string to strncat (s1,s2,2) World of
another printf("%s",s1)
strcpy() Copies s2 into sl strcpy (s1,s2 ) of C
printf("%s",s1)
strncpy() Copies given number of strncpy (s1,s2, 2) of
printf("%s",s1)
strlen() Gives the length of s1 c = strlen(s1) 5
printf(“%d”, c)
strcmp() Returns 0 if s1 is same as s2. i= strcmp(s1,"World")
Returns <0 if s1<s2. printf("%d",i) 0
Returns >0 if s1>s2 i = strcmp(s1,s2)
printf("%d",i) 1
i = strcmp(s2,s1)
printf("%d",i) -1
strcmpi() Same as strcmp() function. But i= strcmp(s1,"WORLD") 0
this function negotiates case. printf("%d",i)
strchr() Returns pointer to first i=strchr(s1,'o') 1
occurrence of char in str1 printf("%d",i)
strrchr() Returns the last occurrence of s1="World of C” 6
given character in a string i = ,strchr(s1,'o')
printf("%d”, i)
strstr() Returns pointer to first s1="World of C” 2
occurrence of s2 in sl i = ,strchr(s1,'o')
printf("%d”, i)
strrstr() Returns pointer to last s1= "Test to Test you " 8
occurrence of s2 in sl i= strstr(s1,"Test")
printf("%d",i)
strdup() Duplicates the string s1 = "Hello"
s2 = strdup(s1)
printf("%s",s2)
strlwr() Converts string to lowercase s1 = "Hello" hello
printf("%s",strlwr(s1))

Programming in C CSE@AVCCE
UNIT III

strupr() Converts string to uppercase s1 = "Hello" HELLO


printf("%s",strupr(s1))
strrev() Reverses the given string s1 = "Hello" olleH
printf("%s",strrev(s1))
strset() Sets all character in a string to s1 = "Hello" #####
given character printf("%s",strset(s1,'#'))
strnset() It sets the portion of characters s1=”Hello” ##llo
in a string to given character printf(“%s”,strnset(s1,„#‟,2)
strtok() Tokenizing given string using s1= "Hello to all" Hello:to:all
delimiter printf("%s",strtok(s1,":"))
Recursion
Recursion is the process of repeating items in a self-similar way. In programming languages,
a function calling itself is called recursive function.
Example:
void recursion()
{
recursion (); /* function calls itself */
}
void main()
{
recursion();
}

The recursive functions should be used very carefully because; when a function called by
itself it enters into infinite loop. Define the condition to exit from the function call so that the
recursive function gets terminated.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.

Programming in C CSE@AVCCE
UNIT III

Program
/* C Program to find Factorial of a given number using
Recursion */
#include <stdio.h>
int fact(int i)
{
if(i <= 1)
{
return 1;
}
return i * fact(i-1);
}
void main()
{
int i = 5;
printf("Factorial = %d", fact(i));
}
Output:
Factorial = 120

Program
/* C Program to generate Fibonacci Series using Recursion */
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,...
#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;
for (i= 0; i<10; i++)
printf("%d\t", fibonacci(i));
}
Output:
0 1 1 2 3 5 8 13 21 34

Programming in C CSE@AVCCE
UNIT III

Merits of using Recursion


 To write efficient programs using a minimum amount of code.
 Nominal chance of syntax and logical errors.
 Increases the program efficiency.

Demerits of using Recursion


 Can cause infinite loops and other unexpected results if not written properly.
 Recursion takes a lot of stack space, usually not considerable when the program size
is small.
 Recursion uses more processor time.

Key Points to remember while writing Functions


 Every C program has a function called main().
 C Functions can be invoked from anywhere within a C program.
 C functions can be called with or without arguments/parameters. These arguments
inputs to the functions.
 C functions may or may not return values to calling functions. These values output of
the functions.
 When a function completes its task, program control is returned to the function from
where it is called.
 Before calling and defining a function, declare function prototype to inform the
compiler about the function name, function parameters and return value type.
 When return data type of a function is "void", then, it won't return any values.
 When return data type of a function is other than void such as "int, float, double", it
returns value to the calling function.
Example Programs
Computation of Sine series using Built-in functions.
/* C Program to Compute Sine series using Built-in functions */
sin x = x - x³/3! + x5/ 5! – x7/7! + ……

(−1)n
= 𝑥 2𝑛 +1 ²:
𝑛=0 2n+1 !

Programming in C CSE@AVCCE
UNIT III

#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
void main()
{
int n, x1;
float acc, term, den, x, sinx=0, sinval;
clrscr();
printf("Enter the value of x (in degrees)\n");
scanf("%f",&x);
x1 = x;
/* Converting degrees to radians*/
x = x* (3.142/180.0);
sinval sin(x);
printf("Enter the accuary for the result\n");
scanf("%f", &acc);
term = X;
sinx = term;
n = 1;
do
{
den = 2*n* (2*n+1);
term = -term * x * x / den;
sinx sinx + term;
n = n + 1;
}
while (acc<= fabs (sinval - sinx));
printf("Sum of the sine series %f\n", sinx);
printf("Using Library function sin(%d)=%f\n",x1,sin(x));
getch();
}
Input:
Enter the value of x (in degrees)
45
Enter the accuary for the result
0.00001
Output:
Sum of the sine series =0.707178
Using Library function sin (45)= 0.707179

Programming in C CSE@AVCCE
UNIT III

Program
Scientific Calculator using Built-in functions.
/* C Program Scientific Calculator using Built-in functions */
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(void)
{
int choice, i, a, b;
float x, y, result;
clrscr();
do
{
printf("\nSelect your operation (0 to exit):\n");
printf("[Link] \n [Link] \n
[Link] \n 4. Division \n”);
printf("5. Square root\n 6. X ^ Y\n7. X^2 \n 8. X^3
\n”);
printf("Choice: ");
scanf("%d", &choice);
if(choice == 0)
exit(0);
switch (choice)
{
case 1:
printf("Enter X: ");
scanf("%f", &x);
printf("\nEnter Y: ");
scanf("%f", &y);
result = x + y;
printf("\nResult: %f", result);
break;
case 2:
printf("Enter X: ");
scanf("%f", &x);
printf("\nEnter Y: ");
scanf("%f", &y);
result = x - y;
printf("\nResult: %f", result);
break;
case 3:
printf("Enter X: ");
scanf("%f", &x);
printf("\nEnter Y: ");

Programming in C CSE@AVCCE
UNIT III

scanf("%f", &y);
result = x * y;
printf("\nResult: %f", result);
break;
case 4:
printf("Enter X: ");
scanf("%f", &x);
printf("\nEnter Y: ");
scanf("%f", &y);
result = x / y;
printf("\nResult: %f", result);
break;
case 5:
printf("Enter X: ");
scanf("%f", &x);
result = sqrt(x);
printf("\nResult: %f", result);
break;
case 6:
printf("Enter X: ");
scanf("%f", &x);
printf("\nEnter Y: ");
scanf("%f", &y);
result = pow (x, y);
printf("\nResult: %f", result);
break;
case 7:
printf("Enter X: ");
scanf("%f", &x);
result = pow (x, 2);
printf("\nResult: %f", result);
break;
case 8:
printf("Enter X: ");
scanf("%f", &x);
result = pow (x, 3);
printf("\nResult: %f", result);
break;
default:
printf("\nInvalid Choice!");
}
}while (choice);
getch();
}

Programming in C CSE@AVCCE
UNIT III

Input:
Select your operation (0 to exit):
1. Addition
2. Subtraction
3. Multiplication
4. Division
[Link] root
6.X^Y
7.X^2
8.X^3
Output:
Choice: 1
Enter X:5
Enter Y:4
Result:9

Program
Binary Search using Recursive functions.

Programming in C CSE@AVCCE
UNIT III

/* C Program to perform Binary Search using Recursive


functions*/
#include<stdio.h>
void main()
{
int a[10],i, n,m,c,l,u;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: );
for(i=0; i<n; i++)
scanf("%d",&a[i]);
printf("Enter the number to be search: ");
scanf("%d",&m);
l=0,u=n-1;
c = binary (a, n,m,1,u);
if (c==0)
printf("Number is not found.");
else
printf("Number is found.");
}

int binary(int a[], int n, intm, intl, int u)


{
int mid, c=0;
if (l<=u)
{
mid=(1+u)/2;
if(m==a[mid])
c=1;
else if (m<a [mid])
return binary(a,n,m,1,mid-1);
else
return binary(a,n,m,mid+1, u);
}
else
return c;
}
Input:
Enter the size of an array: 4
Enter the elements of the array: 4 5 6 7
Enter the number to be search: 7
Output: Number is found.

Programming in C CSE@AVCCE
UNIT III

POINTERS
Pointers are the powerful feature of C that differentiates it from other popular programming
languages like: Java and Python.
In C programming language, we use normal variables to store data values. When we declare a
variable, the compiler allocates required memory with specified name. We use a special type
of variable called pointer to store the address of another variable with same data type.
Pointer Operators
Pointer is a special type of variable used to store the memory location address of another
variable.

Fig- Pointer variable


When a variable name x is declared as integer type, a memory location is selected with a
name x.
int x;
The variable name is the symbolic name for the address in memory. The numeric value of the
address corresponding to x is shown.

Fig- Effect of declaring a variable

Where, int x = 32; is declared, the integer 32 is stored as contents of x.

Fig. - A variable name with a value assigned to it

Programming in C CSE@AVCCE
UNIT III

1. Accessing the Address of Variables


In C programming language, the reference operator "&" is used to access the address of
variable. For example, to access the address of a variable, &marks is used. p = &marks would
assign the address 5000 (location of marks) to the pointer variable p. The & operator can be
remembered as "address of" operator.
2. Declaring Pointers (Creating Pointers)
The pointer variable is declared similar to the creation of normal variable but the name is
prefixed with * symbol.
Syntax:
datatype *pointer Name;
A variable declaration prefixed with * symbol becomes a pointer variable.
Example:
int *ptr;
The variable "ptr" is a pointer variable is of integer datatype, is used to store any integer
variable address.
3. Assigning Address to Pointer
To assign address to a pointer variable use the assignment operator with the following syntax.
Syntax:
pointerVariableName = &variableName ;
Example:
int a, *ptr ;
ptr = &a;
Here, "a" is a normal integer variable and variable "ptr" is an integer pointer variable.
4. Accessing Variable Value Using Pointer
Pointer variables are used to store the address of other variables. We can use this address to
access the value of the variable through its pointer.
Use the symbol "*" in front of pointer variable name to access the value of variable to which
the pointer is pointing.
Syntax:
*pointerVariableName

Programming in C CSE@AVCCE
UNIT III

Program
/* C Program to explain Reference operator (&) and Dereference operator (*) */
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 10, *ptr ;
clrscr();
ptr = &a ;
printf("Address of variable a = %u\n", ptr);
printf("Value of variable a =%d\n",*ptr);
printf("Address of variáble ptr = %u\n", &ptr);
}
Output:
Address of variable a = 65524
Value of variable a = 10
Address of variable ptr = 65526

In the above example program, variable a is a normal variable and variable ptr is a pointer
variable. Address of variable a is stored in pointer variable ptr. Here ptr is used to access the
address of variable a and *ptr is used to access the value of variable a.

5. Memory Allocation of Pointer Variables


Every pointer variable is used to store the address of another variable. Memory address of
any memory location is an unsigned integer value.
Program
/* C Program to explain memory location in Pointers */
#include<stdio.h>
void main()
{
char a;
int x;
a = 'X';
x = 549;
printf("%c is at address = %u\n", a, &a) ;
printf("%d is at address = %u\n",x, &x);
}
Output:
X is at address = 5482
549 is at address = 5484

Programming in C CSE@AVCCE
UNIT III

Program
/* C program to explain handling of pointers */
#include <stdio.h>
void main()
{
int *pc;
int c;
c=22;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
pc=&c;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc: %d\n\n", *pc);
C=11;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc: %d\n\n", *pc);
*pc=2;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
}
Output
Address of c: 2686784
Value of c: 22
Address of pointer pc: 2686784
Content of pointer pc: 22
Address of pointer pc: 2686784
Content of pointer pc: 11
Address of c: 2686784
Value of c: 2

Chain of Pointers
A pointer to a pointer is a form of multiple in-directions, or a chain of pointers. Normally, a
pointer contains the address of a variable. When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that contains
the actual value as shown below.

Programming in C CSE@AVCCE
UNIT III

Fig. – Pointer to Pointer – In depth


Syntax:
datatype **pointerName;
A variable that is a pointer to a pointer must be declared by placing an additional asterisk in
front of its name. For example, the following declaration declares a pointer to a pointer of
type int.
int **var;
Program
/* C program to explain Pointers to Pointers */
#include <stdio.h>
void main()
{
int var;
int *ptr;
int **pptr;
var = 3000;
printf("Value of var = %d\n", var);
/* take the address of var "/
ptr = &var;
printf("Address of 3000 = %u\n", ptr);
printf("Value available at *ptr = %d\n", *ptr);
/* take the address of ptr using address of operator & */
pptr = &ptr;
printf("Address of pointer = %u\n", pptr);

Programming in C CSE@AVCCE
UNIT III

/* take the value using pptr */


printf("Value available at **pptr = %d\n", **pptr);
}
Output:
Value of var = 3000
Address of 3000 = 7956
Value available at *ptr = 3000
Address of pointer = 6598
Value available at **pptr = 3000

Pointer Arithmetic
Pointer variables are used to store address of variables. Address of any variable is an
unsigned integer value i.e., it is a numerical value. Arithmetic operations can be performed on
pointer values. But the result depends on the amount of memory required by the variable to
which the pointer is pointing.
The following arithmetic operations are performed on pointers.
1. Adding a number to pointer.
2. Subtracting a number form a pointer.
3. Incrementing a pointer.
4. Decrementing a pointer.
5. Subtracting two pointers.

1. Adding Numbers to Pointers


Adding a number N to a pointer leads the pointer to a new location after adding N times size
of data type.
ptr + N = ptr + (N * sizeof(pointer_data_type))
Let ptr be a 4-byte integer pointer, initially pointing to location 5000.
ptr + 5 = 5000 + 4*5 = 5020
Now, pointer ptr will point at memory location 5020.

2. Subtracting Numbers from Pointers


Subtracting a number N from a pointer is subtracting N times the data type and moving to the
new location.
ptr -N = ptr - (N * sizeof(pointer_data_type))

Programming in C CSE@AVCCE
UNIT III

Let ptr be a 6-byte double pointer, initially pointing to location 5000.


ptr - 3 = 5000 - 6*3 = 4982.
Now, pointer ptr will point at memory location 4982.

3. Incrementing a Pointer
"Incrementing a pointer increases its value by the number of bytes of its data type".
Let ptr be an integer pointer which points to the memory location 5000 and size of an integer
variable is 32-bit(4 bytes). Now, when we increment pointer ptr
ptr++;
will point to memory location 5004 because it will jump to the next integer location which is
4 bytes next to the current location. Incrementing a pointer is not same as incrementing an
integer value.
On incrementing, a pointer will point to the memory location after skipping N bytes, where N
is the size of the data type (in this case it is 4).A character (1 bytes) pointer is incremented by
1 bytes.
ptr + (sizeof(pointer_data_type))

4. Decrementing a Pointer
"Decrementing a pointer increases its value by the number of bytes of its data type"
ptr--;
ptr will point to 4996.
ptr - (sizeof(pointer_data_type))

5. Subtracting Pointers
The difference between two pointer returns indicates. It gives the total number of elements
between two pointers. If an integer pointer 'ptrl' points at memory location 10000 and
integer pointer 'ptr2' points at memory location 10008, the result of ptr2 - ptr1 is 2.
Scale Factor
We increment a pointer, its value is increased by the length of the data type that it points to.
This length is called the scale factor
The length of various data types are as follows:
character 1 byte
integers 2 byte
floats 4 bytes
long integers 4 bytes
doubles 8 bytes

Programming in C CSE@AVCCE
UNIT III

Program
/* program to explain Pointer Arithmetic Operations */
#include<stdio.h>
void main()
{
intint_var = 10, *int_ptr;
char char_var = 'A', *char_ptr;
float float_val = 4.65, *float_ptr;

/* Initialize pointers */
int_ptr = &int_var;
char_ptr = &char_var;
float_ptr = &float_val;
printf("Address of int_var = %u\n", int_ptr);
printf("Address of char_var = %u\n", char_ptr);
printf("Address of float_var = %u\n\n", float_ptr);

/* Incrementing pointers */
int_ptr++;
char_ptr++;
float_ptr++;
printf("Afterincrement address in int_ptr=%u\n",int_ptr);
printf("After increment address in char_ptr=%u\n",
char_ptr);
printf("After increment address in float_ptr= %u\n\n",
float_ptr);
/* Adding 2 to pointers */
int_ptr = int_ptr + 2;
char_ptr = char_ptr + 2;
float_ptr = float_ptr + 2;
printf("After addition address in int_ptr = %u\n",
int_ptr);
printf("After addition address in char_ptr = %u\n",
char_ptr);
printf("After addition address in float_ptr = %u\n\n",
float_ptr);
}
Output:
Address of int_var = 2293300
Address of char_var = 2293299
Address of float_var = 2293292

Programming in C CSE@AVCCE
UNIT III

After increment address in int_ptr = 2293304


After increment address in char_ptr = 2293300
After increment address in float_ptr - 2293296
After addition address in int_ptr = 2293312
After addition address in char_ptr = 2293302
After addition address in float_ptr = 2293304

POINTERS AND ARRAYS


Array is a collection of similar data type elements. When we declare all array then
consecutive memory location are located to the array of elements. The element of an array
can be efficiently accessed by using pointers.
Array element is always store in consecutive memory locations according to the size of
the array. The size of the data type in the pointer variable refer to, is depends on the
data type pointed to by the pointer.
A pointer when incremented. always points to a location after skipping the number of
bytes required for the data type pointed to by It.
Eg:
int a[5]= {l0,20,30,40,50};
a[5] means the array 'a' has 5 elements and of integer data type.
The base address of the array starts with 0th element of the array. The array is in integer type,
the integer will have 2 bytes and hence the address of the next address element is incremented
by 2.
Eg:
int a[5]= {l0,20,30,40,50};
int *b;
b=a;
'b' is a pointer variable which holds the base address of the array 'a' ie. b=&a[0].
When pointer variable is incremented by 1 then it related base address will be incremented by
address + 2 because pointer is of type integer. Hence the next address element by increase by
2 till the size of an array.

Programming in C CSE@AVCCE
UNIT III

Program
/* Program to print the value and address of the element. */
#include < stdio. h >
void main ( )
{
int a[5] ={l0,20,30,40,50};
int b;
for (b=0;b<5;b++)
{
printf("The value of a[%d]=%d",b,a[b]);
printf("Address of a[%d]=%u",b,&a[b]);
}
}
Output:
The value of a[0] =10 Address of a[0]=4000
The value of a[1] =20 Address of a[1]=4002
The value of a[2] =30 Address of a[2]=4004
The value of a[3] =40 Address of a[3]=4006
The value of a[4] =50 Address of a[4]=4008

Program
#include < stdio. h >
void main()
{
int *p, sum, i;
static int x[5] = {10,20,30,40,50};
i = 0; p = x; sum = 0;
printf(“Element \t Value \t Address\n”);
while(i<5)
{
printf(“x[%d] \t %d \t %u”,i,*p,p);
sum = sum + *p;
i++;
p++;
}
printf(“\n Sum = %d\n”,sum);
printf(“\n &x[0] = %u \n”,&x[0]);
printf(“\n p = %u\n”,p);
}
Output
Element Value Address
x[0] 10 4000
x[1] 20 4002

Programming in C CSE@AVCCE
UNIT III

x[2] 30 4004
x[3] 40 4006
x[4] 50 4008
sum = 150
&x[0] = 4000
p = 4010

Program
/* Program to add the sum of number using pointer*/
#include <stdio.h>
void main ()
{
int b, total;
int a[5];
int *c ;
for(b=0;b<5;b++)
{
printf("Enter the number %d", b + 1);
scanf ("%d",&a[b]);
}
c = a;
for (b = 0;b<5; b++)
{
total = total + *c;
c = c + 1;
}
printf("\n total=%d", total);
}
Output
Enter the number 1 10
Enter the number 2 20
Enter the number 3 30
Enter the number 4 40
Enter the number 5 50
Total = 150

Program
/* Program to sort a given number using pointer*/
#include < stdio.b >
main ( )
{
int j,k;
int arr[5];

Programming in C CSE@AVCCE
UNIT III

int *a;
a = arr;
for (j=0;j<5;j+ +)
{
printf("Enter the number %d= “, j+ 1);
scanf ("%d", &arr[i]);
}
printf ("\n Before sorting");
for(j =0;j<5;j+ +)
printf("%d",arr[j]);
a=arr;
for (j=0;j<5;j++)
{
for (k=0;k< 5- j -l; k+ +)
{
if (*(arr+k) > *(arr+k+1))
swap(arr+k, arr+k+1);
}
}
printf("After sorting");
for (j=0; j<5; j+ +)
printf ("%d", arr[j]);;
}
swap (b,c)
{
int *b, *c;
int temp;
temp=*b;
*b=*c;
*c=temp;
}
Output
Enter the number=8
Enter the number=5
Enter the number=7
Enter the number=4
Enter the number=6
Before sorting
85746
After sorting
45678

Programming in C CSE@AVCCE
UNIT III

Pointers with Multi- Dimensional Array


A multi dimensional array can also be represented with an equivalent pointer notation. A two
dimensional array can be considered as a collection of one-dimensional arrays.
Syntax:
data-type (*pointer variable)[Expression 2];
rather than
data-type array[Expression 1][Expression 2];

Where
Data-type - refers to the data type of the array.
Pointer-variable - is the name of the pointer variable.
Array - is the corresponding array name.
Expression 1, Expression 2 - are positive-integer expression that indicate the maximum
number of arrays elements associated with each subscript.
If 'a' is a two dimensional integer array having 10 rows and 20 columns.
'a' can be declared as
pointer  int (*a)[20]; rather than
array  int a[l0][20];
In first declaration 'a' is defined to be a group of contiguous, one dimensional, 20-elements
integer array, 'a' points to the first 20 element array which is actually first row (0th row) of
the original two-dimensional array. Similarly (2 +1) points to the second 20 elements array.
i.e., second row (1th row) and so on.
Pointers to two-dimensional arrays are denoted as follows:
Let us take p as a pointer variable ,
p → pointer to first row
p+i → pointer the ith row
*(p+i) → pointer to first element in the ith row
*(p+i)+j → pointer to jth element in the ith row
*(*(p+i)+j) → Value stored in the cell( i , j) (ith row and jth column);
For example, In the array x, the item in 2 row, 5 column can be accessed using the
expression. *(*(x+2)+5)

Programming in C CSE@AVCCE
UNIT III

Program
/* Program to print the values and address of the array
elements */
#include<stdio.h>
main()
{
int arr[4][2]={{5,100}, {10,200}, {15,300}, {20,400}};
int a,b;
for(a=0;a<4;a++)
{
printf("Address of %d array=%u" a, &arr[a]);
for(b=0; b<2; b++)
printf("value = %d",arr[a][b]);
}
}
Output
Address of 0 array = 4000
value= 5
value= l00
Address of 1 array = 4004
value=10 value =200
Address of 2 array = 4008 value =15
value =300
Address of 3 array = 4012 value =20
value =400

Pointers and Character Strings


Character and Pointer
A character pointer is a pointer to the character. It can be declared as
char *pointer_character
A character pointer can also be used to access character arrays and string constants in the
same way as accessing numeric arrays using their respective pointer variable.
A character_type pointer variable can be assigned an entire string as part of variable
declarations
whereas a numerical pointer variable cannot be initialized in the same manner as a numerical
array.

Programming in C CSE@AVCCE
UNIT III

Program: Pointers and Character Strings


#include<stdio.h>
void main()
{
char *name;
int length;
name ="DELHI";
char *cptr = name;
while(*cptr!='\0')
{
printf("%c is stored at address %u\n",*cptr, cptr);
cptr++;
}
length = cptr - name;
printf("\n name address value = %u",name);
printf(“cptr address value = %u”,cptr);
printf("\n Lenth of the String = %d",length);
}
Output:
D is stored at address 171
E is stored at address 172
L is stored at address 173
H is stored at address 174
I is stored at address 175
name address value = 171
cptr address value = 176
Length of the string = 5

Pointers and Strings


A String is a sequence of characters stored in an array. A string always ends with null ('\0')
character. A pointer to array of characters or string can be looks like the following:

C \0 C + + \0` J a v a \0
Fig. - Pointers and strings
Program
/* C program to explain Pointers and Strings */
#include <stdio.h>
void main()
{
int i;
char *lang[4]= {"C", "C++", "Java"};
for (i = 0; i < 3; i++)

Programming in C CSE@AVCCE
UNIT III

printf("%s\n", lang[i]);
}

Output:
C
C++
Java
In the above program, a pointer array of character data type is declared and strings like
"C","C++","Java" are initialized to the pointer array (*lang[]). Note that the size of the array
is not declared as it is of character pointer type.

Program: Sorting of names.


/* C Program to Sort names using Pointers */
#include <stdio.h>
void main()
{
char *fruit[] = {"apricot", "banana", "pineapple",
"apple", "persimmon", "pear", "blueberry\n"};
char *temp;
int a, b, x;
for (a=0; a<6; a++)
for (b=a+1; b<7;b++)
if (strcmp(*(fruit+a), *(fruit+b))>0)
{
temp = *(fruit+a);
*(fruit+a)= *(fruit+b);
*(fruit+b) = temp;
}
for (x=0; x<7; x++)
puts(fruit[x]);
}
Output:
apple
apricot
banana
blueberry
pear
persimmon
Pineapple

Programming in C CSE@AVCCE
UNIT III

Array of Pointers
One important use of pointers is in handling of a table of strings. Consider the following
array of strings:
char lang[3][20] = {C,C++, Java}
It means that the lang is a array containing 3 names, each with a maximum length of 20
characters (including null character). The total space needed for the lang array is 60 bytes.

Instead of making each row a fixed number of characters, make it a pointer to a string of
varying length.
char *lang[3] = {C, C++, Java}
Declares lang to an array of 3 pointers.
This declaration needs only 11 bytes.

POINTERS AND FUNCTIONS


A pointer can be used as an argument in function. The arguments or parameters to the
function are passed in two ways.
i) Call by value
ii) Call by reference

(i) Call by value


The process of passing the actual value of variables is known as "call by Value".
When a function is called in program. the values to the arguments in the function are taken by
the calling program.
The value taken can be used inside the function.

Programming in C CSE@AVCCE
UNIT III

Alteration to the value is not accepted inside the function in calling program but change is
locally available in the function.

Program: Write a program to swap (interchange) the two given variable .


#include<stdio.h>
void main()
{
int a=10, b=20;
printf ("Before swap a=%d, b=%d", a, b);
void swap(a,b);
printf ("After swap a = %d, b= %d", a, b);
}
void swap(x,y)
{
int x,y;
x=x+y;
y=x-y;
x=x-y;
printf ("In swap function x=%d, y=%d" ,x, y);
}
Output
Before swap a=10, b=20.
In swap junction x=20, y=10.
After calling the swap junction a=10, b=20.

(ii) Call by Reference


The process of calling a function using pointers to pass the addresses of variables is known as
"call by Reference".
A function can be declared with pointers as its arguments. Such function are called by calling
program with the address of a variable as argument from it.
The address of the variable are altered to the pointers and any change made to the value
inside the function is automatically carried out in the location. This change is accepted by the
calling program.
Program: Write a program to explain about call by reference.
#include<stdio.h>
void main()
{
int a=10, b=20;
printf("\n Before swap a=%d,b=%d",a,b);
void swap(&a,&b);

Programming in C CSE@AVCCE
UNIT III

printf("\n After calling swap function a=%d, b=%d",a,b);


}

void swap(int *x, int *y)


{
int temp;
temp = *x;
*x = *y;
*y = temp;
printf("\n In swap function x=%d, y =%d", *x, *y);
}
Output
Before swap a=10, b=20.
In swap junction x=20, y=10.
After calling swap junction a=20, y=10.

Comparison between Call by value and Call by reference

[Link] Call by Value Call by Reference


1 Different memory locations are Same memory location occupied by
occupied by format and actual formal and actual arguments and there is
arguments a saving of memory location.
2 Any alteration in the value of the Any alteration in the value of the
arguments passed is local to the function argument passed is accepted in the
and is not accepted in the calling calling program
program
3 The usual method to call a function in The address of the variable is passed as
which only the value of the variable is an argument
passed as an argument
4 When a new location is created it is very The existing memory location is used
slow. through its address, it very fast
5 There is no possibility of wrong data There is a possibility of wrong data
manipulation since the argument are manipulation since the address are used
directly used in an expression in an expression. A good skill of
programming is required here.
Benefits of using pointers
 Reduces the storage space and complexity of the program.
 Reduces the execution time of the program.
 Pointers can be used to pass information back and forth between the calling function
and called function.

Programming in C CSE@AVCCE
UNIT III

 Pointers allow us to perform dynamic memory allocation and deallocation.


 Pointers helps us to build complex data structures like linked list, stack, queues, trees,
graphs etc.

Drawbacks of using pointers


 Uninitialized pointers might cause segmentation fault.
 Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to
memory leak.
 Pointers are slower than normal variables.
 If pointers are updated with incorrect values, it might lead to memory corruption.

ADDITIONAL PROGRAMS
Program
/* C Program to Compute the Sum of Digits of a given Integer*/
Sum of Digits in a Integer
435 = 4 + 3 + 5 = 12

#include <stdio.h>
void main()
{
int num, no, digit, sum = 0;
printf("Enter the number \n");
scanf("%d", &num);
no = num;
while (num> 0)
{
digit = num % 10;
sum = sum + digit;
num /= 10;
}
printf("Given number = %d\n", no);
printf("Sum of the digits of %d = %d\n", sum);
}
Input:
Enter the number
167
Output:

Programming in C CSE@AVCCE
UNIT III

Given number = 167


Sum of the digits of 167 = 14

Program
/* C Program to Check if a Given String is Palindrome */
Palindrome: A string is said to be palindrome if reverse are of the string is same as string.
Examples: "dad", "radar", "madam" etc.*/
#include <stdio.h>
#include <string.h>
void main()
{
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string: \n");
scanf("%s", string1);
length = strlen(string1);
for(i=0; i < length ;i++)
{
if(string[i] != string1[length-i-1])
{
flag 1;
break;
}
}
if(flag)
printf("%s is not a palindrome\n", string1);
else
printf("%s is a palindrome\n", string1);
}
Input:
Enter a string: dad
Output:
dad is a palindrome

Program
/* C program for using recursion, find the sum of the series:

Programming in C CSE@AVCCE
UNIT III

#include <stdio.h>
int power(int,int);
int fact(int);
float sum (int,int);
void main()
{
int x,n;
float f;
printf("Enter the 'x' value: \n");
scanf("%d",&x);
printf("Enter the 'n' value: \n");
scanf("%d",&n);
f=sum(x, n) ;
printf("\n sum of the series: %f\n", f);
}
int power (intx,int i)
{
int p;
if (i==0)
p=1;
else
p=power(x,i-1)*x;
return p;
}
int fact(int x)
{
int f;
if(x==0)
f=1;
else
f=fact (x-1) *x;
return f;
}
float sum(intx,int n)
{
int i;
float s,s1=0, s2, s3;
for(i=0; i<n; i++)
{

Programming in C CSE@AVCCE
UNIT III

s2=power(x,i);
s3=fact(n);
s=s2/s3;
s1=s1+s;
}
return s1;
}
Input:
Enter the 'x' value: 2
Enter the 'n' value: 3
Output:
sum of the series: 1.166667

Program
/* C Program to perform sum = 1+ (1+2) + (1+2+3)+...+ (1+2...+n)*/
#include <stdio.h>
void main()
{
int n, sum, i, j;
printf("Please enter an integer, n =\n ");
scanf("%d", &n);
for(i=1;i<n;i++)
for(j=1;j<=i; j++)
sum = sum + n;
printf("sum = %d\n", sum);
}
Input:
Please enter an integer, n =2
Output:
sum = 4

Program
/* C Program to Compute the Sum of the series */

#include<stdio.h>
void main()
{

Programming in C CSE@AVCCE
UNIT III

int n,i;
int sum=0;
printf("Enter the n i.e. max values of series: \n");
scanf("%d",&n);

Programming in C CSE@AVCCE
UNIT III

sum = (n*(n + 1)/(2 n + 1))/6;


printf("Sum of the series : %d\n", sum);
}
Input:
Enter the ni.e. max values of series: 5
Output:
Sum of the series: 55

Program
/* C Program to Compute the Sum of the series */
Sum of the series:1^2 +3^2 +5^2+…..+n^2.
#include<stdio.h>
void main()
{
int i,n, sum=0;
printf("1^2+3^2+5^2+.....+n^2");
printf("Enter value of n:\n");
scanf("%d",&n);
for(i=1;i<n; i+=2)
sum = sum + (i*i);
printf("Sum of the series : %d\n", sum);
}
Input:
Enter value of n: 2
Output:
Sum of the series : 5

Program
/* C Program to Compute the Sum of the series*/
Sum of the series: 1 + 3 + 5 +...n
#include <stdio.h>
void main()
{
int i,n, sum=0;
printf("1 + 3 + 5 ++ n");
printf("Enter value of n:\n");
scanf("%d",&n);
for(i=1;i<=n;i+=2)

Programming in C CSE@AVCCE
UNIT III

sum = sum + i;
printf("Sum of the series :%d\n", sum);
}
Input:
Enter value of n: 9
Output:
Sum of the series : 165

Program
/*C Program to find Factorial of a given number using Iteration */
#include <stdio.h>
void main()
{
int i,n;
printf(“Enter n Value:”);
scanf(“%d”, &n);
for (i =1; i < n; i++)
fact = fact * i
printf("Factorial Execution: = %d\n", fact);
}
Input:
Enter n Value: 5
Output:
Factorial = 120

Program
/* C Program to find largest and smallest element in an array using functions*/
#include <stdio.h>
void main()
{
int arr[30], size, largest,i;
printf("Enter the size of the array :\n ");
scanf("%d", &size);
printf("Enter the numbers:\n");
for(i=0; i<size; i++)
scanf("%d",&arr[i]);
largest = find_largest(arr, size);
printf("\nThe largest element is: %d\n", largest);

Programming in C CSE@AVCCE
UNIT III

smallest = find_smallest (arr, size);


printf("\nThe smallest element is: %d\n", smallest);
}
int find_largest (int arri[], int size1)
{
int large, i;
large = arr1[0];
for(i=1;i<size1; i++)
if(arri[i] >large)
large =arri[i];
return(large);
}
int find_smallest(int arri[], int size1)
{
int small, i;
small=arri[0];
for(i=1;i<size1; i++)
if (arri[i]<small)
small =arri[i];
return (small);
}
Input:
Enter the size of the array: 4
Enter the numbers: 22 55 11 44
Output:
The largest element is: 55
The smallest element is: 11

Programming in C CSE@AVCCE

You might also like