[go: up one dir, main page]

0% found this document useful (0 votes)
14 views64 pages

Unit 3

Uploaded by

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

Unit 3

Uploaded by

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

3

Functions and Pointers


Introduction to functions: Function prototype, function
definition, function call, Built-in functions (string functions,
math functions) - Recursion - Example Program: Computation
of Sine series, Scientific calculator using built-in functions,
Binary Search using recursive functions - Pointers - Pointer
operators - Pointer arithmetic - Arrays and pointers - Array
of pointers - Example Program: Sorting of names -
Parameter passing: Pass by value, Pass by reference -
Example Program: Swapping of two numbers and changing
the value of a variable using 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
3.1
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.

Main
Program

Module 1 Module Module 3


2

Module 4 Module 5

Fig 3.1 Program is divided into multiple functions.


3.2 PROGRAMMING IN C

In the previous chapters, we have discussed the three functions, namely,


main(), printf() and scanf(). Every C program starts with the user-defined
function main(). The C language supports two types of functions.
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
✤ 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.

3.1.1 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 re-
usability).
FUNCTIONS AND 3.3
POINTERS
Syntax
Every function in C has the following.
✤ Function Declaration (Function Prototype)
✤ Function Definition
✤ Function Call

3.1.2 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
return Typefunction Name(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 intsum(int,int);

3.1.3 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.
3.4 PROGRAMMING IN C

Syntax
returnTypefunctionName(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;
}

3.1.4 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=function Name(parameters);
Example:
display(a);
or
s = sum(x,y);
FUNCTIONS AND 3.5
POINTERS
Working of C - function
How function works in C programming?

#include
<stdio.h> void
functionName()
{
..................
..................
} Function
int main() is
{ called
..................
When the Function is ..................
completed, it returns functionName();
back ..................
..................
Fig 3.2 Working of a C - function

/* Simple C program using Functions*/


void message(); //Function
prototype void main()
{
message(); //Function call
}

void message() // Function Definition


{
printf("Hello World");
}

Execution:
Output:
Hello World
3.6 PROGRAMMING IN C

/* C program to explain Multiple Functions in a


void biology(); //Function
prototypes void maths();
void commerce();
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");
}

void maths() //Function Definition 2


{
printf("I am maths Student\n");
}

void commerce() //Function Definition 2


{
printf("I am commerce Student\n");
}

Execution:
Output:
I am Biology Student
I am maths Student
I am commerce Student
FUNCTIONS AND 3.7
POINTERS
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.

How to pass arguments to a Return statement of a


function? Function

#include <stdio.h> #include <stdio.h>


int addNumbers(int a, int b); int addNumbers(int a, int b);
int main() int main()
{ {
.................. ..................
sum = addNumbers(n1, n2); sum = addNumbers(n1, n2);
.................. ..................
} }
int addNumbers(int a, int b) int addNumbers(int a, int b)
{ {
.................. sum=resul
..................
return t
..................
} result
}

Fig 3.3

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


Example:

First Secon Sum of


Numbe d two
r Numbe Numbers
r

4 3 = 80
5 5
3.8 PROGRAMMING IN C

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

3.2 FUNCTION PROTOTYPES


Based on the data flow between the calling function and called function,
the functions are classified.
✤ Functions with no arguments and no return value.
✤ Functions with no arguments and with return value.
✤ Functions with arguments and no return value.
✤ Functions with arguments and with return value.

3.2.1 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.
FUNCTIONS AND 3.9
POINTERS
✤ The execution control jumps from calling function to called function
and executes called function, and finally comes back to the calling
function.

Control Passing
void
function1() void function2()
No Argument Passing
{ {
....................... ..........................
No Return Value
... ..........................
function2(); }
Control Passing
.......................
...
}
Calling Function Called Function

Fig 3.4 No arguments and no return values

/* C program to explain functions with no arguments


#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 ) ;
}
Execution:
Input:
Enter any two integer numbers :
20 30 Output:
Sum = 50
3.10 PROGRAMMING IN C

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.

Control Passing
void function1()
{ void function2()
No Argument
.......................... {
result=function2( return(z);
Passing ..........................
);
.......................... }
Returning Value
}
Control Passing
Calling Function Called Function

Fig 3.5 No arguments and with return values

/* C program to explain functions with no arguments and


#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) ;
}
FUNCTIONS AND 3.11
POINTERS
Execution:
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).
✤ 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.

Control Passing
void function1()
{ void function2(int x, int y)
Argument Passing
......................... {
. ..........................
No Return Value
function2(10,20 ..........................
); }
Control Passing
.........................
.
}
Calling
Called Function
Function

Fig 3.6 With arguments and no return values

/* C program to explain functions with arguments and


#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);
3.12 PROGRAMMING IN C

addition(num1, num2) ; // function call


}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
Execution:
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).
✤ 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.

Control Passing
void function1() void function2(int x, int y)
{ {
Argument
......................... ..........................
.
Passing return(z);
function2(10,20 ..........................
);
Returning Value }
.........................
.
Control Passing
}
Calling
Called Function
Function
Fig 3.7 With arguments and with return values
FUNCTIONS AND 3.13
POINTERS

/* C program to explain functions with arguments and


#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) ;
}

Execution:
Input:
Enter any two integer numbers : 20 30
Output:
Sum = 50
3.14 PROGRAMMING IN C

Functions with arguments Vs Functions without arguments

Function

with Arguments without Arguments

declared and
defined with No parameter list
parameter list
No value passed
values for parameter during function call
passed during function
call
Ex:
int show();
Ex:
int sum(int x, int y);
//declaration show();
//call
//declaration sum(10, 20); //call

Fig 3.8

3.2.2 Function Call


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:
✤ Actual Parameters
 The actual parameters are the parameters that are specified in
calling function.
✤ 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.
FUNCTIONS AND 3.15
POINTERS

//Invoke(call) the method Actual Parameters


...... or Arguments
sum = add(number1, number1,number2
number2);
......

//Method definition
int add(int x, int y)
{
return Formal Parameters
or Arguments
(x+y); x, y
}

Fig 3.9 Formal and Actual Parameters

There are two methods to pass parameters from calling function to


called function and they are as follows.
✤ Call by Value (or) Pass by value
✤ Call by Reference (or) Pass by Reference

Original
Value

No If Ye
chang s
e

call by call by
value reference
Fig 3.10 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.
3.16 PROGRAMMING IN C

 That means, after the execution control comes back to the calling
function, the actual parameter values remains same.

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


Example:

Exchange or Swap values


First
Secon
Numbe
d
r
Numbe
r

45 35

#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\nnum2 = %d", num1,
num2);
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a = b ;
b = temp ;
}
Execution:
Output:
Before swap: num1 = 10, num2 = 20
After swap: num1 = 10, num2 = 20
FUNCTIONS AND 3.17
POINTERS
Here, num1 and num2 are called actual parameters,a andb are called
formal parameters. num1 is copied to a and num2 is copied to b. Changes
made 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.

/* C program to swap two numbers using call by


#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\nnum2 = %d", num1,
num2);
}
void swap(int*a, int*b) // called function
{
int temp ;
temp = *a
;
*a = *b ;
*b = temp ;
}
Execution:
Output:
Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10
3.18 PROGRAMMING IN C

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.

3.2.3 Nesting of Functions


✤ A function calling another function is known as a nested function.

main()

funct1()
Call funct1
funct2()
Call funct2
ret

ret

Fig 3.11 Nested Functions

/* one Function calling another Function in a C program*/


void message(); //Function prototype
void message(); //Function
prototype void main()
{
message(); //Function call
}
void message() // Function Definition
{
say();
printf("Hello World");
}
void say()
{
printf("This will be executed first\n");
}
FUNCTIONS AND 3.19
POINTERS
Execution:
Output:
This will be executed first
Hello World

3.3 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.

3.3.1 Standard Functions


Table 3.1 Header files and standard functions

Header File Purpose Example

stdio.h Provides functions to perform standard


I/O operations printf(), scanf()
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 calloc(), malloc()
general functions
math.h Provides functions to perform sqrt(), pow()
mathematical operations
time.h Provides functions to perform operations time(), localtime()
on time and date
graphics.h Provides functions to draw graphics. circle(), rectangle()
3.20 PROGRAMMING IN C

3.3.2 Math Functions


✤ "math.h" header file supports all the mathematical related functions in
C language. All the arithmetic functions used in C language are given
below.
Table 3.2 Math Functions

Function Description Example Output


Include the Header file: #include <math.h>
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 ceil(5.4) 6
greater 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 ( ) Returnshyperbolic 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 returns integer value trunc(20.1) 20
FUNCTIONS AND 3.21
POINTERS
3.3.3 String Functions
✤ "string.h" header file supports all the string functions in C language.
All the string functions are given below.

Table 3.3 String Functions

Function Description Example Output

Include the Header file: #include


<string.h> strcat ( ) Concatenates
s2 at the end of s1 s1 = "World "
s2 = "of C"
strcat (s1,s2
)
printf("%s",s1) World of C
strncat ( ) Appends a portion of string to another strncat (s1,s2,2)
printf("%s",s1) World of
strcpy ( ) Copies s2 into s1 strcpy (s1,s2 )
printf("%s",s1) of C
strncpy ( ) Copies given number of strncpy (s1,s2,2 )
characters of one string to another printf("%s",s1) of
strlen ( ) Gives the length of s1 c = strlen(s1)
printf("%d",c) 5
strcmp ( ) Returns 0 if s1 is same as s2. i = strcmp(s1,"World") 0
Returns <0 if s1<s2. printf("%d",i)
Returns >0 if s1>s2 i = strcmp(s1,s2) 1
printf("%d",i)
i = strcmp(s2,s1) 1
printf("%d",i)
strcmpi ( ) Same as strcmp() function. But this i
= strcmp(s1,"WORLD") function negotiates case.
printf("%d",i)
0
strchr ( ) Returns pointer to first occurrence i = strchr(s1,'o')
of char in str1 printf("%d",i) 1
strrchr ( ) Returns the last occurrence of given s1 = "World of
C" character in a string i=
strchr(s1,'o')
printf("%d",i) 6
strstr ( ) Returns pointer to first occurrence s1 = "World of
C" of s2 in s1 i=
strstr(s1,"of")
printf("%d",i) 6
3.22 PROGRAMMING IN C

Functio Descriptio Example Output


n n
Include the Header file: #include
<string.h>
s1 = "Test to Test
strrstr ( ) Returns pointer to last you " i =
occurrence of s2 in s1 strstr(s1,"Test") 8
printf("%d",i)
strdup ( ) Duplicates the
string s1 = "Hello"
s2 = strdup(s1) Hello
printf("%s",s2)
strlwr ( ) Converts string to
lowercase s1 = "Hello" hello
printf("%s",strlwr(s1)
strupr ( Converts string to )
) uppercase HELLO
s1 = "Hello"
strrev ( Reverses the given printf("%s",strupr(s1
) string )) olleH
strset ( Sets all character in a string to s1 = "Hello"
) given character printf("%s",strrev(s ###
1)) ##
strnset ( It sets the portion of characters in
) a string to given character printf("%s",strrev(s1,'#',2))
##llo
Tokenizing given string using
strtok ( ) delimiter s1 = "Hello to all"
printf("%s",strtok(s1,": Hello:to:all
"))

3.4 RECURSION
Recursion is the process of repeating items in a self-similar way. In
programming languages, a function calling itself is called recursive function.
void recursion()
{
recursion(); /* function calls itself */
}
void main()
{
recursion();
}
FUNCTIONS AND 3.23
POINTERS
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.
fact(5)

1 - call fact(5) Step 10 - return 120 (5*24)


Step
5 * fact(4)
Step 9 - return 24 (4*6)
2 - call fact(4)
Step
4 * fact(3) Step 8 - return 6 (3*2)
Step 3 - call fact(3)

3 * fact(2)

4 - call fact(3)
Step Step 7 - return 2 (2*1)
2 * fact(1)
Step 6 - return 2 (2*1)
- call fact(1)
Step 5
1
Fig 3.12 Factorial using Recursion

/* C Program to find Factorial of a given number using


#include
<stdio.h> int
fact(int i)
{
if(i <= 1)
{
return 1;
}
return i * fact(i - 1);
}
void main()
{
int i = 5;
3.24 PROGRAMMING IN C

printf("Factorial = %d", fact(i));


}
Execution:
Output:
Factorial = 120

/* C Program to generate Fibonacci Series using


Example:

1+1=2 13 + 21 = 34
1 3,
1, 1, 2, +2 5,=8,313, 21,
2134,
+ 34
55,=89,
55 144,
233, 377,...
2+3=5 34 + 55 = 89
3+5=8 55 + 89 =
144
5 + 8 = 13 89 + 144 =
233
8 + 13 = 21 144 + 233 =
377

#include
<stdio.h>
intfibonacci(in
t 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));
}
Execution:
Output:
0 1 1 2 3 5 8 13 21 34
FUNCTIONS AND 3.25
POINTERS
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.
3.26 PROGRAMMING IN C

3.4.1 Example programs


Program 1:
Computation of Sine series using Built-in functions.

/* C Program to Compute Sine series using Built-in functions */


3 5 7
x x x
sin x  x    ....
3! 5! 7!
n

1 2n1
x
 
n  0 2n  1!

#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);
FUNCTIONS AND 3.27
POINTERS
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();
}
Execution:
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

Program 2:
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)
3.28 PROGRAMMING IN C

{
int choice, i, a,
b; float x, y,
result;
clrscr();
do
{
printf("\nSelect your operation (0 to exit):\n");
printf("1.Addition\n 2.Subtraction\
n 3.Multiplication\n
4.Division\n");
printf("5. Square root\n6. X ^ Y\n7. X ^ 2\n8. 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);
FUNCTIONS AND 3.29
POINTERS
printf("\nEnter Y:
"); 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;
3.30 PROGRAMMING IN C

case 8:
printf("Enter X: ");
scanf("%f",
&x); result =
pow(x, 3);
printf("\nResult: %f",
result); break;

default:
printf("\nInvalid Choice!");
}
} while(choice);
getch();
}
Execution:
Input:
Select your operation (0 to exit):
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Square
root 6.X^Y
7.X^2
8.X^3
Output:
Choice:
1 Enter
X:5
Enter
Y:4
Result:
9
FUNCTIONS AND 3.31
POINTERS
Program 3:
Binary Search using Recursive functions.

/* C Program to perform Binary Search using Recursive functions*/

Lower Middle Higher

4 5 10 15 20 25 30 35 40 45 50 58 65 80 98

Lower Middle Higher

4 5 10 15 20 25 30 35 40 45 50 58 65 80 98

Lower Middle Higher

4 5 10 15 20 25 30 35 40 45 50 58 65 80 98

Middle
Lower Higher

4 5 10 15 20 25 30 35 40 45 50 58 65 80 98

#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);
3.32 PROGRAMMING IN C

l=0,u=n-1;
c=binary(a,n,m,l,u);
if(c==0)
printf("Number is not
found."); else
printf("Number is found.");
}
int binary(int a[],intn,intm,intl,int u)
{
intmid,c=0;
if(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
c=1;
else if(m<a[mid])
return binary(a,n,m,l,mid-1);
else
return binary(a,n,m,mid+1,u);
}
else
return
c;
}
Execution:
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.
FUNCTIONS AND 3.33
POINTERS
3.5 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.

3.5.1 Pointer Operators


✤ Pointer is a special type of variable used to store the memory location
address of another variable.

100 204
1 7
50
100
var ptr
(normal (pointe
variable) r)

Fig 3.13 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.
Variable name Address Contents

Memory X 2568

Fig 3.14 Effect of declaring a variable

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


Variable name Address Contents

Memory X 2568 32

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


3.34 PROGRAMMING IN C

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,
&marksis 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 *pointerName ;
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 ;
Here, "a" is a normal integer variable and variable "ptr" is an integer
pointer variable.
FUNCTIONS AND 3.35
POINTERS
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
*pointer Variable Name

/* C Program to explain Reference operator (&) and


#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 variable ptr = %u\n", &ptr) ;
}
Execution:
Output:
Address of variable a =
65524 Value of variable a =
10 Address of variable ptr
= 65526

In the above example program, variablea 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.
3.36 PROGRAMMING IN C

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.

/* 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);
}
Execution:
Output:
X is at address = 5482
549 is at address = 5484

/* 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;
FUNCTIONS AND 3.37
POINTERS
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);
}
Execution:
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

3.5.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.
Pointer Pointer Variable
Addres Addres Addres
s s s
Fig 3.16 Pointer to Pointer
3.38 PROGRAMMING IN C

**somewhere_else
*somewhere here

Value

Address

Address

The pointer-to-a-
The pointer contains The variable
pointer contains the
the address of a contains a value.
address of another
variable
pointer

Fig 3.17 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;

/* C program to explain Pointers to Pointers */


#include
<stdio.h> void
main ()
{
intvar;
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 );
FUNCTIONS AND 3.39
POINTERS
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 );
/* take the value using pptr */
printf("Value available at **pptr = %d\n", **pptr);
}
Execution:
Output:
Value of var = 3000
Address of 3000 =
7956
Value available at *ptr =
3000 Address of pointer =
6598
Value available at **pptr =
3000

3.5.3 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.
✤ Adding a number to pointer.
✤ Subtracting a number form a pointer.
✤ Incrementing a pointer.
✤ Decrementing a pointer.
✤ 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))
3.40 PROGRAMMING IN C

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))
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
location4982.

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))
FUNCTIONS AND 3.41
POINTERS
5. Subtracting Pointers
The difference between two pointer returns indicates. It gives the total
number of elements between two pointers. If an integer pointer 'ptr1' points
at memory location 10000 and integer pointer 'ptr2' points at memory location
10008, the result of ptr2 – ptr1 is 2.

