C Programing Unit 4 Notes
C Programing Unit 4 Notes
C Programing Unit 4 Notes
UNIT 4 FUNCTIONS
Introduction to Functions – Types: User-defined and built-in functions - Function
prototype - Function definition - Function call - Parameter passing: Pass by value -
Pass by reference - Built-in functions (string functions) – Recursive functions –
Exercise programs: Calculate the total amount of power consumed by ‘n’ devices
(passing an array to a function) – Menu-driven program to count the numbers
which are divisible by 3, 5 and by both (passing an array to a function) – Replace
the punctuations from a given sentence by the space character (passing an array to
a function)
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);
Unit 4 notes
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
…
}
Unit 4 notes
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
Unit 4 notes
void show(int x)
{
printf(“Value =%d”, x);
}
Output:
Enter the value for a
10
Value = 10
{
return 3.14 * r1 * r1;
}
Output:
Enter the radius
2
Area of circle = 12.000
4. 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.4.3 Pass by value & Pass by reference
Argument passing methods in ‘C’ are,
1. Pass by value
2. Pass by reference
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:
Unit 4 notes
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;
}
Unit 4 notes
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.
Example:
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.
Unit 4 notes
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)
;
If the first string is greater than the second string a positive number is returned.
Unit 4 notes
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
strupr() Converts lowercase characters to uppercase
Unit 4 notes
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;
Unit 4 notes
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
…
}
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;
/* Loop to calculate the value of Sine */
for(i=1;i<=n;i++)
{
t=(t*(-1)*x*x)/(2*i*(2*i+1));
Unit 4 notes
sum=sum+t;
}
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: “);
Unit 4 notes
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");
scanf("%d", &element);
position = RecursiveBinarySearching(arr, 0, limit - 1, element);
if(position == -1)
{
printf("\nElement %d Not Found\n", element);
Unit 4 notes
}
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