P&DS Unit3 Theory
P&DS Unit3 Theory
P&DS
FUNCTIONS
Syllabus:
Function declaration
Function definition
Function call
Call by value
Call by reference
Recursion
String Fundamentals
String Handling Functions
Functions:-
In c, we can divide a large program into the basic building blocks known as function. The function contains
the set of programming statements enclosed by {}. A function can be called multiple times to provide
reusability and modularity to the C program. In other words, we can say that the collection of functions
creates a program. The function is also known as procedureor subroutinein other programming languages.
Functions
Predefined Userdefined
Usercustomized
Libraryfunctions Functions, to
reduceComplexityofbi
g
Declarationinheaderfiles.
[Link]
3.
Built-in functions are also called as library function or pre-defined functions or
standard functions. These functions are available in C header files. scanf(), printf(),
strlen() etc. are some of the examples for built-in functions.
User defined functions are the functions which are developed by users/programmers.
The C program contains at least one function [Link](). The program execution starts
from main().
The following information should be known before entering in to the functions.
Return type: It says about the type of data that can be returned from the function after
execution. Return type can be of any data type such as int, double, char, void, short etc.
Function name: It is an identifier. It identifies the function with unique name which
given by the programmer. However it is advised to have a meaningful name for the
functions so that it would be easy to understand the purpose of function just by seeing
its name.
Argument/Parameter list: Argument list contains variables names along with their
data types. These arguments are kind of inputs for the function. For example – A
function which is used to add two integer variables will be having two integer
arguments. Arguments are of two types namely actual arguments and formal
arguments.
Called function: the function which is called by another function to execute is known
as called function.
Calling function: the function which calls another function to execute is known as
calling function.
In C, each function should consist of following components
Function declaration or functionprototype
Functiondefinition
Functioncall
User DefinedFunctions:-
These are the functions which are developed by the user/programmer according to their
program requirements.
Function declaration:-
Each and every function should be declared before they used. Function prototype /
declaration gives compiler information about function name, type of arguments to be passed
and returntype.
Syntax:
<Return data type><Function name> (<datatype><var1>, <datatype><var2>,...);
Note: function prototype can skip, if the function definition is before the function call.
Function definition:-
Function definition contains programming codes to perform specific task. It consist of
two parts namely function header and function body. Function header is the first line of
function definition. When a function is called, control of the program is transferred to
function header. Function header is followed by body of function insidebraces.
Syntax:
<Return_data_type><Function_name>(<datatype><var1>,<datatype><var2>,...)
{ Statement1....
Statement2....
Statement3....
.....
.....
return (expression);
}
Return statement is used for returning a value and program control from function
definition to calling function. The return statement may or may not return the values.
Function call:-
Function call invokes the function to execute. It makes the control of program jump
from that statement to function definition and executes the codes inside that function.
Syntax:
Function_name(variable1,variable2,......);
When function call occurred, the control flow of the program moves to function
definition, there it checks function header details like function name, no of arguments, data
types of the arguments. If they are matched then moves to function body and executes the
statements in it. Again the control returns to function call after completion of last statement or
first occurrence of return statement in the function body.
Example: Write a C program to add two numbers using user defined functions.
#include<stdio.h>
void main()
printf("\n\n %d + %d = %d\n\n",x,y,sum);
int add(a,b)
int c;
c=a+b;
Output:
90 + 10 = 100
Inter FunctionCommunication:-
Communication between called function and calling function to exchange the
information is called as inter function communication.
The data flow between calling and called functions can be in three ways namely
upward flow, down ward flow and Bi-directional flow. Upward flow and downward flow are
the unidirectional flows where the data flows either from calling function to called function
or called function to calling function. If the data is flowing from calling function to called
function then it is downward flow else if the data is flowing from called function to calling
function then it is upward flow. If the data is flowing from called to calling and also vice
versa then it is bidirectional dataflowing.
While establishing the inter function communication, the arguments can be passed in
two ways namely call by value and call by reference. In call by value, values are passing
through the parameters where as in call by reference the addresses are passed to establish the
communication between called and calling function.
By default in C programming call by value is used to pass the parameters. Here, only
the values of the actual arguments will copy in the formal arguments. Hence, changes made
in formal arguments will not affect the changes in actual arguments in the calledfunction.
In call by reference, the formal arguments copies the address passed from the actual
arguments. Therefore, the changes made in the formal arguments effect the actual arguments.
Here to argument pointer are passed as the values to the function.
Based on the existence of return value and arguments the inter function communication
can be done in four ways namely as follows.
1. With return values and with arguments (Bi directionflow).
2. With return value and without arguments (Upward flow).
3. Without return value and with arguments (Down wardflow).
4. Without return and without arguments (there will be no flow ofdata).
(Or)
A function may or may not accept any argument. It may or may not return any value. Based on these facts,
There are four different aspects of function calls.
[Link]
1. #include<stdio.h>
2. void printName();
3. void main ()
4. {
5. printf("Hello ");
6. printName();
7. }
8. void printName()
9. {
10. printf("Rgukt");
11. }
Output
Hello Rgukt
[Link]:-
1. #include<stdio.h>
2. void sum();
3. void main()
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum();
7. }
8. void sum()
9. {
10. int a,b;
11. printf("\nEnter two numbers");
12. scanf("%d %d",&a,&b);
13. printf("The sum is %d",a+b);
14. }
Output
The sum is 34
Example for Function without argument and with return value
[Link] :-
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. int result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. result = sum();
8. printf("%d",result);
9. }
10. int sum()
11. {
12. int a,b;
13. printf("\nEnter two numbers");
14. scanf("%d %d",&a,&b);
15. return a+b;
16. }
Output
The sum is 34
[Link] :
#include<stdio.h>
1. int sum();
2. void main()
3. {
4. printf("Going to calculate the area of the square\n");
5. float area = square();
6. printf("The area of the square: %f\n",area);
7. }
8. int square()
9. {
10. float side;
11. printf("Enter the length of the side in meters: ");
12. scanf("%f",&side);
13. return side * side;
14. }
Output
[Link]:-
1. #include<stdio.h>
2. void sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
11. void sum(int a, int b)
12. {
13. printf("\nThe sum is %d",a+b);
14. }
Output
[Link] :
1. #include<stdio.h>
2. void average(int, int, int, int, int);
3. void main()
4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }
Output
[Link] :-
1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }
Output
[Link]:-
1. #include<stdio.h>
2. int even_odd(int);
3. void main()
4. {
5. int n,flag=0;
6. printf("\nGoing to check whether a number is even or odd");
7. printf("\nEnter the number: ");
8. scanf("%d",&n);
9. flag = even_odd(n);
10. if(flag == 0)
11. {
12. printf("\nThe number is odd");
13. }
14. else
15. {
16. printf("\nThe number is even");
17. }
18. }
19. int even_odd(int n)
20. {
21. if(n%2 == 0)
22. {
23. return 1;
24. }
25. else
26. {
27. return 0;
28. }
29. }
Output
C standardLibrary Functions:-
Library functions are the inbuilt function in C that are grouped and placed at a common place called the
library. Such functions are used to perform some specific operations. For example, printf is a library
function used to print on the console. The library functions are created by the designers of compilers. All C
standard library functions are defined inside the different header files saved with the extension .h. We need
to include these header files in our program to make use of the library functions defined in such header files.
For example, To use the library functions such as printf/scanf we need to include stdio.h in our program
which is a header file that contains all the library functions regarding standard input/output.
The list of mostly used header files is given in the following table.
SN Header Description
file
1 stdio.h This is a standard input/output header file. It contains all the library functions regarding
standard input/output.
3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h This header file contains all the general library functions like malloc(), calloc(), exit(), etc.
5 math.h This header file contains all the math operations related functions like sqrt(), pow(), etc.
Let's understand call by value and call by reference in c language one by one.
Call by value in C
o In call by value method, the value of the actual parameters is copied into the formal parameters. In other words, we
can say that the value of the variable is used in the function call in the call by value method.
o In call by value method, we can not modify the value of the actual parameter by the formal parameter.
o In call by value, different memory is allocated for actual and formal parameters since the value of the actual
parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal parameter is the argument
which is used in the function definition.
Let's try to understand the concept of call by value in c language by the example given below:
1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
Call by reference in C
o In call by reference, the address of the variable is passed into the function call as the actual parameter.
o The value of the actual parameters can be modified by changing the formal parameters since the address of the
actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters and actual parameters. All the
operations in the function are performed on the value stored at the address of the actual parameters, and the
modified value gets stored at the same address.
Consider the following example for the call by reference:-:-QL CREATE TABLE
1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b
in main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters d
o change in call by reference, a = 10, b = 20
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20,
b = 10
18. }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
1 A copy of the value is passed into the function An address of value is passed into the function
2 Changes made inside the function is limited to the Changes made inside the function validate outside of the
function only. The values of the actual parameters do function also. The values of the actual parameters do
not change by changing the formal parameters. change by changing the formal parameters.
3 Actual and formal arguments are created at the different Actual and formal arguments are created at the same
memory location memory location
RecursiveFunctions:
If a function calls itself is called recursive function. A recursive function has two
components namely base case and recursive case. Recursive case is also known as general
case. A base case is the statement that solves the problem and the recursive case is the
statement which calls the function itself recursively to break the problem. Each recursive
function should have the base case, otherwise the function never come out of it. The steps to
design a recursive function are asfollows.
1. Determine the basecase.
2. Determine the recursive case.
3. Combine these base and recursive cases in to afunction.
Example: [Link] a C program to find the factorial of the given number using
recursion.(direct Declaration)
#include<stdio.h>
int factorial(int);
void main()
{
int n=6,fact;
fact=factorial(n);
printf("\n\n %d! = %d\n\n",n,fact);
}
intfactorial(intx){ // recursive function
if(x==0 || x==1)return1; // basecase
else
return(x*factorial(x-1)); // recursivecase
}
Output:
6! = 720
Strings:-
Group of character is known as string. In C, string can be defined as NULL (\0)
terminated character array which means the last character of the array is NULL. NULL
character at the end signifies that it is end of the array.
Declaring strings:
Syntax: char <string_name> [<size>];
String initialization:
Syntax1: char <string_name> [<size>] = “<string>”;
as no. Of characters+1
R G U K T \0
0 1 2 3 4 5
Syntax3: char <string_name> [ ] = {‘c1’, ‘c2’,..........‘cn’, ‘\0’};
R G U K T \0 \0 \0 \0 \0
0 1 2 3 4 5 6 7 8 9
Of course, we can access the individual character from the string using its index
number like in array.
In the above example we can access the character as
follows. a[0] retrieves ‘R’
a[1]
retrieves
‘G’ a[2]
retrieves
‘U’ a[3]
retrieves
‘K’ a[4]
retrieves ‘T’
Note: In any compiler a single character always takes ‘1 byte’ of memory. Therefore
the size of array itself indicates number of maximum characters can be stores and
memory required for the string.
String I/O functions :
Thefollowingaretheinputandoutputfunctionsofstringsin c
The scanf() andprintf() are generic i/o functionsthatthey support all built-in data
types such as int, float, long, double, strings,..etc.
But gets() and puts() are specialized to scan and print only string data. There is a
little difference between scanf() and gets(), while reading string from keyboard,
the scanf() accepts character by character from keyboard until either anew line (‘\
n’) or blank space is found, which ever comes earlier.
#include<stdio.h>
#include<string.h
>void main()
{
char name[30];
printf(“Enter name:
“);
gets(name); //Function to read string from
user. printf(“Name: “);
puts(name); //Functiontodisplaystring.
}
Output:
Entername:Rgukt
Name: Rgukt
No Function Description
.
3) strcat(first_string, concats or joins first string with second string. The result of the string is
second_string) stored in first string.
4) strcmp(first_string, compares the first string with second string. If both strings are same, it
second_string) returns 0.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={‘R' ,’G’,’U’,’K’,’T’,’O’,’N’,’G’,’O’, ‘L’,’E’, '\0'};
5. printf("Length of string is: %d",strlen(ch));
6. return 0;
7. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={‘R' ,’G’,’U’,’K’,’T’,’O’,’N’,’G’,’O’, ‘L’,’E’, '\0'};
5. char ch2[20];
6. strcpy(ch2,ch);
7. printf("Value of second string is: %s",ch2);
8. return 0;
9. }
Output:
Output:
Here, we are using gets() function which reads string from the console.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str1[20],str2[20];
5. printf("Enter 1st string: ");
6. gets(str1);//reads string from console
7. printf("Enter 2nd string: ");
8. gets(str2);
9. if(strcmp(str1,str2)==0)
10. printf("Strings are equal");
11. else
12. printf("Strings are not equal");
13. return 0;
14. }
Output:
Example1: In below program, string “Hello” is reversedusing strrev( ) function and output is
displayed as “olleH”
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nReverse String is: %s",strrev(str));
9. return 0;
10. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nLower String is: %s",strlwr(str));
9. return 0;
10. }
Output:
EX:1
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nUpper String is: %s",strupr(str));
9. return 0;
10. }
Output:
EX:2
#include<stdio.h>
#include<string.h
>
intmain()
{
charstr[]=“ModifyThisStringToUpper”;
printf(“%s\n”,strupr(str));
return0;
}
Output:
MODIFYTHISSTRINGTOUPPER
Syntax:
C++ vs Java
Output:
Syntax:
intatoi(string);
For example:
printf(“output=%d”,atoi(“123”)+atoi(“234”));
10).atol() function: converts along int string value to equivalent long integer
value.
Syntax:long intatol(string);
For example:
printf(“output=%d”,atol(“486384”)-atol(“112233”));
/*programtocount vowels*/
# include<stdio.h>
#include<string.
h>main()
{
charst[80], ch;
intcount=0,i;
printf(“\nEnter thesentence:\n”);
gets(st);
for(i=0;i<strlen(st);i++)
switch(st [i ])
{
case‘A’:
case‘E’:
case ‘I’:
case‘O’:
case‘U’:
case‘a’:
case‘e’:
case‘I’:
case‘o’:
case‘u’:
count++;
break;
}
printf(“\n%dvowelsarepresentinthesentence”,count);
Output:
Enterthesentence:
Thisisabook
5vowelsarepresentinthesentence.
****************** END****************************
Page no :33