/* C 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("After increment 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;
3.42 PROGRAMMING IN C

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);
}

Execution:
Output:
Address of int_var = 2293300
Address of char_var =
2293299 Address of float_var
= 2293292
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

3.6 ARRAYS AND POINTERS


In c programming language, when an array is declared, the compiler
allocates required amount of memory and creates constant pointer with array
name and stores the base address to that pointer. The address of first element
of an array is called as base address of that array.The array name itself acts
as pointer to the first element of that array.
int names[6] ;
For the above declaration, the compiler allocates 12 bytes of memory
and the address of first memory location (i.e., names[0]) is stored in a constant
pointer called names. That means in the above example, names is a pointer
to names[0].

/* C Program to explain Arrays and Pointers */


#include<stdio.h>
void main()
{
FUNCTIONS AND 3.43
POINTERS
intnames[6] = {89, 45, 58, 72, 90, 93} ;
int *ptr ;
ptr =
names ;
printf("Base Address of 'names' array = %u\n", ptr) ;
}
Execution:
Output:
Base Address of 'names' array = 8956

Rules
✤ An array name is a constant pointer.
✤ Array name can be used to access the address and value of all the
elements of that array.
✤ Since array name is a constant pointer we can't modify its value.
Consider the following example statements.
ptr = names + 2 ;
Here, the pointer variable "ptr" is assigned with address of "names[2]"
element.
printf("Address of 'names[4]' = %u",names+4) ;
The above printf statement displays the address of element "names[4]".
printf("Value of 'names[0]' = %d",*names) ;
printf("Value of 'names[3]' = %d",*(names+3)) ;
In the above two statements, first printf statement prints the value 89
(i.e., value of names[0]) and the second printf statement prints the value 72
(i.e., value of names[3]).
names++ ;
The above statement generates compilation error because the array name
acts as a constant pointer. So we can't change its value.
3.44 PROGRAMMING IN C

