Unit 4
Saranya K
AP/CSE
SRIT
FUNCTION
 A Function is a sub-program, which contains one or
more statements and it performs some task when its
called.
 A computer program cannot handle all the tasks by it
self. Instead its requests other program like entities –
called functions in C to get its tasks done.
 A function is a self contained block of statements that
perform a coherent task of same kind
Why we use functions?
 Writing functions avoids rewriting the same code over and
over.
 Suppose that there is a section of code in a program that
calculates area of a circle. If later in the program we want to
calculate the area of a different circle, we wont like to write
the same instructions again.
 Instead, we would prefer to jump to a “section of code” that
calculates area and then jump back to the place from where
we left off.
 This section of code is nothing but a function.
 Using functions it becomes easier to write programs and
keep track of what they are doing.
 If the operation of a program can be divided in to separate
activities, and each activity placed in a different function,
then each could be written and checked more or less
independently.
 Separating the code in to modular functions also makes the
pro-gram easier to design and understand.
Why we use functions?
TYPES
 There are two different types of functions:
 Pre-defined functions
 User-defined functions
Pre-Defined Functions
 The pre-defined functions or library functions are
built-in functions.
 The user can use the functions, but cannot modify
those functions.
 Example: sqrt(), main()
User-Defined Functions
 The functions defined by the user for their
requirements are called user-defined functions.
 Whenever it is needed, the user can modify this
function.
 Example: sum(a,b)
Advantage of User-Defined Functions
 The length of the source program can be reduced.
 It is easy to locate errors.
 It avoids coding of repeated instructions.
Elements of User-Defined
Function
 Function declaration
 Function definition
 Function call
Function
 Syntax for function definition
datatype function_name (parameters/arguments list)
{
local variable declaration;
…………………………
body of the function;
…………………………
return(expression);
}
How Function Works?
 Once a function is called the control passes to the
called function.
 The working of calling function is temporarily
stopped.
 When the execution of called function is completed
then the control returns back to the calling function
and executes the next statement.
Parameters
 Actual Parameter
These are the parameters which are transferred from
the calling function to the called function.
 Formal Parameter
These are the parameters which are used in the called
function.
return Statement
 The return statement may or may not send some
values to the calling function.
 Syntax:
return; (or)
return (expression);
Function Prototypes
There are four types:
 Function with no arguments and no return values.
 Function with arguments and no return values.
 Function with arguments and return values.
 Function with no arguments and with return values.
Function with no arguments
and no return values
 Here no data transfer takes place between the calling
function and the called function.
 These functions act independently, i.e. they get input
and display output in the same block.
Example
#include <stdio.h>
#include<conio.h>
void main() //calling function
{
void add();
add();
}
void add() //called function
{
int a,b,c;
printf("nEnter two number:");
scanf("%d%d",&a,&b);
c=a+b;
printf("nSum is:%d",c);
}
Output
Enter two number:3
4
Sum is:7
Function with arguments
and no return values
 Here data transfer take place between the calling
function and the called function.
 It is a one way data communication, i.e. the called
program receives data from calling program but it does
not return any value to the calling program.
Example
#include <stdio.h>
#include<conio.h>
void main()
{
int a,b;
void add(int,int);
printf("nEnter two number:");
scanf("%d%d",&a,&b);
add(a,b);
}
void add(int x,int y) //function with arguments
{
int z;
z=x+y;
printf("nSum is:%d",z);
}
Output
Enter two number:2
4
Sum is:6
Function with arguments
and return values
 Here data transfer takes place between the calling
function and the called function as well as between
called function and calling function .
 It is a two way data communication, i.e. the called
program receives data from calling program and it
returns some value to the calling program.
Example
#include <stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
int add(int,int);
printf("nEnter two number:");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("nSum is:%d",c);
}
int add(int x,int y)
{
int z;
z=x+y;
return(z);
}
Output
Enter two number:6
7
Sum is:13
Function with no arguments
and with return values
 Here data transfer takes place between the called
function and the calling function.
 It is a one way data communication, i.e. the called
program does not any receive data from the calling
program but it returns some value to the calling
program.
Example
#include <stdio.h>
#include<conio.h>
void main()
{
int add(),d;
d=add();
printf("nSum is:%d",d);
}
int add() //function with no argument
{
int a,b,c;
printf("nEnter two number:");
scanf("%d%d",&a,&b);
c=a+b;
return(c);
}
Output
Enter two number:5
8
Sum is:13
Parameter Passing Methods
 There are two different ways of passing parameters to a
method, they are:
 Call by value
 Call by reference
Call by value
 Actual arguments are passed to the formal arguments.
 Any changes made to the formal argument does not
