Cs8151 Unit III Notes
Cs8151 Unit III Notes
4.1 Functions
A function is a subprogram of one or more statements that performs a specific task
when called.
Advantages of Functions:
1. Code reusability
2. Better readability
3. Reduction in code redundancy
4. Easy to debug & test.
Classification of functions:
Based on who develops the function
Based on the number of arguments a function accepts
1. Based on who develops the function
There are two types.
1. Library functions
2. User-defined functions
1. Library functions [Built-in functions]
Library functions are predefined functions. These functions are already developed by
someone and are available to the user for use. Ex. printf( ), scanf( ).
2. User-defined functions
User-defined functions are defined by the user at the time of writing a program. Ex.
sum( ), square( )
a) Return type – data type of return value. It can be int, float, double, char, void etc.
b) Function name – name of the function
c) Parameter type list –It is a comma separated list of parameter types. Parameter names
are optional.
Ex: int add(int, int);
or
int add(int x, int y);
statements;
return (value);
}
4.4 FUNCTION CALL:
A function can be called by using its name & actual parameters.
It should be terminated by a semicolon ( ; ).
4.4.1. Working of a function
void main()
{
int x,y,z;
int abc(int, int, int) // Function declaration
…..
…..
abc(x,y,z) // Function Call
… Actual arguments
…
}
{ Formal arguments
…….
….
return (value);
}
Calling function – The function that calls a function is known as a calling function.
Called function – The function that has been called is known as a called function.
Actual arguments – The arguments of the calling function are called as actual arguments.
Formal arguments – The arguments of called function are called as formal arguments.
#include<stdio.h>
void main()
{
void show( );
show( );
} No arguments are passed.
No values are sent back.
void show( )
{
printf(“Hai \n”);
}
Output:
Hai
void show(int x)
{
printf(“Value =%d”, x);
}
Output:
Enter the value for a
10
Value = 10
1. Pass by value
In this method the values of actual arguments are copied to formal arguments.
Any change made in the formal arguments does not affect the actual arguments.
Once control, return backs to the calling function the formal parameters are
destroyed.
E.g. Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int ,int);
a=10;
b=20;
printf("\n Before swapping: a = %d and b = %d",a,b);
swap(a, b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
OUTPUT:
Main function
a b
10 20
1000 1002
Swap function
a1 b1
10 20
2000 2002
After swap function
a1 b1
20 10
2000 2002
2. Pass by reference
In this method, the addresses of the actual arguments are passed to formal argument.
Thus formal arguments points to the actual arguments.
So changes made in the arguments are permanent.
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int *,int *);
a=10;
b=20;
printf("\n Before swapping: a= %d and b= %d",a,b);
swap(&a,&b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int *a1,int *b1)
{
int t;
t = *a1;
*a1 = *b1;
*b1 = t;
}
OUTPUT:
Before swapping: a = 10 and b = 20
After swapping: a = 20 and b = 10
Main function
a b
10 20
1000 1002
Swap function
a1 b1
1000 1002
a1, b1 points to a and b.
2000 2002
After swap function
a b
20 10
1000 1002
4.5. Built in Functions(String Functions, Math Functions):
Library functions are predefined functions. These functions are already developed by
someone and are available to the user for use.
Declaration:
The declarations of library functions are available in the respective header files. To use
a library function, the corresponding header file must be included.
Library of Mathematical functions.
These are defined in math.h header file.
Example:
1 double cos(double x)- Returns the cosine of a radian angle x
2 double sin(double x)- Returns the sine of a radian angle x.
3 double exp(double x)- Returns the value of e raised to the xth power
double log(double x)
4
Returns the natural logarithm (base-e logarithm) of x.
double sqrt(double x)
5
Returns the square root of x.
double pow(double x, double y)
6
Returns x raised to the power of y.
E.g.
M.Nasrin Farzana, National College of Engineering.
CS8151 – CS – Unit 3
s= “hai”;
strlen(s)-> returns the length of string s i.e. 3.
2. strcpy() function
It copies the source string to the destination string
Syntax
strcpy(destination,source);
E.g.
s1=“hai”;
s2= “welcome”;
strcpy(s1,s2); -> s2 is copied to s1. i.e. s1=welcome.
3. strcat() function
It concatenates a second string to the end of the first string.
Syntax
strcat(firststring, secondstring);
E.g.
s1=“hai ”;
s2= “welcome”;
strcat(s1,s2); -> s2 is joined with s1. Now s1 is hai welcome.
E.g. Program:
#include <stdio.h>
#include <string.h>
void main ()
{
char str1[20] = "Hello";
char str2[20] = "World";
char str3[20];
int len ;
strcpy(str3, str1);
printf("Copied String= %s\n", str3 );
strcat( str1, str2);
printf("Concatenated String is= %s\n", str1 );
len = strlen(str1);
printf("Length of string str1 is= %d\n", len );
return 0;
}
Output:
Copied String=Hello
Concatenated String is=HelloWorld
Length of string str1is 10
4. strcmp() function
It is used to compare 2 strings.
Syntax
temp_varaible=strcmp(string1,
string2);
M.Nasrin Farzana, National College of Engineering.
CS8151 – CS – Unit 3
If the first string is greater than the second string a positive number is returned.
If the first string is less than the second string a negative number is returned.
If the first and the second string are equal 0 is returned.
5. strlwr() function
It converts all the uppercase characters in that string to lowercase
characters.
Syntax
strlwr(string_name);
E.g.
str[10]= “HELLO”;
strlwr(str);
puts(str);
Output: hello
6. strupr() function
It converts all the lowercase characters in that string to uppercase
characters.
Syntax
strupr(string_name);
E.g.
str[10]= “HEllo”;
strupr(str);
puts(str);
Output: HELLO
7. strrev() function
It is used to reverse the string.
Syntax
strrev(string_name);
E.g.
str[10]= “HELLO”;
strrev(str);
puts(str);
Output: OLLEH
String functions
Functions Descriptions
strlen() Determines the length of a String
strcpy() Copies a String from source to destination
strcmp() Compares two strings
strlwr() Converts uppercase characters to lowercase
M.Nasrin Farzana, National College of Engineering.
CS8151 – CS – Unit 3
Declaration
char arrayname[rowsize][colsize];
E.g.
char s[2][30];
Here, s can store 2 strings of maximum 30 characters each.
Initialization
2 ways
1. Using string constants
char s[2][20]={“Ram”, “Sam”};
2. Using initialization list.
char s[2][20]={ {‘R’, ‘a’, ‘m’, ‘\0’},
{‘S’, ‘a’, ‘m’, ‘\0’}};
E.g. Program
#include<stdio.h>
void main()
M.Nasrin Farzana, National College of Engineering.
CS8151 – CS – Unit 3
{
int i;
char s[3][20];
printf(“Enter Names\n”);
for(i=0;i<3;i++)
scanf(“%s”, s[i]);
printf(“Student Names\n”);
for(i=0;i<3;i++)
printf(“%s”, s[i]);
}
4.5 RECURSION
A function that calls itself is known as a recursive function.
Direct & Indirect Recursion:
Direct Recursion:
A function is directly recursive if it calls itself.
A( )
{
….
….
A( );// call to itself
….
}
Indirect Recursion:
Function calls another function, which in turn calls the original function.
A( )
{
…
…
B( );
…
}
B( )
{
…
…
A( );// function B calls A
…
}
void main()
{
int fact(int);
int n,f;
printf(“Enter the number \n”);
scanf(“%d”,&n);
f=fact(n);
printf(“The factorial of a number =%d”,f);
getch();
}
int fact(int n)
{
if(n==1)
return(1);
else
return n*fact(n-1);
}
OUTPUT
Enter the number to find the factorial
5
The factorial of a number=120
Pattern of Recursive Calls:
Based on the number of recursive calls, the recursion is classified in to 3 types. They
are,
1. Linear Recursion
Makes only one recursive call.
2. Binary Recursion
Calls itself twice.
3. N-ary recursion
Calls itself n times.
4.6EXAMPLE PROGRAM:
COMPUTATION OF SINE SERIES:
program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i, n;
float x, sum, t;
clrscr();
printf(" Enter the value for x : ");
scanf("%f",&x);
printf(" Enter the value for n : ");
scanf("%d",&n);
x=x*3.14159/180;
t=x;
sum=x;
break;
case 3:
printf(“Enter X: “);
scanf(“%f”, &x);
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;
case 8:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(x, 3);
printf(“\nResult: %f”, result);
break;
case 9:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = (x * y) / 100;
printf(“\nResult: %.2f”, result);
break;
case 10:
printf(“Enter X: “);
scanf(“%f”, &x);
result = log10(x);
printf(“\nResult: %.2f”, result);
break;
}
} while(choice);
getch();
return 0;
}
BINARY SEARCH USING RECURSIVE FUNCTIONS:
Program:
#include <stdio.h>
int RecursiveBinarySearching(int arr[], int low, int high, int element)
{
int middle;
if(low > high)
{
return -1;
}
middle = (low + high) / 2;
if(element > arr[middle])
{
RecursiveBinarySearching(arr, middle + 1, high, element);
}
else if(element < arr[middle])
{
RecursiveBinarySearching(arr, low, middle - 1, element);
}
else
{
return middle;
}
}
int main()
{
int count, element, limit, arr[50], position;
printf("\nEnter the Limit of Elements in Array:\t");
scanf("%d", &limit);
printf("\nEnter %d Elements in Array: \n", limit);
for(count = 0; count < limit; count++)
{
scanf("%d", &arr[count]);
}
printf("\nEnter Element To Search:\t");
M.Nasrin Farzana, National College of Engineering.
CS8151 – CS – Unit 3
scanf("%d", &element);
position = RecursiveBinarySearching(arr, 0, limit - 1, element);
if(position == -1)
{
printf("\nElement %d Not Found\n", element);
}
else
{
printf("\nElement %d Found at Position %d\n", element, position + 1);
}
return 0;
}
Output:
Enter the Limit of Elements in Array: 5
Enter 5 Elements in Array:
12345
Enter Element To Search:3
Element 3 Found at Position 3
4.7. POINTERS
Definition:
A pointer is a variable that stores the address of a variable or a function
Advantages
1. Pointers save memory space
2. Faster execution
3. Memory is accessed efficiently.
Declaration
datatype *pointername;
int a=10; p a
int *p=&a;
2000 10
4000 2000
p is an integer pointer & holds the address of an int variable a.
Pointer to pointer
A pointer that holds the address of another pointer variable is known as a pointer to
pointer.
E.g.
int **p;
int a=12;
int *p=&a; a
int **pptr=&p;
12
p 4000 4000
6000
6000 pptr
8000
So **pptr=12
Operations on pointers:
a 12.5
1000 1000
P
2000
2. Dereferencing a pointer
The object referenced by a pointer can be indirectly accessed by dereferencing
the pointer. Dereferencing operator (*) is used for this .This operator is also known as
indirection operator or value- at-operator
Eg) int b;
int a=12;
a 12 int *p;
1000 p=&a;
b=*p; \\value pointed by p(or)value
1000 at 1000=12,
p so b=12
2000 Note
Example program
%p is used for addresses; %u can
#include<stdio.h>
also be used.
void main()
{
*p=value at p
int a=12;
=value at (1000)=12
M.Nasrin Farzana, National College of Engineering.
*pptr=value at(pptr)
=value at(value at (2000))
=value at (1000)=12
CS8151 – CS – Unit 3
int *p;
int **pptr;
p=&a;
pptr=&p;
printf(“a value=%d”,a);
printf(“value by dereferencing p is %d \n”,*p);
printf(“value by dereferencing pptr is %d \n”,**pptr);
printf(“value of p is %u \n”,p);
printf(“value of pptr is %u\n”,pptr);
}
Output:
a value=12
value by dereferencing p is 12
value by dereferencing pptr is 12
value of p is 1000
value of pptr is 2000
a 12
1000 p 1000
3000
4.8. Initialization
1. Pointer can be assigned or initialized with the address of an object.
Eg) int a=10;
int *p=&a;
2. A pointer to one type cannot be initialized with the address of other type object.
Eg) int a=10;
float *p;
p=&a; //not possible
Because p is a float pointer so it can’t point int data.
1. Addition
(i) An addition of int type can be added to an expression of pointer type. The result
M.Nasrin Farzana, National College of Engineering.
CS8151 – CS – Unit 3
Pre-increment
Result = initial
value of
pointer +
sizeof (T)
Pre-
decrement
Result = initial
value of
pointer –
sizeof(T)
Eg.pre float* - float* ftr=--p ftr=? ftr=1996
decrement p=2000 p=1996 Value of ptr =
Value of ptr –
sizeof(T)
10 20 30
Output:
Given array is
0: GeeksforGeeks
1: GeeksQuiz
2: CLanguage
Sorted array is
0: CLanguage
1: GeeksQuiz
2: GeeksforGeekss
4.11.PARAMETER PASSING:
Function with input and outputs
More than one value can be indirectly returned to the calling function by making use of
pointers.
E.g. Program:
Call by reference program
4.11.1 Pass by value & Pass by reference
Argument passing methods in ‘C’ are,
3. Pass by value
4. Pass by reference
2. Pass by value
In this method the values of actual arguments are copied to formal arguments.
Any change made in the formal arguments does not affect the actual arguments.
Once control, return backs to the calling function the formal parameters are
destroyed.
E.g. Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int ,int);
a=10;
b=20;
printf("\n Before swapping: a = %d and b = %d",a,b);
swap(a, b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
OUTPUT:
Before swapping: a =10 and b =20
After swapping: a =10 and b = 20
Main function
a b
10 20
1000 1002
Swap function
a1 b1
10 20
2000 2002
After swap function
a1 b1
20 10
2000 2002
2. Pass by reference
In this method, the addresses of the actual arguments are passed to formal argument.
Thus formal arguments points to the actual arguments.
So changes made in the arguments are permanent.
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int *,int *);
a=10;
b=20;
printf("\n Before swapping: a= %d and b= %d",a,b);
swap(&a,&b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int *a1,int *b1)
{
int t;
t = *a1;
*a1 = *b1;
*b1 = t;
}
OUTPUT:
Before swapping: a = 10 and b = 20
After swapping: a = 20 and b = 10
Main function
a b
10 20
1000 1002
Swap function
a1 b1
1000 1002
a1, b1 points to a and b.
2000 2002
After swap function
a b
20 10
1000 1002
Pass by Value Pass by Reference
Values of the Actual arguments are Passed to Addresses of the Actual arguments are passed to
the Formal Arguments. the Formal Arguments.
Different Memory Locations are Occupied Same memory Locations are Occupied.
In this, you are sending a copy of the data. In this, you are passing the memory address of the
data that is stored.
Changes does not affect the actual value. Changes to the value affect the original data.
swap(a, b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
OUTPUT:
Before swapping: a =10 and b =20
After swapping: a =10 and b = 20
Pass by Reference:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int *,int *);
a=10;
b=20;
printf("\n Before swapping: a= %d and b= %d",a,b);
swap(&a,&b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int *a1,int *b1)
{
int t;
t = *a1;
*a1 = *b1;
*b1 = t;
}
OUTPUT:
Before swapping: a = 10 and b = 20
After swapping: a = 20 and b = 10