In the above example program, the array name names can be used as
follows.

Table 3.4

names is same as &names[0] *names is same as names[0]


names + 1 is same as &names[1] *(names + 1) is same as names[1]
names + 2 is same as &names[2] *(names + 2) is same as names[2]
names + 3 is same as &names[3] *(names + 3) is same as names[3]
names + 4 is same as &names[4] *(names + 4) is same as names[4]
names + 5 is same as &names[5] *(names + 5) is same as names[5]

/* C program to explain Arrays and Pointers */


#include
<stdio.h> void
main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p =
&a[0] for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
}
Execution:
Output:
12345
FUNCTIONS AND 3.45
POINTERS

/* C Program to find Sum of numbers using Arrays and


#include
<stdio.h> void
main()
{
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\
n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));
// *(classes + i) is equivalent to
classes[i] sum += *(classes + i);
}
printf("Sum = %d", sum);
}
Execution:
Input
Enter 6 numbers:
2
3
4
5
3
4
Output:
Sum = 21

3.6.1 Pointers to Multi-Dimensional Array


In case of multi-dimensional array also the array name acts as a constant
pointer to the base address of that array.
int marks[3][3];
Here, the array name marks acts as constant pointer to the base address
(address of marks [0][0]) of that array. The element marks[1][2] is accessed
as *(*(marks + 1) + 2).
3.46 PROGRAMMING IN C

3.6.2 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 3.18 Pointers and strings

/* 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++) printf("%s\n", lang[i]);
}
Execution:
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.

3.6.3 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}
FUNCTIONS AND 3.47
POINTERS
It means that the lang is a array containing 3 names, each with a
maximum length of 25 characters (including null character). The total space
needed for the lang array is 60 bytes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
lang[0] C \0
lang[1] C + + \0
lang[2] J a v a \0

Fig 3.19

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.

1 2 3 4 5
lang[0] C \0
lang[1] C + + \0
lang[2] J a v a \0

Fig 3.20

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.
✤ 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.
3.48 PROGRAMMING IN C

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.

3.7 EXAMPLE PROGRAM


Program 1:
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;
inta,b,x;
for(a=0;a<6;a++)
for(b=a+1;b<7;b+
+)
if(*(fruit+a) > *(fruit+b))
{
temp = *(fruit+a);
*(fruit+a) = *(fruit+b);
*(fruit+b) = temp;
}
for(x=0;x<7;x++)
puts(fruit[x]);
}
FUNCTIONS AND 3.49
POINTERS
Execution:
Output:
Apricot
Banana
Pineapple
apple
persimmon
pear
blueberr
y

ADDITIONAL PROGRAMS FROM PREVIOUS QUESTION PAPERS

/* C Program to Compute the Sum of Digits of a given


Example:

Sum of Digits in a Integer


Given
Integer Sum

435 = 4 + 3 + 5 =
12

#include
<stdio.h> void
main()
{
intnum, 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);
3.50 PROGRAMMING IN C

printf("Sum of the digits of %d = %d\n", sum);


}
Execution:
Input:
Enter the
number 167
Output:
Given number = 167
Sum of the digits of 167 = 14

/* C Program to Check if a Given String is Palindrome */


