[go: up one dir, main page]

0% found this document useful (0 votes)
137 views19 pages

Unit4-Pps-functions &dynamic Memory Allocation

Functions allow programmers to organize code and reuse functionality. Functions are defined with a return type, name, and parameters. Parameters can be passed by value or by reference. Passing by value copies the values, while passing by reference copies the addresses. Standard functions from header files like math.h, stdio.h, and string.h provide common operations like input/output, mathematics, and string manipulation. Inter-function communication allows passing of data between functions through parameters.

Uploaded by

Gowtham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views19 pages

Unit4-Pps-functions &dynamic Memory Allocation

Functions allow programmers to organize code and reuse functionality. Functions are defined with a return type, name, and parameters. Parameters can be passed by value or by reference. Passing by value copies the values, while passing by reference copies the addresses. Standard functions from header files like math.h, stdio.h, and string.h provide common operations like input/output, mathematics, and string manipulation. Inter-function communication allows passing of data between functions through parameters.

Uploaded by

Gowtham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.

Tech I-Year

(Q1) Define function and explain its implementation


 A function is a subprogram it perform a specific task.
 Function is a derived data type .
 The function type is derived from return type.
int sub(int a,int b);
Advantages of using functions: main()
{
1. The functions are used to implement modular programming concept. int a=30,b=20;
2. The function provide the reuse of code s=sub(a,b); printf("a-b=
3. The function avoid the repetition of the code in the program %d",s);
}
Steps to follow to write functions in
C 1.function declaration int sub( int x,int y)
2.function definition a,b: actual parameters { 30 20
3.function calling x,y: formal parameters l=a-b; 10
4. return type return(l);
sub
1. function declaration : The function declaration should be done before function call. the
declaration contains the name of the function ,return type and the order of the formal
parameters

Syntax :
function returntype functionname( formal parameters)

Example : int add (int a, int b, int c)


add is a function it returns integer value and it pass two
values of the variables a and b as arguments to the function
called.

2. function definition: the function definition is also called function prototype. within the function
definition we will write the code of task to be performed by the function.

Syntax for function definition:


function returntype functionname( formal parameters)
{
function code
return
}
Example : int add(ina,int b,intc ) /a,b and c are formal parameters
{ int sum;
sum=a+b+c;
return(sum);
}
3. function calling :The function is calling to perform the task. when the function is calling the
controller transfer to the function definition (called function),when the called function
completes
Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM Page 1
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM Page 2


Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

its task control return back to the calling function.


Syntax : for calling function
Function name(actual parameters)
Example :
add(int a, int b, int c) / a,b and c are actual parameters

When a function is calling : things remembering are


1. The no of formal parameters=the no of actual parameters
2. the corresponding data types should be match
3.
4. function return type: return() statement is used to return the value from the called function to
calling function .the return type can be any type except an array.
Syntax : return(expression);
Example : return 0;
return(sum) ;
return(a+b+c);

Example :

write a C program to arithmetic operations using

functions #include<stdio.h>
#include<conio.h>
void add(int ,int); // function declaration
int subtraction(int ,int) // function declaration
void main()
{
int a,b,sub;
clrscr();
printf(“enter a b values
:”); scanf(“%d
%d”,&a,&b);
add(a,b); // function calling with actual
parameters sub=subtraction(a,b);
printf(“ %d-%d is :%d”,a,b,sub);
}

void add(int x,int y) // function definition with formal parameters


{ int sum; //local variable within
function sum=x+y;
printf(“ sum of %d %d is : %d “,x,y,sum);
}

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM Page 3


Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM Page 4


Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

int subtraction( int a,int b)


{
int s;
s=a-b;
return(s);
}

Testdata : input : enter a b value : 30 20


Output :
sum of 30 20 is : 50
30-20 is : 10

(Q2) What is interfunction communication ?explain parameters passing technique

Inter function communication/parameter passing technique : the way of communicating


calling and called functions to exchange the data through parameters passing is called inter
function communication or parameters passing technique.

Parameters passing can be done in two ways


1.call by value
2. call by reference

call by value: The values of the actual parameters of calling function are copied into the formal
parameters of the called function.
The called function may changed the values passed ,but the original value in the
calling function are unchanged.

Example:for call by value


Example: Swapping using (call by value)
void swap(int a ,int b)
int main()
{
int a, b; a = 5; b = 20;
printf(“before swap “)
printf(“a=%d %d”,a,b)
swap (a, b);
printf(“after swap “)
printf(“a=%d %d”,a,b)
return 0;
}

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM


Page 5
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

void swap (int x, int y)


{ int t;
t = x;
x = y;
y = t;
}
out put :
before swap a=5 b=20
after swap a=5 b=20
Parameters passed by value, so changes done on copy, not returned to calling function

call by reference(address):
 passing the address to the called function instead of values is called call by reference .
 The call by reference can be achieved by using pointers .
 The address of the actual parameters of calling function are copied into the formal
parameters of the called function.
 If any changes occurred for the values of the formal parameters in the called function
the changes will affect the actual parameters of the calling function because we are
passing the address .

Ex: for call by reference


void swap(int a , int b)
int main()
{ int a, b;
a = 5; b = 20;
swap (&a, &b);
printf (“\n a=%d, b=%d”, a, b);
return 0; }
void swap (int *x, int *y)
{ int t;
t = *x;
*x = *y;
*y = t;
}
Output :
a=20, b=5 Parameters passed by address, changes done on the value stored at that address
A=5 b=20

Note : 1.use & (address symbol ) before the actual parameter when we call a function.
2.use *(asterisk ) symbol before the formal parameters in the called function

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM


Page 5
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

Standard functions: standard functions are predefined functions (library functions)


available for the user program in the form of header file

C provides a collection of standard functions whose definition(logic) have been written and are
ready to be used in our program.

The header file contains all the function declarations .The include statement used to include the
header file for our program.

Ex:include<stdio.h>

The library file stdio.h include the standard input output functions into our program.
It contains the declarations for printf()& scanf().when the program is linked the object code
for these functions is combined with our code to build the complete program.

1. The standard functions available in header file <math.h> to perform


mathematical operations:

Cell(1,.7)=1 floor(1.7)=2, power(3,3)=27 ,sqrt(25)=5

2.Standard input /output functions available in <stdio.h> to perform I/Ooperations


Standard functions used Reading data from key board and writing data on to the
console(screen)
scanf() ---read data from key board
printf()---write data on to the
screen
gets()-----read string data only from key board
puts()----write string data only on to the enscr
getchar()—read single character from keyboard
putchar()—write single character on to a screen
Standard functions used reading data from file and writing data into a file
fscanf()—read data from the file
fprintf()—write data into a
file
getw() ----read integer data only from a file
putw()- - -write integer data only in to the
file

3.Standard functions available in <string.h>to perform string operations


strlen()----to find the length of the given
string strcpy() to copy one string to
another
strcat()----to concatenate two string
strcmp()- - -to compare two strings
Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM
Page 5
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

strchar()- -to search a single character in the given string and find rest of data from match
strstr()----to search a string in the given string and return rest of data from match
strrev()----to reverse the given string

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM


Page 5
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

(Q4) What is recursion? explain recursive function with examples.

Recursion : Recursion is a repetitive process


Recursive function : the function calling by itself repetitively is called recursive function and the
technique is called recursion.

Example 1: recursive formula to find factorial of a given number


factorial(n)= 1 if n=0
=n*factorial(n-1) if n>1
Recursive function to find factorial of a number:
int factorial(int n)
{
if(n==0)
return 1;
else
return(n*factorial(n-1)
}

Write C program to find factorial of a given number using recursion


#include<stdio.h>
#include<conio.h>
int factrorial( int n); // function declaration
void main()
{
int n ,fact;r
clrscr();
printf(“enter n value \n”);
scanf(“%d”,&n);
fact=factorial(n) // function calling
printf(“the factorial of %d is : %d”,fact);
}
int factorial(int n) // function definition (called function)
{
if(n==0)
return 1;
else
return(n*factorial(n-1)
}

Test data1 : input : enter n value : 5 Output


: the factorial of 5 is : 120
Test data2 : input : enter n value : 6
Output : the factorial of 6 is : 720

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM


Page 5
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

Example 2: recursive function that generate Fibonacci numbers


Fib0=0, fib1=1
Fibn=fibn-1+fibn-2
int fib( int num)
{
if (n==0|| n==1)
return(n);
return(fib(n-1+fib(n-2))
}
Write C program to generate n Fibonacci numbers
#include<stdio.h>
int fibonacci(int num);
#include <stdio.h>
main()
{
int num;
printf("Enter a number");
scanf("%d", &num);
for(int i = 0; i < num; i++)
printf("%d\t",fibonacci(i));
}
int fibonacci(int num){

if(num == 0 || num == 1)
return(num);
else
//recursive call
return (fibonacci(num-1) + fibonacci(num-2));
}

Testdata1: input : enter n value : 5


Output : the first 5 fibonacci numbers are: 0 1 1 2 3

Testdata1: input : enter n value : 10


Output : the first 10 fibonacci numbers are: 0 1 1 2 3 5 8 13 21 34 55

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM


Page 5
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

Non recursive function to generate n fibonacci numbers

#include<stdio.h>
int main(){
int n,n1=0,n2=1,n3;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Fibonacci Series:\n ");
printf("%d\t %d \t",n1,n2);
n=n-2;
while(n >0)
{
n3=n1+n2;
n1=n2;
n2=n3;
printf("%d\t",n3);
n--;
}

return 0;
}

Non rrecursive function to find factorial of a given number

#include<stdio.h>
int main(){
int n,product=1,i;
printf("Enter the number : ");
scanf("%d",&n);
i=1;
while(i<=n)
{
product=product*i;
i++;
}

printf("the factorial of %d is :%d",n,product) ;


}

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM


Page 5
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

Passing array to function:

 Array is a pointer variable when we pass the array as argument to the function it pass
the base address to the function
 if any changes made in the called function the changes will affect the calling function
 i.e passing arry to a function is a call by reference

write a C program to pass array to the function #include<conio.h>


void readarray(int []);
void arraychange(int []);
void displayarray(int []);

int n,i; /* globaldeclaration variables */


main()
{
int a[10];
printf("enter the size of an array\n");
scanf("%d",&n);
printf("enter %d elements ",n);
readarray(a);
printf("\nthe array elements before calling the function:\n ");
display(a);
arraychange(a);
printf("\nthe array elements after calling the function: \n");
display(a);
}
void readarray(int a[])
{
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void displayarray(int a[])
{
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM
Page 5
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

void arraychange(int a[])


{
int j=10;
for(i=0;i<n;i++)
a[i]=a[i]+j;
}
}
Testdata : input : enter array size 5
Enter array elements : 1 2 3 4 5
Output :
the array elements before calling the arraychange () function : 1 2 3 4 5

the array elements before calling the arraychange () function : 10 20 30 40 50

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM


Page 5
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

write a C program to pass structure to a function through call by


reference technique
#include<stdio.h>
#include<string.h>
struct lecturer
{
char name[30];
int tot_exp;
int pre_exp;
};
void call_byreference(struct lecturer *lectures);
int main()
{
struct lecturer lecturer1;
printf("\enetr name of lecturer :");
scanf("%s",&lecturer1.name);
printf("\enetr total experience :");
scanf("%d",&lecturer1.tot_exp);
printf("\enetr present experence :");
scanf("%d",&lecturer1.pre_exp);
call_byreference(&lecturer1);
printf("name :%s\n",lecturer1.name);
printf("tot experience :%d\n",lecturer1.tot_exp);
printf("present experience:%d\n",lecturer1.pre_exp);

return 0;
}

void call_byreference(struct lecturer *lectures)


{
strcpy(lectures->name,"chinnaiah");
lectures->tot_exp=21;
lectures->pre_exp=6;
}

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM


Page 7
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

write a C program to pass structure using call by value technique


#include<stdio.h>
#include<string.h>
struct lecturer
{
char name[30];
int tot_exp;
int pre_exp;

};

void call_byvalue(struct lecturer lectures);


int main()
{
struct lecturer lecturer1;
printf("\enetr name of lecturer :");
scanf("%s",&lecturer1.name);
printf("\enetr total experience :");
scanf("%d",&lecturer1.tot_exp);
printf("\enetr present experence :");
scanf("%d",&lecturer1.pre_exp);
call_byvalue(lecturer1);
printf("name :%s\n",lecturer1.name);
printf("tot experience :%d\n",lecturer1.tot_exp);
printf("present experience:%d\n",lecturer1.pre_exp);

return 0;
}

void call_byvalue(struct lecturer lectures)


{
strcpy(lectures.name,"chinnaiah");
lectures.tot_exp=21;
lectures.pre_exp=6;
}

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM


Page 7
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

Allocation of memory for the variable during run time is called dynamic
memory allocation.
There are three functions to allocate memory during runtime .

1. malloc()
2.calloc()
3.realloc()

1. malloc ( ): malloc() is a dynamic memory allocation function .it allocate the


block of memory of specified size during the run time of the program and
returns a pointer of type void. whenever use malloc() function we need to
use free() function to release allocated memory .
the syntax for malloc():
Void * manlloc(size of (datatype),no of elements)
it is a void type pointer we need to type cast for allocated data type using
(data type *)
Ex: int *par;
float *par1;
Par= (int *) malloc(sizeof (int ) ) /allocate 2 bytes during runtime for
the variable par
free(par)
Par1=(float *) malloc(sizeof (float) *5)
Free(par1)
// allocate 5*4=20 bytes during runtime for the variable par1 and par1 is
tread as array
Ex: int *ptr=(int*)malloc(3*sizeof(int))
the malloc function allocates 6 bytes for the array ptr of 3 elements and
array 3 elements are initialized with the garbage values .
ptr

ptr[0] ptr[1] ptr[2]

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM


Page 7
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

C program read the array elements during runtime and find the sum of
array elements ( using malloc function)

#include<stdio.h>
#include<stdlib.h>
int main()
{
int I,len,sum=0,*par;
printf(“enter the array size”);
scanf(“%d”,&len);
par=(int *) malloc(sizeof(int)*len);
for(i=0;i<len;i++)
{
printf(“\nenter number:”);
scanf(“%d”,&par[i]);
}
for(i=0;I<len,i++)
{
sum=sum+*(par+i);
}
printf(“the array elements are \n”);
for(i=0,i<n;i++)
{
printf(“\n par[%d]=%d”,I,*(par+i));

}
printf(“the sum of the array elements is :%d”,sum);
free(par);
}

Computer programming in C (unit-3 pointers &Strings)


Vijaya Engineering College ,Ammapalem,Khammam-507305 Page 8
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

2. calloc() :calloc is a dynamic memory allocation function . it is similar to the


malloc function but the difference is it initialize the allocated memory blocks
with 0
syntax : calloc function

void * calloc (sizeof(datatype),no of

elements) int *ptr=(int*)calloc(3,sizeof(int))

the calloc function allocates 6 bytes for the array ptr of 3 elements
and array 3 elements are initialized with the value 0 .
ptr 0 0 0
ptr[0] ptr[1] ptr[2]

C program read the array elements during runtime and find the sum of
array elements ( using calloc function)

#include<stdio.h>
#include<stdlib.h>
Main()
{ int len,I;
Int *par
Printf( “enter the count of the numbers\n”);
Scanf(“%d”,&len);

par=(int *) calloc(sizeof(int)*len); /par is a dynamic array


for (i=0;i<len;i++)
{ printf(“enter number\n”);
scanf(“%d”,&(par+i));
}
for (i=0;i<len;i++)
{ sum=sum+par[i];
}
free(par);}

Faculty :Prof Chinnaiah.V (Dept:CSE ) ) Vijaya Engineering College ,Khammam


Page 9
Sub:Programming for problem solving Unit4 (Functions & Dynamic Memory allocation ) B.Tech I-Year

3. realloc() :realloc is a dynamic memory allocation function, it is used to


re size the blocks of memory already allocated by malloc (or) calloc()

syntax:
void * realloc (void *ptr , size )

The function realloc(ptr,n) uses two arguments

Ptr: .the first argument ptr is a pointer to a block of memory for which the size is to be
altered.
Size: new size of the block in bytes

The following example shows the usage of realloc() function.

#include <stdio.h> #include


<stdlib.h> int main()
{
int *array = (int*)malloc(sizeof(int)*2); int i;
int *array1;

*array = 100;
*(array + 1) = 200;

Array1_new = (int *)realloc(array, sizeof(int)*3);


*(array1 + 2) = 300;
Printf(“array elements are\n”);
for(i = 0; i < 3; i++)
printf("array[%d]=%d ", i,*(parray1 + i));

}
note :
Int *B=(int *)realloc(NULL,n*sizeof(int) // equivalent to malloc
Int *B=(int*)realloc(A,0) // equivalent to free(A)

Faculty:Prof Chinnaiah.V (Dept:CSE) VIJAYA ENGINEERING COLLEGE ,KHAMMAM Page 15

You might also like