affect the actual argument.
Example
#include <stdio.h>
#include<conio.h>
void main()
{
int x,y,change(int,int);
printf("nEnter value of x:");
scanf("%d",&x);
printf("nEnter value of y:");
scanf("%d",&y);
change(x,y);
printf("nnValues in the
Main()-->x=%d,y=%d",x,y);
}
int change(int a,int b)
{
int c;
c=a;
a=b;
b=c;
printf("nValues in the
Fuction --
>x=%d,y=%d",a,b);
}
Output
Enter value of x:5
Enter value of y:6
Values in the Function -->x=6,y=5
Values in the Main()-->x=5,y=6
Call by reference
 Instead of passing values, the address of the argument
will be passed.
 Any changes made to the formal argument will affect
the actual argument.
Example
#include <stdio.h>
#include<conio.h>
void main()
{
int x,y,change(int*,int*);
printf("nEnter value of
x:");
scanf("%d",&x);
printf("nEnter value of
y:");
scanf("%d",&y);
change(&x,&y);
printf("nnValues in
the Main()--
>x=%d,y=%d",x,y);
}
int change(int *a,int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
printf("nValues in the
Function --
>x=%d,y=%d",*a,*b);
}
Output
Enter value of x:5
Enter value of y:6
Values in the Function -->x=6,y=5
Values in the Main()-->x=6,y=5
Recursion
 It is a process of calling the same function itself again and
again until some condition is satisfied.
Syntax:
func1()
{
………..
func1();
…………
}
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
int rec(int);
printf("nEnter the number:");
scanf("%d",&a);
printf("The factorial of %d! is
%d",a,rec(a));
}
int rec(int x)
{
int f;
if(x==1)
return(1);
else
f=x*rec(x-1);
return(f);
}
Output:
Enter the number:5
The factorial of 5! is 120
Example: Working of 3!
Sum of natural numbers using recursion
#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0;
}
int sum(int n)
{
if (n != 0) // sum() function calls itself
return n + sum(n-1);
else
return n;
}
Library Function
 Library functions are the pre-defined functions.
 The library function provides functions like
mathematical, string manipulation etc,.
 In order to use a library function, it is necessary to call
the appropriate header file at the beginning of the
program.
 The header file informs the program of the name,
type, and number and type of arguments, of all of the
functions contained in the library in question.
 A header file is called via the preprocessor statement.
Some Examples of Library
Functions
 sqrt(x):
It is used to find the square root of x
Example: sqrt(36) is 6
 abs(x):
It is used to find the absolute value of x
Example: abs(-36) is 36
 pow(x,y):
It is used to find the value of xy
Example: pow(5,2) is 25
 ceil(x):
It is used to find the smallest integer greater than or equal to x.
Example: ceil(7.7) is 8
 floor(x):
returns the largest integer value less than or equal to x.
example: floor(7.5) is 6
 rand():
It is used to generate a random number.
 sin(x):
It is used to find the sine value of x
Example: sin(30) is 0.5
 cos (x):
It is used to find the cosine value of x
Example: cos(30) is 0.86
 tan(x):
It is used to find the tan value of x
Example: tan(30) is 0.577
 toascii(x):
It is used to find the ASCII value of x
Example: toascii(a) is 97
 toupper(x):
It is used to convert lowercase character to uppercase.
Example: toupper(‘a’) is A
 tolower(x):
It is used to convert uppercase character to lowercase.
Example: tolower(‘A’) is a
Example:
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<ctype.h>
void main()
{
int x,y=2;
printf("nEnter the number:");
scanf("%d",&x);
printf("nThe square root of %d is %f",x,sqrt(x));
printf("nThe value of %d power%dis%f ",x,y,pow(6,2));
printf("nThe ceiling of 6.7 is %f",ceil(6.7));
printf("nThe floor of 6.7 is %f",floor(6.7));
printf("nThe absolute value of -6 is %d",abs(-6));
printf("nThe value of sin 45 is %f",sin(45));
printf("nThe uppercase of 'a' is %c",toupper('a'));
printf("nThe uppercase of 97 is %c",toupper(97));
getch();
}
Output:
Enter the number:6
The square root of 6 is 2.449490
The value of 6 power 2 is 36.000000
The ceiling of 6.7 is 7.000000
The floor of 6.7 is 6.000000
The absolute value of -6 is 6
The value of sin 45 is 0.850904
The uppercase of 'a' is A
The uppercase of 97 is A
Computation of Sine Series
#include<stdio.h>
#include<conio.h>
void main()
{
int i, n;
float x, sum, t;
printf(" Enter the value for x : ");
scanf("%f",&x);
x=x*3.14159/180;
t=x;
sum=x;
/* Loop to calculate the value of Sine */
for(i=1;i<=n;i++)
{
t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
}
printf(" The value of Sin(%f) = %.4f",x,sum);
}
Random Number Generation
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Generates and prints 'count' random
// numbers in range [lower, upper].
void printRandoms(int lower, int upper, int count)
{
int i;
for (i = 0; i < count; i++) {
int num = (rand() %(upper - lower + 1)) + lower;
printf("%d ", num);
int main()
{
int lower = 10, upper = 20, count = 1;
// Use current time as
// seed for random generator
srand(time(0));
printRandoms(lower, upper, count);
return 0;
}
Towers of Hanoi
#include<stdio.h>
void TOH(int n,char x,char y,char z)
{
if(n>0)
{
TOH(n-1,x,z,y);
printf("n%c to %c",x,y);
TOH(n-1,z,y,x);
}
}
int main()
{
int n=3;
TOH(n,'A','B','C');
}
Output
A to B
A to C
B to C
A to B
C to A
C to B
A to B
Pointers
 Pointer is a variable that contains the address of
another variable i.e.. direct address of the memory
location.
 Like any variable or constant, you must declare a
pointer before you can use it to store any variable
address.
Example:
x=5
x Variable
1002 Address
5 Value
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int x=5;
printf("n The Address of x = %u",&x);
printf("n The Value of x = %d",x);
}
Output
The Address of x = 8714
The Value of x = 5
Pointer Declaration
 Syntax:
data-type *pointer-name;
data-type - Type of the data to
which the pointer points.
pointer-name - Name of the pointer
 Example: int *a;
Accessing Variable through Pointer
 If a pointer is declared and assigned to a variable, then
the variable can be accessed through the pointer.
 Example:
int *a;
x=5;
a=&x;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int y=10;
int *a;
a=&y;
printf("n The Value of y = %d",y);
printf("n The Address of y = %u",&y);
printf("n The Value of a = %d",a);
printf("n The Address of a = %u",&a);
}
Illustration of the example:
5001 10
8000
a y
5001
Variable
Value
Address
Output
The Value of y = 10
The Address of y = 5001
The Value of a = 5001
The Address of a = 8000
Null Pointer
 A pointer is said to be null pointer if zero is assigned to
the pointer.
 For Example:
int *a,*b;
a=b=0;
Pointer to Pointer
 Here one pointer stores the address of another pointer
variable.
 Example:
int x=10,*a,**b;
a=&x;
b=&a;
 Illustration:
5001 10
8000
a x
5001
Variable
Value
Address
8000
9000
b
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
int *b,**c;
b=&a;
c=&b;
printf("n The Value of a = %d",a);
printf("n The Address of a = %u",&a);
printf("n The Value of b = %d",b);
printf("n The Address of b = %u",&b);
printf("n The Value of c = %d",c);
printf("n The Address of c = %u",&c);
}
Output
The Value of a = 10
The Address of a = 5001
The Value of b = 5001
The Address of b = 8000
The Value of c = 8000
The Address of c = 9000
Pointers and Arrays
 The elements of the array can also be accessed through
a pointer.
 Example
int a[3]={2,3,7};
int *b;
b=a;
Example 1
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3]={2,3,7};
int *b;
b=a;
printf("n The Value of a[0] = %d",a[0]);
printf("n The Address of a[0] = %u",&a[0]);
printf("n The Value of b = %d",b);
}
 Illustration of the example:
8744 2
9000
b a[0]
8744
Variable
Value
Address
Output
The Value of a[0] = 2
The Address of a[0] = 8744
The Value of b = 8744
Example 2
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={2,3,7,9,10};
int i;
for(i=0;i<5;i++)
{
printf("n The Value of a[%d] = %d",i,a[i]);
printf("n The Address of a[%d] = %u",i,&a[i]);
}
}
Illustration of the example:
2 3 7 9 10
a[0] a[1] a[2] a[3] a[4]
8724 8726 8728 8730 8732
Array
Value
Address
Output
The Value of a[0] = 2
The Address of a[0] = 8724
The Value of a[1] = 3
The Address of a[1] = 8726
The Value of a[2] = 7
The Address of a[2] = 8728
The Value of a[3] = 9
The Address of a[3] = 8730
The Value of a[4] = 10
The Address of a[4] = 8732
Example 3
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={1,2,3,4,5};
int i,sum=0;
int *b;
b=a;
for(i=0;i<5;i++)
{
sum=sum + *b;
b++; //b=b+1
}
printf("n The Sum is %d",sum);
}
Output
The Sum is 15
Pointer Arithmetic
 A pointer in c is an address, which is a numeric value.
 Therefore, you can perform arithmetic operations on a