/* Define Palindrome:A string is said to be palindrome if
reverse of the string is same as string. Some palindrome
strings examples are "dad", "radar", "madam" etc.*/
Example:

Eye Poop Ewe Noon Peep

#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(string1[i] != string1[length-i-1])
FUNCTIONS AND 3.51
POINTERS
{
flag = 1;
break;
}
}
if (flag)
printf("%s is not a palindrome\n",
string1); else
printf("%s is a palindrome\n", string1);
}

Execution:
Input:
Enter a string:
12 Enter a
string: dad
Output:
12 is not a
palindrome dad is
a palindrome

/* C program for using


2
recursion, find the sum of the
3
x x
1+ x + + +...........* /
2! 3!
#include
<stdio.h> void
main()
{
int
power(int,int);
int fact(int);
float
sum(int,int);
void main()
{
intx,n;
float f;
printf("Enter the 'x'
value:\n"); scanf("%d",&x);
3.52 PROGRAMMING IN C

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++)
{
s2=power(x,i);
s3=fact(n);
FUNCTIONS AND 3.53
POINTERS
s=s2/s3;
s1=s1+s
;
}
return s1;
}
}
Execution:
Input:
Enter the 'x'
value: 2 Enter the
'n' value: 3
Output:
sum of the series: 1.166667

/* C Program to perform sum = 1+ (1+2) + (1+2+3) + …


#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);
}
Execution:
Input:
Please enter an integer, n =2
Output:
sum = 4
3.54 PROGRAMMING IN C

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


n n +1 2n
Sum of the series: 12 + 22 + 32 +.......n2 =
+1 6
#include
<stdio.h> void
main()
{
intn,i;
int
sum=0;
printf("Enter the n i.e. max values of series:\n ");
scanf("%d",&n);
sum = (n * (n + 1) * (2 * n + 1 )) /
6; printf("Sum of the series : %d\n",
sum);
}
Execution:
Input:
Enter the n i.e. max values of series: 5
Output:
Sum of the series: 55

/* 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()
{
inti,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);
}
FUNCTIONS AND 3.55
POINTERS
Execution:
Input:
Enter value of n: 2
Output:
Sum of the series : 5

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

Sum of the series: 1 + 3 + 5


+ ...n #include <stdio.h>
void main()
{
inti,n,sum=0;
printf("1 + 3 + 5 + …... +
n"); printf("Enter value of
n:\n"); scanf("%d",&n);
for(i=1;i<=n;i+=
2) sum = sum
+ i;
printf("Sum of the series :%d\n",sum);
}
Execution:
Input:
Enter value of n: 9
Output:
Sum of the series : 165

/*C Program to find Factorial of a given number using


#include
<stdio.h> void
main()
{
inti,n = 5;
for (i =1; i < n; i++)
3.56 PROGRAMMING IN C

fact = fact * i
printf("Factorial = %d\n", fact);
}
Execution:
output:
Factorial = 120

/* C Program to find largest and smallest element in an


Example:

Largest and Smallest Element


Given numbers: 56, 213, 5, 98, 902

Smalles Larges
t t
Elemen Elemen
t t
5 902

#inclu <stdio.h
de >
void main()
{
intarr[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); smallest =
find_smallest(arr,size);
printf("\nThesmallest element is: %d\n",smallest);
}
FUNCTIONS AND 3.57
POINTERS
intfind_largest(int arr1[],int size1)
{
intlarge,i;
large=arr1[0];
for(i=1;i<size1;i++)
if(arr1[i] >large)
large =arr1[i];
return(large);
}

intfind_smallest(int arr1[],int size1)


{
intsmall,i;
small=arr1[0];
for(i=1;i<size1;i++)
if(arr1[i] < small)
small =arr1[i];
return(small);
}

Execution:
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
3.58 PROGRAMMING IN C

TWO MARKS QUESTIONS AND ANSWERS


1. What is function?(Nov/Dec 2014)
✤ 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.
2. What are the components of a function? (May/June 2017)
Every function in C has the following.
✤ Function Declaration (Function Prototype)
✤ Function Definition
✤ Function Call
3. Specify the advantages of functions.(May/June 2016, Nov/Dec 2013)
✤ 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 re-usability).
4. How to declare a function?
return type function name(parameters);
✤ Return Type specifies the data type of the value which is sent as a
return value from the function definition.
✤ Function Name is a user defined name used to identify the function
uniquely.
✤ Parameters List is the data values that are sent to the function
definition.
FUNCTIONS AND 3.59
POINTERS
5. Define call by value and call by reference (May/June 2014)
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.
Call by Reference
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.
6. Define Recursion. (May/June 2014)
Recursion is the process of repeating items in a self-similar way. In
programming languages, a function calling itself is called recursive
function.
void recursion()
{
recursion(); /* function calls itself */
}
void main()
{
recursion();
}
3.60 PROGRAMMING IN C

