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
…
}
….
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
Arguments are passed through the calling function. The called function operates on the
values but no result is sent back.
Example program:
#include<stdio.h>
void main()
{
int a;
void show( );
printf(“Enter the value for a \n”);
scanf(“%d”, &a);
show(a);
} Arguments are passed.
No values are sent back.
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:
Before swapping: a =10 and b =20
After swapping: a =10 and b = 20
CS8151 – CS – Unit 3
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;
}
CS8151 – CS – Unit 3
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.
This function is used to print the character, string, float, integer, octal
1 printf()
and hexadecimal values onto the output screen
This function is used to read a character, string, and numeric data from
2 scanf()
keyboard.
3 getc() It reads character from file
4 gets() It reads line from keyboard
E.g.
s= “hai”;
strlen(s)-> returns the length of string s i.e. 3.
2. strcpy() function
CS8151 – CS – Unit 3
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);
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
CS8151 – CS – Unit 3
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
strupr() Converts lowercase characters to uppercase
strdup() Duplicates a String
strstr() Determines the first occurrence of a given String in another string
strcat() Appends source string to destination string
strrev() Reverses all characters of a string
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()
{
int i;
char s[3][20];
printf(“Enter Names\n”);
for(i=0;i<3;i++)
scanf(“%s”, s[i]);
CS8151 – CS – Unit 3
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
…
}
getch();
}
OUTPUT:
Enter the value for x :45
Enter the value for n: 5
The value of Sin(0.7853980 = 0.7071
case 3:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = x * y;
CS8151 – CS – Unit 3
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");
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;
}
CS8151 – CS – Unit 3
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;
6000
6000 pptr
8000
So **pptr=12
CS8151 – CS – Unit 3
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
Example program
#include<stdio.h>
void main() Note
{
int a=12; %p is used for addresses; %u can
int *p; also be used.
int **pptr;
p=&a; *p=value at p
pptr=&p; =value at (1000)=12
printf(“a value=%d”,a);
printf(“value by dereferencing p is %d \n”,*p); *pptr=value at(pptr)
printf(“value by dereferencing pptr is %d \n”,**pptr); =value at(value at (2000))
printf(“value of p is %u \n”,p); =value at (1000)=12
printf(“value of pptr is %u\n”,pptr);
}
Output:
a value=12
value by dereferencing p is 12
CS8151 – CS – Unit 3
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
is pointer type.(or)A pointer and an int can be added.
3. Decrement
Decrement operator can be applied to an operand of pointer type.
4. Subtraction
i) A pointer and an int can be subtracted.
ii) 2 pointers can also be subtracted.
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
Sorting of Names:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static int myCompare (const void * a, const void * b)
{
return strcmp (*(const char **) a, *(const char **) b);
}
void sort(const char *arr[], int n)
{
qsort (arr, n, sizeof (const char *), myCompare);
}
int main ()
{
const char *arr[] = {"GeeksforGeeks", "GeeksQuiz", "CLanguage"};
int n = sizeof(arr)/sizeof(arr[0]);
int i;
printf("Given array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
sort(arr, n);
printf("\nSorted array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
return 0;
}
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
CS8151 – CS – Unit 3
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
CS8151 – CS – Unit 3
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;
}
CS8151 – CS – Unit 3
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.
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