pointer just as you can on a numeric value.
 here are four arithmetic operators that can be used on
pointers: ++, --, +, and –
 To understand pointer arithmetic, let us consider
that ptr is an integer pointer which points to the
address 1000. Assuming 32-bit integers, let us perform
the following arithmetic operation on the pointer −
ptr++
 After the above operation, the ptr will point to the
location 1004 because each time ptr is incremented, it
will point to the next integer location which is 4 bytes
next to the current location. This operation will move
the pointer to the next memory location without
impacting the actual value at the memory location.
If ptr points to a character whose address is 1000, then
the above operation will point to the location 1001
because the next character will be available at 1001.
Incrementing a Pointer
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr; /* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++)
{
printf("Address of var[%d] = %xn", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr ); /* move to the next location */
ptr++;
}
return 0;
}
Decrementing a pointer
Dynamic Memory Allocation
 Since C is a structured language, it has some fixed
rules for programming.
 One of it includes changing the size of an array.
 An array is collection of items stored at continuous
memory locations.
If there is a requirement to change this length (size). For
Example,
 If there is a situation where only 5 elements are needed
to be entered in this array. In this case, the remaining 4
indices are just wasting memory in this array. So there
is a requirement to lessen the length (size) of the array
from 9 to 5.
 Take another situation. In this, there is an array of 9
elements with all 9 indices filled. But there is a need to
enter 3 more elements in this array. In this case 3
indices more are required. So the length (size) of the
array needs to be changed from 9 to 12.
 This procedure is referred to as Dynamic Memory
Allocation in C.
 Therefore, C Dynamic Memory Allocation can be