7. Write a C Program to find Factorial of a given number using


Recursion. (May/June 2014)
Program:
#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
8. Write a C Program to generate Fibonacci Series using Recursion
Program:
#include
<stdio.h>
intfibonacci(in
t i)
{
if(i == 0)
return 0;
if(i == 1)
return 1;
returnfibonacci(i-1) + fibonacci(i-2);
}
void main()
{
int i;
FUNCTIONS AND 3.61
POINTERS
for (i = 0; i < 10; i++)
printf("%d\t", fibonacci(i));
}
Output:
0 1 1 2 3 5 8 13 21 34
9. What is a Pointer? What is the use of Pointers? (Nov/Dec 2013)
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.
1 0 . How is pointer arithmetic done? (May/June 2016)
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.
1 1 . What is the use of Pointers?(Nov/Dec 2013 , Nov/Dec 2015)
✤ 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.
✤ 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.
1 2 . Define Actual Parameters and formal parameter (May/June 2015)
✤ Actual Parameters
 The actual parameters are the parameters that are specified in
calling function.
3.62 PROGRAMMING IN C

✤ 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.
1 3 . What is Parameter Passing in C?
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.
1 4 . How the functions are classified in C?
✤ Functions with no arguments and no return value.
✤ Functions with no arguments and with return value
✤ Functions with arguments and no return value.
✤ Functions with arguments and with return value
1 5 . What type of functions available in C?
The C language supports two types of functions.
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
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.
FUNCTIONS AND 3.63
POINTERS
1 6 . What is 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.
1 7 . List the Various Built-In Functions in C.
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 follow.
Header File Purpose Example