defined as a procedure in which the size of a data
structure (like Array) is changed during the runtime.
 C provides some functions to achieve these tasks.
There are 4 library functions provided by C defined
under <stdlib.h> header file to facilitate dynamic
memory allocation in C programming. They are:
 malloc()
 calloc()
 free()
 realloc()

malloc()
 “malloc” or “memory allocation” method in C is
used to dynamically allocate a single large block of
memory with the specified size.
 It returns a pointer of type void which can be cast into
a pointer of any form.
 It initializes each block with default garbage value.
 Syntax
ptr = (cast-type*) malloc(byte-size)
Example:
ptr = (int*) malloc(100 * sizeof(int));
Note:
 If space is insufficient, allocation fails and returns a
NULL pointer.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
Calloc()
 “calloc” or “contiguous allocation” method in C
is used to dynamically allocate the specified
number of blocks of memory of the specified type.
It initializes each block with a default value ‘0’.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
For Example:
ptr = (float*) calloc(25, sizeof(float));
 This statement allocates contiguous space in
memory for 25 elements each with the size of the
float.
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by calloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0; }
cfree()
 “free” method in C is used to dynamically de-allocate the memory.
 The memory allocated using functions malloc() and calloc() is not de-
allocated on their own.
 Hence the free() method is used, whenever the dynamic memory
allocation takes place. It helps to reduce wastage of memory by freeing it.
Syntax:
free(ptr);
Program
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Dynamically allocate memory using calloc()
ptr1 = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.n");
// Free the memory
free(ptr);
printf("Malloc Memory successfully freed.n");
// Memory has been successfully allocated
printf("nMemory successfully allocated using calloc.n");
// Free the memory
free(ptr1);
printf("Calloc Memory successfully freed.n");
}
return 0;
}
realloc()
 “realloc” or “re-allocation” method in C is used to
dynamically change the memory allocation of a
previously allocated memory.
 In other words, if the memory previously allocated with
the help of malloc or calloc is insufficient, realloc can be
used to dynamically re-allocate memory.
 re-allocation of memory maintains the already present
value and new blocks will be initialized with default
garbage value.
Syntax:
ptr = realloc(ptr, newSize); where ptr is reallocated with new
size 'newSize'.
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
// Get the new size for the array
n = 10;
printf("nnEnter the new size of the array: %dn", n);
// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));
// Memory has been successfully allocated
printf("Memory successfully re-allocated using
realloc.n");
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}
Card Shuffling and Dealing Simulation
 Collection of playing cards is known as deck
 A deck of card contains 52 cards.
 There are 4 suits and each 4 suits contains 13 faces
 The 4 suits are
 Hearts, Diamonds, Clubs, Spades
The 13 faces are
Ace, Deuce, Three, Four, Five, Six, Seven, Eight, Nine,
Ten, Jack, Queen, King
Program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h> /*…Used to count time …*/
void shuffle( int [][ 13 ] );
void deal( const int [][ 13 ], const char *[], const char *[] );
void main()
{
const char *suit[ 4 ] = { “Hearts”, “Diamonds”, “Clubs”, “Spades” };
const char *face[ 13 ] = { “Ace”, “Deuce”, “Three”, “Four”, “Five”, “Six”,
“Seven”, “Eight”, “Nine”, “Ten”, “Jack”, “Queen”, “King” };
int deck[ 4 ][ 13 ] = { 0 };
srand( time( 0 ) );
shuffle( deck );
deal( deck, face, suit );
} /*…Main Function Ends..*/
void shuffle( int wDeck[][ 13 ] ) /*….Function Definition…*/
{
int row, column, card;
for ( card = 1; card <= 52; card++ )
{
do {
row = rand() % 4;
column = rand() % 13;
} while( wDeck[ row ][ column ] != 0 );
wDeck[ row ][ column ] = card;
}
} /*…Loop End’s…*/
void deal( const int wDeck[][ 13 ], const char *wFace[],const char *wSuit[] )
{
int card, row, column;
for ( card = 1; card <= 52; card++ )
for ( row = 0; row <= 3; row++ )
for ( column = 0; column <= 12; column++ )
if ( wDeck[ row ][ column ] == card )
printf( “%5s of %-8s%c”,
wFace[ column ], wSuit[ row ],
card % 2 == 0 ? ‘n’ : ‘t’ );
}
Functions and pointers_unit_4

Functions and pointers_unit_4

  • 1.
  • 2.
    FUNCTION  A Functionis a sub-program, which contains one or more statements and it performs some task when its called.  A computer program cannot handle all the tasks by it self. Instead its requests other program like entities – called functions in C to get its tasks done.  A function is a self contained block of statements that perform a coherent task of same kind
  • 3.
    Why we usefunctions?  Writing functions avoids rewriting the same code over and over.  Suppose that there is a section of code in a program that calculates area of a circle. If later in the program we want to calculate the area of a different circle, we wont like to write the same instructions again.  Instead, we would prefer to jump to a “section of code” that calculates area and then jump back to the place from where we left off.  This section of code is nothing but a function.
  • 4.
     Using functionsit becomes easier to write programs and keep track of what they are doing.  If the operation of a program can be divided in to separate activities, and each activity placed in a different function, then each could be written and checked more or less independently.  Separating the code in to modular functions also makes the pro-gram easier to design and understand. Why we use functions?
  • 5.
    TYPES  There aretwo different types of functions:  Pre-defined functions  User-defined functions
  • 6.
    Pre-Defined Functions  Thepre-defined functions or library functions are built-in functions.  The user can use the functions, but cannot modify those functions.  Example: sqrt(), main()
  • 7.
    User-Defined Functions  Thefunctions defined by the user for their requirements are called user-defined functions.  Whenever it is needed, the user can modify this function.  Example: sum(a,b)
  • 8.
    Advantage of User-DefinedFunctions  The length of the source program can be reduced.  It is easy to locate errors.  It avoids coding of repeated instructions.
  • 9.
    Elements of User-Defined Function Function declaration  Function definition  Function call
  • 10.
    Function  Syntax forfunction definition datatype function_name (parameters/arguments list) { local variable declaration; ………………………… body of the function; ………………………… return(expression); }
  • 11.
    How Function Works? Once a function is called the control passes to the called function.  The working of calling function is temporarily stopped.  When the execution of called function is completed then the control returns back to the calling function and executes the next statement.
  • 13.
    Parameters  Actual Parameter Theseare the parameters which are transferred from the calling function to the called function.  Formal Parameter These are the parameters which are used in the called function.
  • 15.
    return Statement  Thereturn statement may or may not send some values to the calling function.  Syntax: return; (or) return (expression);
  • 16.
    Function Prototypes There arefour types:  Function with no arguments and no return values.  Function with arguments and no return values.  Function with arguments and return values.  Function with no arguments and with return values.
  • 17.
    Function with noarguments and no return values  Here no data transfer takes place between the calling function and the called function.  These functions act independently, i.e. they get input and display output in the same block.
  • 19.
    Example #include <stdio.h> #include<conio.h> void main()//calling function { void add(); add(); } void add() //called function { int a,b,c; printf("nEnter two number:"); scanf("%d%d",&a,&b); c=a+b; printf("nSum is:%d",c); }
  • 20.
  • 21.
    Function with arguments andno return values  Here data transfer take place between the calling function and the called function.  It is a one way data communication, i.e. the called program receives data from calling program but it does not return any value to the calling program.
  • 23.
    Example #include <stdio.h> #include<conio.h> void main() { inta,b; void add(int,int); printf("nEnter two number:"); scanf("%d%d",&a,&b); add(a,b); } void add(int x,int y) //function with arguments { int z; z=x+y; printf("nSum is:%d",z); }
  • 24.
  • 25.
    Function with arguments andreturn values  Here data transfer takes place between the calling function and the called function as well as between called function and calling function .  It is a two way data communication, i.e. the called program receives data from calling program and it returns some value to the calling program.
  • 27.
    Example #include <stdio.h> #include<conio.h> void main() { inta,b,c; int add(int,int); printf("nEnter two number:"); scanf("%d%d",&a,&b); c=add(a,b); printf("nSum is:%d",c); } int add(int x,int y) { int z; z=x+y; return(z); }
  • 28.
  • 29.
    Function with noarguments and with return values  Here data transfer takes place between the called function and the calling function.  It is a one way data communication, i.e. the called program does not any receive data from the calling program but it returns some value to the calling program.
  • 31.
    Example #include <stdio.h> #include<conio.h> void main() { intadd(),d; d=add(); printf("nSum is:%d",d); } int add() //function with no argument { int a,b,c; printf("nEnter two number:"); scanf("%d%d",&a,&b); c=a+b; return(c); }
  • 32.
  • 33.
    Parameter Passing Methods There are two different ways of passing parameters to a method, they are:  Call by value  Call by reference
  • 34.
    Call by value Actual arguments are passed to the formal arguments.  Any changes made to the formal argument does not affect the actual argument.
  • 35.
    Example #include <stdio.h> #include<conio.h> void main() { intx,y,change(int,int); printf("nEnter value of x:"); scanf("%d",&x); printf("nEnter value of y:"); scanf("%d",&y); change(x,y); printf("nnValues in the Main()-->x=%d,y=%d",x,y); } int change(int a,int b) { int c; c=a; a=b; b=c; printf("nValues in the Fuction -- >x=%d,y=%d",a,b); }
  • 36.
    Output Enter value ofx:5 Enter value of y:6 Values in the Function -->x=6,y=5 Values in the Main()-->x=5,y=6
  • 37.
    Call by reference Instead of passing values, the address of the argument will be passed.  Any changes made to the formal argument will affect the actual argument.
  • 38.
    Example #include <stdio.h> #include<conio.h> void main() { intx,y,change(int*,int*); printf("nEnter value of x:"); scanf("%d",&x); printf("nEnter value of y:"); scanf("%d",&y); change(&x,&y); printf("nnValues in the Main()-- >x=%d,y=%d",x,y); } int change(int *a,int *b) { int c; c=*a; *a=*b; *b=c; printf("nValues in the Function -- >x=%d,y=%d",*a,*b); }
  • 39.
    Output Enter value ofx:5 Enter value of y:6 Values in the Function -->x=6,y=5 Values in the Main()-->x=6,y=5
  • 40.
    Recursion  It isa process of calling the same function itself again and again until some condition is satisfied. Syntax: func1() { ……….. func1(); ………… }
  • 41.
    Example #include<stdio.h> #include<conio.h> void main() { int a; intrec(int); printf("nEnter the number:"); scanf("%d",&a); printf("The factorial of %d! is %d",a,rec(a)); } int rec(int x) { int f; if(x==1) return(1); else f=x*rec(x-1); return(f); } Output: Enter the number:5 The factorial of 5! is 120
  • 42.
  • 43.
    Sum of naturalnumbers using recursion #include <stdio.h> int sum(int n); int main() { int number, result; printf("Enter a positive integer: "); scanf("%d", &number); result = sum(number); printf("sum = %d", result); return 0; }
  • 44.
    int sum(int n) { if(n != 0) // sum() function calls itself return n + sum(n-1); else return n; }
  • 45.
    Library Function  Libraryfunctions are the pre-defined functions.  The library function provides functions like mathematical, string manipulation etc,.  In order to use a library function, it is necessary to call the appropriate header file at the beginning of the program.  The header file informs the program of the name, type, and number and type of arguments, of all of the functions contained in the library in question.  A header file is called via the preprocessor statement.
  • 46.
    Some Examples ofLibrary Functions  sqrt(x): It is used to find the square root of x Example: sqrt(36) is 6  abs(x): It is used to find the absolute value of x Example: abs(-36) is 36  pow(x,y): It is used to find the value of xy Example: pow(5,2) is 25
  • 47.
     ceil(x): It isused to find the smallest integer greater than or equal to x. Example: ceil(7.7) is 8  floor(x): returns the largest integer value less than or equal to x. example: floor(7.5) is 6  rand(): It is used to generate a random number.  sin(x): It is used to find the sine value of x Example: sin(30) is 0.5  cos (x): It is used to find the cosine value of x Example: cos(30) is 0.86
  • 48.
     tan(x): It isused to find the tan value of x Example: tan(30) is 0.577  toascii(x): It is used to find the ASCII value of x Example: toascii(a) is 97  toupper(x): It is used to convert lowercase character to uppercase. Example: toupper(‘a’) is A  tolower(x): It is used to convert uppercase character to lowercase. Example: tolower(‘A’) is a
  • 49.
    Example: #include<stdio.h> #include<conio.h> #include<math.h> #include<ctype.h> void main() { int x,y=2; printf("nEnterthe number:"); scanf("%d",&x); printf("nThe square root of %d is %f",x,sqrt(x)); printf("nThe value of %d power%dis%f ",x,y,pow(6,2)); printf("nThe ceiling of 6.7 is %f",ceil(6.7)); printf("nThe floor of 6.7 is %f",floor(6.7));
  • 50.
    printf("nThe absolute valueof -6 is %d",abs(-6)); printf("nThe value of sin 45 is %f",sin(45)); printf("nThe uppercase of 'a' is %c",toupper('a')); printf("nThe uppercase of 97 is %c",toupper(97)); getch(); }
  • 51.
    Output: Enter the number:6 Thesquare root of 6 is 2.449490 The value of 6 power 2 is 36.000000 The ceiling of 6.7 is 7.000000 The floor of 6.7 is 6.000000 The absolute value of -6 is 6 The value of sin 45 is 0.850904 The uppercase of 'a' is A The uppercase of 97 is A
  • 52.
    Computation of SineSeries #include<stdio.h> #include<conio.h> void main() { int i, n; float x, sum, t; printf(" Enter the value for x : "); scanf("%f",&x); x=x*3.14159/180; t=x; sum=x;
  • 53.
    /* Loop tocalculate the value of Sine */ for(i=1;i<=n;i++) { t=(t*(-1)*x*x)/(2*i*(2*i+1)); sum=sum+t; } printf(" The value of Sin(%f) = %.4f",x,sum); }
  • 54.
    Random Number Generation #include<stdio.h> #include <stdlib.h> #include <time.h> // Generates and prints 'count' random // numbers in range [lower, upper]. void printRandoms(int lower, int upper, int count) { int i; for (i = 0; i < count; i++) { int num = (rand() %(upper - lower + 1)) + lower; printf("%d ", num);
  • 55.
    int main() { int lower= 10, upper = 20, count = 1; // Use current time as // seed for random generator srand(time(0)); printRandoms(lower, upper, count); return 0; }
  • 56.
  • 57.
    #include<stdio.h> void TOH(int n,charx,char y,char z) { if(n>0) { TOH(n-1,x,z,y); printf("n%c to %c",x,y); TOH(n-1,z,y,x); } } int main() { int n=3; TOH(n,'A','B','C'); }
  • 58.
    Output A to B Ato C B to C A to B C to A C to B A to B
  • 59.
    Pointers  Pointer isa variable that contains the address of another variable i.e.. direct address of the memory location.  Like any variable or constant, you must declare a pointer before you can use it to store any variable address.
  • 60.
  • 61.
    Example #include<stdio.h> #include<conio.h> void main() { int x=5; printf("nThe Address of x = %u",&x); printf("n The Value of x = %d",x); } Output The Address of x = 8714 The Value of x = 5
  • 62.
    Pointer Declaration  Syntax: data-type*pointer-name; data-type - Type of the data to which the pointer points. pointer-name - Name of the pointer  Example: int *a;
  • 63.
    Accessing Variable throughPointer  If a pointer is declared and assigned to a variable, then the variable can be accessed through the pointer.  Example: int *a; x=5; a=&x;
  • 64.
    Example #include<stdio.h> #include<conio.h> void main() { int y=10; int*a; a=&y; printf("n The Value of y = %d",y); printf("n The Address of y = %u",&y); printf("n The Value of a = %d",a); printf("n The Address of a = %u",&a); }
  • 65.
    Illustration of theexample: 5001 10 8000 a y 5001 Variable Value Address
  • 66.
    Output The Value ofy = 10 The Address of y = 5001 The Value of a = 5001 The Address of a = 8000
  • 67.
    Null Pointer  Apointer is said to be null pointer if zero is assigned to the pointer.  For Example: int *a,*b; a=b=0;
  • 68.
    Pointer to Pointer Here one pointer stores the address of another pointer variable.  Example: int x=10,*a,**b; a=&x; b=&a;
  • 69.
     Illustration: 5001 10 8000 ax 5001 Variable Value Address 8000 9000 b
  • 70.
    Example #include<stdio.h> #include<conio.h> void main() { int a=10; int*b,**c; b=&a; c=&b; printf("n The Value of a = %d",a); printf("n The Address of a = %u",&a); printf("n The Value of b = %d",b); printf("n The Address of b = %u",&b); printf("n The Value of c = %d",c); printf("n The Address of c = %u",&c); }
  • 71.
    Output The Value ofa = 10 The Address of a = 5001 The Value of b = 5001 The Address of b = 8000 The Value of c = 8000 The Address of c = 9000
  • 72.
    Pointers and Arrays The elements of the array can also be accessed through a pointer.  Example int a[3]={2,3,7}; int *b; b=a;
  • 73.
    Example 1 #include<stdio.h> #include<conio.h> void main() { inta[3]={2,3,7}; int *b; b=a; printf("n The Value of a[0] = %d",a[0]); printf("n The Address of a[0] = %u",&a[0]); printf("n The Value of b = %d",b); }
  • 74.
     Illustration ofthe example: 8744 2 9000 b a[0] 8744 Variable Value Address
  • 75.
    Output The Value ofa[0] = 2 The Address of a[0] = 8744 The Value of b = 8744
  • 76.
    Example 2 #include<stdio.h> #include<conio.h> void main() { inta[5]={2,3,7,9,10}; int i; for(i=0;i<5;i++) { printf("n The Value of a[%d] = %d",i,a[i]); printf("n The Address of a[%d] = %u",i,&a[i]); } }
  • 77.
    Illustration of theexample: 2 3 7 9 10 a[0] a[1] a[2] a[3] a[4] 8724 8726 8728 8730 8732 Array Value Address
  • 78.
    Output The Value ofa[0] = 2 The Address of a[0] = 8724 The Value of a[1] = 3 The Address of a[1] = 8726 The Value of a[2] = 7 The Address of a[2] = 8728 The Value of a[3] = 9 The Address of a[3] = 8730 The Value of a[4] = 10 The Address of a[4] = 8732
  • 79.
    Example 3 #include<stdio.h> #include<conio.h> void main() { inta[5]={1,2,3,4,5}; int i,sum=0; int *b; b=a; for(i=0;i<5;i++) { sum=sum + *b; b++; //b=b+1 } printf("n The Sum is %d",sum); }
  • 80.
  • 81.
    Pointer Arithmetic  Apointer in c is an address, which is a numeric value.  Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value.  here are four arithmetic operators that can be used on pointers: ++, --, +, and –  To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer −
  • 82.
    ptr++  After theabove operation, the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer location which is 4 bytes next to the current location. This operation will move the pointer to the next memory location without impacting the actual value at the memory location. If ptr points to a character whose address is 1000, then the above operation will point to the location 1001 because the next character will be available at 1001.
  • 83.
    Incrementing a Pointer #include<stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have array address in pointer */ ptr = var; for ( i = 0; i < MAX; i++) { printf("Address of var[%d] = %xn", i, ptr ); printf("Value of var[%d] = %dn", i, *ptr ); /* move to the next location */ ptr++; } return 0; }
  • 84.
  • 85.
    Dynamic Memory Allocation Since C is a structured language, it has some fixed rules for programming.  One of it includes changing the size of an array.  An array is collection of items stored at continuous memory locations.
  • 86.
    If there isa requirement to change this length (size). For Example,  If there is a situation where only 5 elements are needed to be entered in this array. In this case, the remaining 4 indices are just wasting memory in this array. So there is a requirement to lessen the length (size) of the array from 9 to 5.  Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there is a need to enter 3 more elements in this array. In this case 3 indices more are required. So the length (size) of the array needs to be changed from 9 to 12.  This procedure is referred to as Dynamic Memory Allocation in C.
  • 87.
     Therefore, CDynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime.  C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are:  malloc()  calloc()  free()  realloc() 
  • 88.
    malloc()  “malloc” or“memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size.  It returns a pointer of type void which can be cast into a pointer of any form.  It initializes each block with default garbage value.  Syntax ptr = (cast-type*) malloc(byte-size) Example: ptr = (int*) malloc(100 * sizeof(int));
  • 90.
    Note:  If spaceis insufficient, allocation fails and returns a NULL pointer.
  • 91.
    #include <stdio.h> #include <stdlib.h> intmain() { // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %dn", n); // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL) { printf("Memory not allocated.n"); exit(0);
  • 92.
    } else { // Memoryhas been successfully allocated printf("Memory successfully allocated using malloc.n"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0; }
  • 93.
    Output: Enter number ofelements: 5 Memory successfully allocated using malloc. The elements of the array are: 1, 2, 3, 4, 5,
  • 94.
    Calloc()  “calloc” or“contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each block with a default value ‘0’. Syntax: ptr = (cast-type*)calloc(n, element-size); For Example: ptr = (float*) calloc(25, sizeof(float));  This statement allocates contiguous space in memory for 25 elements each with the size of the float.
  • 96.
    Program: #include <stdio.h> #include <stdlib.h> intmain() { // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %dn", n); // Dynamically allocate memory using calloc() ptr = (int*)calloc(n, sizeof(int)); // Check if the memory has been successfully // allocated by calloc or not if (ptr == NULL) {
  • 97.
    printf("Memory not allocated.n"); exit(0); } else{ // Memory has been successfully allocated printf("Memory successfully allocated using calloc.n"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0; }
  • 98.
    cfree()  “free” methodin C is used to dynamically de-allocate the memory.  The memory allocated using functions malloc() and calloc() is not de- allocated on their own.  Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. Syntax: free(ptr);
  • 99.
    Program #include <stdio.h> #include <stdlib.h> intmain() { // This pointer will hold the // base address of the block created int *ptr, *ptr1; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %dn", n); // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Dynamically allocate memory using calloc() ptr1 = (int*)calloc(n, sizeof(int));
  • 100.
    // Check ifthe memory has been successfully // allocated by malloc or not if (ptr == NULL || ptr1 == NULL) { printf("Memory not allocated.n"); exit(0); } else { // Memory has been successfully allocated printf("Memory successfully allocated using malloc.n"); // Free the memory free(ptr); printf("Malloc Memory successfully freed.n"); // Memory has been successfully allocated printf("nMemory successfully allocated using calloc.n");
  • 101.
    // Free thememory free(ptr1); printf("Calloc Memory successfully freed.n"); } return 0; }
  • 102.
    realloc()  “realloc” or“re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory.  In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.  re-allocation of memory maintains the already present value and new blocks will be initialized with default garbage value. Syntax: ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.
  • 104.
    Program: #include <stdio.h> #include <stdlib.h> intmain() { // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %dn", n); // Dynamically allocate memory using calloc() ptr = (int*)calloc(n, sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not
  • 105.
    if (ptr ==NULL) { printf("Memory not allocated.n"); exit(0); } else { // Memory has been successfully allocated printf("Memory successfully allocated using calloc.n"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); }
  • 106.
    // Get thenew size for the array n = 10; printf("nnEnter the new size of the array: %dn", n); // Dynamically re-allocate memory using realloc() ptr = realloc(ptr, n * sizeof(int)); // Memory has been successfully allocated printf("Memory successfully re-allocated using realloc.n"); // Get the new elements of the array for (i = 5; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); }
  • 107.
  • 108.
    Card Shuffling andDealing Simulation  Collection of playing cards is known as deck  A deck of card contains 52 cards.  There are 4 suits and each 4 suits contains 13 faces  The 4 suits are  Hearts, Diamonds, Clubs, Spades The 13 faces are Ace, Deuce, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King
  • 109.
    Program: #include <stdio.h> #include <stdlib.h> #include<time.h> /*…Used to count time …*/ void shuffle( int [][ 13 ] ); void deal( const int [][ 13 ], const char *[], const char *[] ); void main() { const char *suit[ 4 ] = { “Hearts”, “Diamonds”, “Clubs”, “Spades” }; const char *face[ 13 ] = { “Ace”, “Deuce”, “Three”, “Four”, “Five”, “Six”, “Seven”, “Eight”, “Nine”, “Ten”, “Jack”, “Queen”, “King” }; int deck[ 4 ][ 13 ] = { 0 }; srand( time( 0 ) ); shuffle( deck ); deal( deck, face, suit ); } /*…Main Function Ends..*/
  • 110.
    void shuffle( intwDeck[][ 13 ] ) /*….Function Definition…*/ { int row, column, card; for ( card = 1; card <= 52; card++ ) { do { row = rand() % 4; column = rand() % 13; } while( wDeck[ row ][ column ] != 0 ); wDeck[ row ][ column ] = card; } } /*…Loop End’s…*/
  • 111.
    void deal( constint wDeck[][ 13 ], const char *wFace[],const char *wSuit[] ) { int card, row, column; for ( card = 1; card <= 52; card++ ) for ( row = 0; row <= 3; row++ ) for ( column = 0; column <= 12; column++ ) if ( wDeck[ row ][ column ] == card ) printf( “%5s of %-8s%c”, wFace[ column ], wSuit[ row ], card % 2 == 0 ? ‘n’ : ‘t’ ); }