stdio.h Provides functions to perform standard I/O operations printf(),

scanf() conio.h Provides functions to perform console I/O

operations clrscr(), getch() string.h Provides

functions to handle string data values strlen(),

strcpy() stdlib.h Provides functions to perform general

functions calloc(), malloc() math.h Provides


18. How to Accessing the Address of Variables in C.
In c programming language, the reference operator "&" is used to access
the address of variable. For example, to access the address of a variable,
&marksis used.
p = &markswould assign the address 5000(location of marks) to the
pointer variable p.
The & operator can be remembered as "address of" operator.
19. What is mean by pointer to pointer?
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
3.64 PROGRAMMING IN C

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.
Pointer Pointer Variable
Addres Addres Addres
s s s
20. Write a C Program to find Factorial of a given number using Iteration.
Program
#include
<stdio.h> void
main()
{
inti,n = 5;
for (i =1; i < n;
i++) fact = fact *
i
printf("Factorial = %d\n", fact);
}
Output:
Factorial = 120

REVIEW QUESTIONS
1. Explain the following with suitable examples.
(i) Function declaration. (8) (ii) Call by reference, call by value. (8)
2. i) Explain function with and without arguments with examples for each. (10)
ii) What is recursion? Give an example. (6)
3. What is a function in C? Discuss about call by value and call by reference
with illustration. (16)
4. What is recursion? Explain a recursion function with suitable example.
Write a iterative and recursive function to find the power of a number. (16)
5. Write in detail about pointer arithmetic. Support your answer with
suitable example. (16)
6. With an example program to explain the pointer to an array and array
of pointer. (16)

You might also like