SlideShare a Scribd company logo
1 of 90
U19CS101- Programming for
Problem Solving
UNIT – 4
Subject code / Name: U19CS101 / Programming for Problem Solving
VIVEKANANDHA COLLEGE OF ENGINEERING FOR WOMEN
(AUTONOMOUS)
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Year / Branch / semester: I Year / ECE / 01
M.Mailsamy
AP / CSE
VCEW
UNIT – I Introduction to Problem Solving Periods 9
Basic Organization of Computer - Programming Languages- Flowchart – Pseudocode - Compilers-
Interpreter-Algorithm - Building Blocks of Algorithm - Algorithmic Problem Solving-Simple Strategies for
Developing Algorithms - Illustrative Problems: Find Minimum value from list of elements, Guess an
Integer Number in a Range, Factorial of a given number.
UNIT - II C Programming Periods 9
Introduction to C – Features - Data Types – Constants – Variables - I/O Statement - Operators –
Expressions - Decision Making and Branching – Looping Statements - Break, Goto, Continue.
UNIT – III Arrays and Strings Periods 9
Arrays: Concepts – Need – one dimensional array – array declaration – features – array initialization -
Two- Dimensional Arrays- Multidimensional Arrays.
Strings: Concepts – Strings manipulation - String Input / Output Functions- Strings standard functions -
Arrays of Strings.
UNIT - IV Functions and Pointers Periods 9
Function: Introduction, function declaration, defining and accessing functions, User-defined Functions-
storage classes-function prototypes-parameter passing methods-recursion.
Pointers: Introduction, pointer declaration-accessing variable through pointer-pointers and Arrays, Pointers
and strings – Pointers structures-pointer Arithmetic - Array of Pointers – dynamic memory allocation.
UNIT – V Structures and Unions Periods 9
Structures-Introduction- nested structures- Arrays of Structures - Structures and Functions - Pointers to
Structures – Unions- Type Definition – Bitfields- Enumerated Types.
Syllabus
Text Books:
T1.
Kernighan BW and Ritchie DM, “The C Programming Language”, 2nd Edition, Prentice
Hall of India, 2015.
T2. E. Balagurusamy, Computer Programming, First Edition, Mc Graw Hill, 2016.
References:
R1. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition
R2.
Dr.V.Rameshbabu, Dr.R.Samyutha, M.Muni Rathnan, “Computer Programming”, VRB
Publishers Pvt.Ltd,
R3. E. Balagurusamy, Programming in ANSI C, Seventh Edition, Mc Graw Hill, 2017.
UNIT 4 - Functions and Pointers
• Function: Introduction
• Function declaration
• Defining and accessing
functions
• User-defined Functions
• Storage classes
• Function prototypes
• Parameter passing methods
• Recursion
• Pointers: Introduction
• Pointer declaration
• Accessing variable through
pointer
• Pointers and Arrays
• Pointers and strings
• Pointers structures
• Pointer Arithmetic
• Array of Pointers
• Dynamic memory allocation
Function: Introduction
• A function is a block of code that performs a specific task.
• Suppose, you need to create a program to create a circle and color
it. You can create two functions to solve this problem:
1) Create a circle function
2) Create a color function
• Dividing a complex problem into smaller chunks makes our
program easy to understand and reuse.
Types of function
• There are two types of function in C programming:
1) Standard library functions
2) User-defined functions
Standard library functions
• The standard library functions are built-in functions in C
programming.
• These functions are defined in header files. For example,
• The printf() is a standard library function to send formatted output
to the screen (display output on the screen).
• This function is defined in the stdio.h header file.
• Hence, to use the printf() function, we need to include the stdio.h
header file using #include <stdio.h>.
• The sqrt() function calculates the square root of a number. The
function is defined in the math.h header file.
• Visit standard library functions in C programming to learn more.
User-defined function
• You can also create functions as per your need.
• Such functions created by the user are known as user-defined functions.
How user-defined function works?
#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}
int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}
• The execution of a C program begins from the main() function.
• When the compiler encounters functionName();, control of the
program jumps to
• void functionName()
• And, the compiler starts executing the codes inside
functionName().
• The control of the program jumps back to the main()
function once code inside the function definition is executed.
• Note, function names are identifiers and should be unique.
• This is just an overview of user-defined functions. Visit these
pages to learn more on:
• User-defined Function in C programming
• Types of user-defined Functions
Advantages of user-defined function
• The program will be easier to understand, maintain and debug.
• Reusable codes that can be used in other programs
• A large program can be divided into smaller modules. Hence, a
large project can be divided among many programmers.
Function Declaration in C
• A function (method) is a block of code that can be called from
another location in the program or class. It is used to reduce
the repetition of multiple lines of code.
Syntax
returnType functionName(parameterTypes); //function prototype
//main code
returnType functionName (functionParameters) //function implementation
{
//statements that execute when called
return value;
}
Example
int findMaximum(int, int); //prototype
void main()
{
int maxNumber = findMaximum(5, 7); //calling a function
}
int findMaximum(int number1, int number2)
{ //implementation
int maximum = number2;
if (number1 > number2)
maximum = number1;
return maximum;
}
Function prototypes
• Here we will see why we should use function prototype in C.
• The function prototypes are used to tell the compiler about the
number of arguments and about the required datatypes of a
function parameter, it also tells about the return type of the
function.
• By this information, the compiler cross-checks the function
signatures before calling it.
• If the function prototypes are not mentioned, then the program
may be compiled with some warnings, and sometimes generate
some strange output.
Syntax of function prototype in C programming
return_type function_name( type argument1, type argument2, ...);
Example of function prototype
Let’s consider following function definition:
int area( int length, int breadth ) //function definition
{
.... //function body
}
Now, the corresponding prototype declaration of the above function is:
int area( int length, int breadth ); //function prototype
It states that function area takes two arguments of type int and returns area of
type int.
Difference between function prototype and function definition
in C
• The only difference between the function definition and its
function prototype is the addition semicolon (;) at the end of
prototype declaration.
Example Code
#include<stdio.h>
main()
{
function(50);
}
void function(int x)
{
printf("The value of x is: %d", x);
}
Output
The value of x is: 50
• This shows the output, but it is
showing some warning like
below:
• [Warning] conflicting types for
'function' [Note] previous
implicit declaration of
'function' was here
Example Code
#include<stdio.h>
void function(int); //prototype
main()
{
function(50);
}
void function(int x)
{
printf("The value of x is: %d", x);
}
Output
The value of x is: 50
• Now using function
prototypes,
it is executing without any
problem.
Classification of functions
• Built in function (Library functions)
Example: scanf(), printf(), strcpy(),clrscr()
• User defined function
–Types of user defined functions
• Function with no argument and no return type
• Function with no argument and return type
• Function with argument and no return type
• Function with argument and return type
Function with no argument and
no return type
#include<stdio.h>
void add(); // Function Declaration / Prototype
void main()
{
add(); // function call
}
// function definition
void add()
{
int a=5,b=45;
int c;
c=a+b;
printf("nAddition result : %d + %d = %d",a,b,c);
}
Output:
Addition result: 5 + 45 = 50
#include<stdio.h>
void add1(int a, int b); // Function Declaration
void main()
{
int a,b;
a=10,b=20;
add1(a,b); // function call
}
// function definition
void add1(int a, int b)
{
int c;
c=a+b;
printf("nAddition result: %d + %d = %d",a,b,c);
}
Output:
Addition result: 10 + 20 = 30.
Function with arguments and
no return type
#include<stdio.h>
int add2(); // Function Declaration
void main()
{
int c;
c=add2(); // function call
printf("nAddition result: %d",c);
}
// function definition
int add2()
{
int a=5,b=45;
int c;
c=a+b;
return (c);
}
Output:
Addition result: 50
Function with no arguments and
with return type
#include<stdio.h>
int add3(int x,int y); // Function Declaration
void main()
{
int a,b,c;
a=90,b=88;
c=add3(a,b); // function call
printf("nAddition result: %d + %d = %d",a,b,c);
}
int add3(int x,int y) // function definition
{
int z;
z=x+y;
return z;
}
Output:
Addition result: 90 + 88 = 178
Function with arguments and
return type
Parameter passing methods
• When a function gets executed in the program, the execution
control is transferred from calling-function to called function
and executes function definition, and finally comes back to the
calling function.
• When the execution control is transferred from calling-function
to called-function it may carry one or number of data values.
These data values are called as parameters.
Note:
Parameters are the data values that are passed from calling
function to called function.
• In C, there are two types of parameters and they are as follows...
Actual Parameters
Formal Parameters
• The actual parameters are the parameters that are speficified in calling
function. The formal parameters are the parameters that are declared
at called function. When a function gets executed, the copy of actual
parameter values are copied into formal parameters.
• In C Programming Language, there are two methods to pass parameters
from calling function to called function and they are as follows...
1. Call by Value
2. Call by Reference
Call by Value
• In call by value parameter passing method, the copy of actual
parameter values are copied to formal parameters and these
formal parameters are used in called function.
• The changes made on the formal parameters does not effect
the values of actual parameters.
• That means, after the execution control comes back to the
calling function, the actual parameter values remains same.
For example consider the following program...
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2 ;
void swap(int,int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(num1, num2) ; // calling function
printf("nAfter swap: num1 = %dnnum2 = %d", num1, num2);
printf("nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
getch() ;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a = b ;
b = temp ;
}
Output:
Before swap:
num1=10, num2=20
After swap:
num1=20, num2=10
• In the above example program, the variables num1 and num2
are called actual parameters and the variables a and b are
called formal parameters.
• The value of num1 is copied into a and the value of num2 is
copied into b.
• The changes made on variables a and b does not effect the
values of num1 and num2.
Call by Reference
• In Call by Reference parameter passing method, the memory location
address of the actual parameters is copied to formal parameters.
• This address is used to access the memory locations of the actual
parameters in called function.
• In this method of parameter passing, the formal parameters must be
pointer variables.
• That means in call by reference parameter passing method, the
address of the actual parameters is passed to the called
function and is recieved by the formal parameters (pointers).
• Whenever we use these formal parameters in called function,
they directly access the memory locations of actual
parameters.
• So the changes made on the formal parameters effects the
values of actual parameters.
• For example consider the following program...
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("nAfter swap: num1 = %d, num2 = %d", num1, num2);
getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Output:
Before swap:
num1=10, num2=20
After swap:
num1=20, num2=10
• In the above example program, the addresses of variables
num1 and num2 are copied to pointer variables a and b.
• The changes made on the pointer variables a and b in called
function effects the values of actual parameters num1 and
num2 in calling function.
Storage classes
Storage Classes in C: auto, extern, static, register class in C
What is Storage Class in C?
• A storage class represents the visibility and a location of a variable.
• It tells from what part of code we can access a variable.
• A storage class in C is used to describe the following things:
1. The variable scope.
2. The location where the variable will be stored.
3. The initialized value of a variable.
4. A lifetime of a variable.
Who can access a variable?
• Thus a storage class is used to represent the information about a variable.
NOTE: A variable is not only associated with a data type, its value but also a
storage class.
• There are total four types of standard storage classes.
• The table below represents the storage classes in C.
Storage class Purpose
auto It is a default storage class.
extern It is a global variable.
static
It is a local variable which is capable of
returning a value even when control is
transferred to the function call.
register
It is a variable which is stored inside a
Register.
#include<stdio.h>
#include<conio.h>
int x; //External variable
static int count=0; //Static Variable
void main()
{
int z; //Auto Variable or Local Variable
register int answer; //Register Variable
clrscr();
++count; //This statement equal to count=count+1
printf("Enter the Value 1:");
scanf("%d",&x);
printf("Enter the Value2:");
scanf("%d",&z);
answer=x+z;
printf("%d.Addition: %d",count,answer);
getch();
}
Output:
#include<stdio.h>
#include<conio.h>
int fun1();
int fun2();
int fun3();
int fun4();
int val2=200;
int main()
{
printf("Welcome to Storage Classn");
fun1();//Auto
fun2();//Static
fun3();//Extern
fun4();//Register
return 0;
}
int fun1()
{
auto int a=10;
printf("nValue of a: %d n",a);
a++;
return 0;
}
int fun2()
{
static int a=10;
printf("nValue of a: %d n",a);
a++;
return 0;
}
int fun3()
{
extern int val1;
printf("The value of val2 is %d n",val2);
printf("This is my value of val1 is %d n",val1);
return 0;
}
int val1=1000;
int fun4()
{
register int number;
for(number=1;number<=5;number++)
{
printf("Value is stored in register %d n:,number);
return 0;
}
}
Output:
Recursion in c
• Recursion is the process of repeating items in a self-similar way.
In programming languages, if a program allows you to call a
function inside the same function, then it is called a recursive
call of the function.
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
• The C programming language supports recursion, i.e., a
function to call itself.
• But while using recursion, programmers need to be careful to
define an exit condition from the function, otherwise it will go
into an infinite loop.
• Recursive functions are very useful to solve many
mathematical problems, such as calculating the factorial of a
number, generating Fibonacci series, etc.
Example: Sum of Natural Numbers Using Recursion
include <stdio.h>
int sum(int n);
int main() {
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0;
}
int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
Output
Enter a positive integer:3
sum = 6
• Recursive Solution:
Factorial can be calculated using following recursive formula.
n! = n * (n-1)!
n! = 1 if n = 0 or n = 1
Factorial of a Number Using Recursion
Factorial of a non-negative integer, is multiplication of all integers smaller than or
equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.
#include<stdio.h>
long int multiplyNumbers(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}
Output:
Enter a positive integer: 6
Factorial of 6 = 720
Fibonacci Series
#include <stdio.h>
int fibonacci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%dtn", fibonacci(i));
}
return 0;
}
Output:
0
1
1
2
3
5
8
13
21
34
What is pointer to array
• Pointer to an array is also known as array pointer.
• We are using the pointer to access the components of
the array.
int a[3] = {3, 4, 5 };
int *ptr = a;
We can likewise declare a pointer that can point to
whole array rather than just a single component of the array.
• When an array is declared, compiler allocates sufficient amount
of memory to contain all the elements of the array.
• Base address i.e address of the first element of the array is also
allocated by the compiler.
• Suppose we declare an array arr,
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer
requires two bytes, the five elements will be stored as follows:
• Here variable arr will give the base address, which is a
constant pointer pointing to the first element of the array, arr[0].
• Hence arr contains the address of arr[0] i.e 1000.
• In short, arr has two purpose - it is the name of the array and it acts
as a pointer pointing towards the first element in the array.
• arr is equal to &arr[0] by default
• We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
• Now we can access every element of the
array arr using p++ to move from one element to another.
• NOTE: You cannot decrement a pointer once incremented.
• p-- won't work.
Pointer to Array:
• As studied above, we can use a pointer to point to an array,
and then we can use that pointer to access the array
elements. Lets have an example,
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
 In the above program, the
pointer *p will print all the
values stored in the array
one by one.
 We can also use the Base
address (a in above case) to
act as a pointer and print all
the values.
Pointers and strings
• We know that a string is a sequence of characters which we
save in an array.
• And in C programming language the 0 null character marks
the end of a string.
• Creating a string In the following example we are creating a
string str using char character array of size 6.
char str[6] = "Hello";
• The above string can be represented in memory as follows.
• Each character in the string str takes 1 byte of memory space.
Creating a pointer for the string
• The variable name of the string str holds the address of the
first element of the array i.e., it points at the starting memory
address.
• So, we can create a character pointer ptr and store the
address of the string str variable in it.
• This way, ptr will point at the string str.
• In the following code we are assigning the address of the
string str to the pointer ptr.
char *ptr = str;
We can represent the character pointer variable ptr as follows.
The pointer variable ptr is allocated memory address 8000 and it holds the
address of the string variable str i.e., 1000.
Accessing string via pointer
• To access and print the elements of the string we can use a
loop and check for the 0 null character.
• In the following example we are using while loop to print the
characters of the string variable str.
#include <stdio.h>
int main(void)
{ // string variable
char str[6] = "Hello"; // pointer variable
char *ptr = str; // print the string
while(*ptr != '0')
{
printf("%c", *ptr); // move the ptr pointer to the next memory location
ptr++;
}
return 0;
}
Using pointer to store string
• We can achieve the same result by creating a character
pointer that points at a string value stored at some memory
location.
• In the following example we are using character pointer
variable strPtr to store string value.
#include <stdio.h>
int main(void)
{ // pointer variable to store string
char *strPtr = "Hello"; // temporary pointer variable
char *t = strPtr; // print the string
while(*t != '0')
{
printf("%c", *t); // move the t pointer to the next memory location
t++;
}
return 0;
}
• Note! In the above code we are using another character
pointer t to print the characters of the string as because we
don't want to lose the starting address of the string "Hello"
which is saved in pointer variable strPtr.
• In the above image the string "Hello" is saved in the memory
location 5000 to 5005.
• The pointer variable strPtr is at memory location 8000 and is
pointing at the string address 5000.
• The temporary variable is also assigned the address of the
string so, it too holds the value 5000 and points at the starting
memory location of the string "Hello".
Pointer Arithmetic
• A pointer in c is an address, which is a numeric value.
• Therefore, you can perform arithmetic operations on a pointer
just as you can on a numeric value.
• There are four arithmetic operators that can be used on pointers:
++, --, +, and -
• To understand pointer arithmetic, let us consider that ptr is an
integer pointer which points to the address 1000.
• Assuming 32-bit integers, let us perform the following arithmetic
operation on the pointer.
ptr++
After the above operation, the ptr will point to the location 1004
because each time ptr is incremented, it will point to the next
integer location which is 4 bytes next to the current location.
This operation will move the pointer to the next memory
location without impacting the actual value at the memory
location.
If ptr points to a character whose address is 1000, then the
above operation will point to the location 1001 because the next
character will be available at 1001.
Incrementing a Pointer
• We prefer using a pointer in our program instead of an array
because the variable pointer can be incremented, unlike the
array name which cannot be incremented because it is a
constant pointer.
• The following program increments the variable pointer to
access each succeeding element of the array.
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr; /* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++)
{
printf("Address of var[%d] = %xn", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr );
/* move to the next location */
ptr++;
}
return 0;
}
Output:
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200
Decrementing a Pointer
• The same considerations apply to decrementing a pointer,
which decreases its value by the number of bytes of its data
type as shown below.
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr; /* let us have array address in pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--)
{
printf("Address of var[%d] = %xn", i-1, ptr );
printf("Value of var[%d] = %dn", i-1, *ptr );
/* move to the previous location */
ptr--;
}
return 0;
}
Output:
Address of var[2] = bfedbcd8
Value of var[2] = 200
Address of var[1] = bfedbcd4
Value of var[1] = 100
Address of var[0] = bfedbcd0
Value of var[0] = 10
Pointer Comparisons
• Pointers may be compared by using relational operators, such
as ==, <, and >.
• If p1 and p2 point to variables that are related to each other,
such as elements of the same array, then p1 and p2 can be
meaningfully compared.
• The following program modifies the previous example − one by
incrementing the variable pointer so long as the address to
which it points is either less than or equal to the address of
the last element of the array, which is &var[MAX - 1].
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have address of the first element in pointer */
ptr = var;
i = 0;
while ( ptr <= &var[MAX - 1] )
{
printf("Address of var[%d] = %xn", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr );
/* point to the next location */
ptr++;
i++;
}
return 0;
}
Output:
Address of var[0] = bfdbcb20
Value of var[0] = 10
Address of var[1] = bfdbcb24
Value of var[1] = 100
Address of var[2] = bfdbcb28
Value of var[2] = 200
Pointer Arithmetic on Arrays:
• Pointers contain addresses.
• Adding two addresses makes no sense because there is no idea what it
would point to.
• Subtracting two addresses lets you compute the offset between the two
addresses.
• An array name acts like a pointer constant.
• The value of this pointer constant is the address of the first element.
• For Example: if an array named arr then arr and &arr[0] can be used to
reference array as a pointer.
• Below is the program to illustrate the Pointer Arithmetic on arrays:
/ C program to illustrate the array
// traversal using pointers
#include <stdio.h>
// Driver Code
int main()
{
int N = 5;
// An array
int arr[] = { 1, 2, 3, 4, 5 };
// Declare pointer variable
int* ptr;
// Point the pointer to first element in array arr[]
ptr = arr;
// Traverse array using ptr
for (int i = 0; i < N; i++)
{
// Print element at which
// ptr points
printf("%d ", ptr[0]);
ptr++;
}
}
Output:
1 2 3 4 5
Dynamic Memory Allocation in C using malloc(), calloc(),
free() and realloc()
• Since C is a structured language, it has some fixed rules for
programming. One of it includes changing the size of an array.
An array is collection of items stored at continuous memory
locations.
• As it can be seen that the length (size) of the array above made is 9.
• But what if there is a requirement to change this length (size).
• For Example,
• If there is a situation where only 5 elements are needed to be entered in
this array.
• In this case, the remaining 4 indices are just wasting memory in this array.
So there is a requirement to lessen the length (size) of the array from 9 to 5.
• Take another situation.
• In this, there is an array of 9 elements with all 9 indices filled.
• But there is a need to enter 3 more elements in this array.
• In this case 3 indices more are required.
• So the length (size) of the array needs to be changed from 9 to 12.
• This procedure is referred to as Dynamic Memory Allocation in C.
• Therefore, C Dynamic Memory Allocation can be defined as a
procedure in which the size of a data structure (like Array) is
changed during the runtime.
• C provides some functions to achieve these tasks. There are 4
library functions provided by C defined under <stdlib.h> header file
to facilitate dynamic memory allocation in C programming. They
are:
• malloc()
• calloc()
• free()
• realloc()
• Let’s look at each of them in greater detail.
C malloc() method
• “malloc” or “memory allocation” method in C is used to dynamically
allocate a single large block of memory with the specified size. It returns a
pointer of type void which can be cast into a pointer of any form. It
initializes each block with default garbage value.
Syntax:
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
• Since the size of int is 4 bytes, this statement will allocate 400 bytes of
memory. And, the pointer ptr holds the address of the first byte in the
allocated memory.
• If space is insufficient, allocation fails and returns a NULL
pointer.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using
malloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
C calloc() method
• “calloc” or “contiguous allocation” method in C is used to
dynamically allocate the specified number of blocks of memory of
the specified type. It initializes each block with a default value ‘0’.
• Syntax:
ptr = (cast-type*)calloc(n, element-size);
• For Example:
ptr = (float*) calloc(25, sizeof(float));
• This statement allocates contiguous space in memory for 25
elements each with the size of the float.
• If space is insufficient, allocation fails and returns a NULL
pointer.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by calloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using
calloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Output:
Enter number of elements: 5 Memory
successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
• “free” method in C is used to dynamically de-allocate the
memory. The memory allocated using functions malloc() and
calloc() is not de-allocated on their own. Hence the free()
method is used, whenever the dynamic memory allocation takes
place. It helps to reduce wastage of memory by freeing it.
Syntax:
free(ptr);
C free() method
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Dynamically allocate memory using calloc()
ptr1 = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.n");
// Free the memory
free(ptr);
printf("Malloc Memory successfully freed.n");
// Memory has been successfully allocated
printf("nMemory successfully allocated using calloc.n");
// Free the memory
free(ptr1);
printf("Calloc Memory successfully freed.n");
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.
Memory successfully allocated using calloc.
Calloc Memory successfully freed.
C realloc() method
• “realloc” or “re-allocation” method in C is used to dynamically
change the memory allocation of a previously allocated memory.
In other words, if the memory previously allocated with the help
of malloc or calloc is insufficient, realloc can be used to
dynamically re-allocate memory. re-allocation of memory
maintains the already present value and new blocks will be
initialized with default garbage value.
Syntax:
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
If space is insufficient, allocation fails and returns a NULL
pointer.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
// Get the new size for the array
n = 10;
printf("nnEnter the new size of the array: %dn", n);
// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));
// Memory has been successfully allocated
printf("Memory successfully re-allocated using realloc.n");
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
Enter the new size of the array: 10
Memory successfully re-allocated using realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
THANK YOU

More Related Content

Similar to U19CS101 - PPS Unit 4 PPT (1).ppt

Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptxAshwini Raut
 
Function in c programming
Function in c programmingFunction in c programming
Function in c programmingSayeemAhmed8
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxvanshhans21102005
 
C structure
C structureC structure
C structureankush9927
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxVigneshkumar Ponnusamy
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxKhurramKhan173
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxrajkumar490591
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1Vikram Nandini
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)Sowri Rajan
 
Book management system
Book management systemBook management system
Book management systemSHARDA SHARAN
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptxmiki304759
 

Similar to U19CS101 - PPS Unit 4 PPT (1).ppt (20)

C FUNCTIONS
C FUNCTIONSC FUNCTIONS
C FUNCTIONS
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Function
FunctionFunction
Function
 
Function in c programming
Function in c programmingFunction in c programming
Function in c programming
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Functions
FunctionsFunctions
Functions
 
C structure
C structureC structure
C structure
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptx
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
Book management system
Book management systemBook management system
Book management system
 
C programming
C programmingC programming
C programming
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
4th unit full
4th unit full4th unit full
4th unit full
 

Recently uploaded

An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 

Recently uploaded (20)

An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 

U19CS101 - PPS Unit 4 PPT (1).ppt

  • 1. U19CS101- Programming for Problem Solving UNIT – 4
  • 2. Subject code / Name: U19CS101 / Programming for Problem Solving VIVEKANANDHA COLLEGE OF ENGINEERING FOR WOMEN (AUTONOMOUS) DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Year / Branch / semester: I Year / ECE / 01 M.Mailsamy AP / CSE VCEW
  • 3. UNIT – I Introduction to Problem Solving Periods 9 Basic Organization of Computer - Programming Languages- Flowchart – Pseudocode - Compilers- Interpreter-Algorithm - Building Blocks of Algorithm - Algorithmic Problem Solving-Simple Strategies for Developing Algorithms - Illustrative Problems: Find Minimum value from list of elements, Guess an Integer Number in a Range, Factorial of a given number. UNIT - II C Programming Periods 9 Introduction to C – Features - Data Types – Constants – Variables - I/O Statement - Operators – Expressions - Decision Making and Branching – Looping Statements - Break, Goto, Continue. UNIT – III Arrays and Strings Periods 9 Arrays: Concepts – Need – one dimensional array – array declaration – features – array initialization - Two- Dimensional Arrays- Multidimensional Arrays. Strings: Concepts – Strings manipulation - String Input / Output Functions- Strings standard functions - Arrays of Strings. UNIT - IV Functions and Pointers Periods 9 Function: Introduction, function declaration, defining and accessing functions, User-defined Functions- storage classes-function prototypes-parameter passing methods-recursion. Pointers: Introduction, pointer declaration-accessing variable through pointer-pointers and Arrays, Pointers and strings – Pointers structures-pointer Arithmetic - Array of Pointers – dynamic memory allocation. UNIT – V Structures and Unions Periods 9 Structures-Introduction- nested structures- Arrays of Structures - Structures and Functions - Pointers to Structures – Unions- Type Definition – Bitfields- Enumerated Types. Syllabus
  • 4. Text Books: T1. Kernighan BW and Ritchie DM, “The C Programming Language”, 2nd Edition, Prentice Hall of India, 2015. T2. E. Balagurusamy, Computer Programming, First Edition, Mc Graw Hill, 2016. References: R1. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition R2. Dr.V.Rameshbabu, Dr.R.Samyutha, M.Muni Rathnan, “Computer Programming”, VRB Publishers Pvt.Ltd, R3. E. Balagurusamy, Programming in ANSI C, Seventh Edition, Mc Graw Hill, 2017.
  • 5. UNIT 4 - Functions and Pointers • Function: Introduction • Function declaration • Defining and accessing functions • User-defined Functions • Storage classes • Function prototypes • Parameter passing methods • Recursion • Pointers: Introduction • Pointer declaration • Accessing variable through pointer • Pointers and Arrays • Pointers and strings • Pointers structures • Pointer Arithmetic • Array of Pointers • Dynamic memory allocation
  • 6. Function: Introduction • A function is a block of code that performs a specific task. • Suppose, you need to create a program to create a circle and color it. You can create two functions to solve this problem: 1) Create a circle function 2) Create a color function • Dividing a complex problem into smaller chunks makes our program easy to understand and reuse. Types of function • There are two types of function in C programming: 1) Standard library functions 2) User-defined functions
  • 7. Standard library functions • The standard library functions are built-in functions in C programming. • These functions are defined in header files. For example, • The printf() is a standard library function to send formatted output to the screen (display output on the screen). • This function is defined in the stdio.h header file. • Hence, to use the printf() function, we need to include the stdio.h header file using #include <stdio.h>. • The sqrt() function calculates the square root of a number. The function is defined in the math.h header file. • Visit standard library functions in C programming to learn more.
  • 8. User-defined function • You can also create functions as per your need. • Such functions created by the user are known as user-defined functions. How user-defined function works? #include <stdio.h> void functionName() { ... .. ... ... .. ... } int main() { ... .. ... ... .. ... functionName(); ... .. ... ... .. ... }
  • 9. • The execution of a C program begins from the main() function. • When the compiler encounters functionName();, control of the program jumps to • void functionName() • And, the compiler starts executing the codes inside functionName(). • The control of the program jumps back to the main() function once code inside the function definition is executed.
  • 10.
  • 11. • Note, function names are identifiers and should be unique. • This is just an overview of user-defined functions. Visit these pages to learn more on: • User-defined Function in C programming • Types of user-defined Functions Advantages of user-defined function • The program will be easier to understand, maintain and debug. • Reusable codes that can be used in other programs • A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers.
  • 12. Function Declaration in C • A function (method) is a block of code that can be called from another location in the program or class. It is used to reduce the repetition of multiple lines of code. Syntax returnType functionName(parameterTypes); //function prototype //main code returnType functionName (functionParameters) //function implementation { //statements that execute when called return value; }
  • 13. Example int findMaximum(int, int); //prototype void main() { int maxNumber = findMaximum(5, 7); //calling a function } int findMaximum(int number1, int number2) { //implementation int maximum = number2; if (number1 > number2) maximum = number1; return maximum; }
  • 14. Function prototypes • Here we will see why we should use function prototype in C. • The function prototypes are used to tell the compiler about the number of arguments and about the required datatypes of a function parameter, it also tells about the return type of the function. • By this information, the compiler cross-checks the function signatures before calling it. • If the function prototypes are not mentioned, then the program may be compiled with some warnings, and sometimes generate some strange output.
  • 15. Syntax of function prototype in C programming return_type function_name( type argument1, type argument2, ...); Example of function prototype Let’s consider following function definition: int area( int length, int breadth ) //function definition { .... //function body } Now, the corresponding prototype declaration of the above function is: int area( int length, int breadth ); //function prototype It states that function area takes two arguments of type int and returns area of type int.
  • 16. Difference between function prototype and function definition in C • The only difference between the function definition and its function prototype is the addition semicolon (;) at the end of prototype declaration.
  • 17. Example Code #include<stdio.h> main() { function(50); } void function(int x) { printf("The value of x is: %d", x); } Output The value of x is: 50 • This shows the output, but it is showing some warning like below: • [Warning] conflicting types for 'function' [Note] previous implicit declaration of 'function' was here
  • 18. Example Code #include<stdio.h> void function(int); //prototype main() { function(50); } void function(int x) { printf("The value of x is: %d", x); } Output The value of x is: 50 • Now using function prototypes, it is executing without any problem.
  • 19.
  • 20. Classification of functions • Built in function (Library functions) Example: scanf(), printf(), strcpy(),clrscr() • User defined function –Types of user defined functions • Function with no argument and no return type • Function with no argument and return type • Function with argument and no return type • Function with argument and return type
  • 21. Function with no argument and no return type #include<stdio.h> void add(); // Function Declaration / Prototype void main() { add(); // function call } // function definition void add() { int a=5,b=45; int c; c=a+b; printf("nAddition result : %d + %d = %d",a,b,c); } Output: Addition result: 5 + 45 = 50
  • 22. #include<stdio.h> void add1(int a, int b); // Function Declaration void main() { int a,b; a=10,b=20; add1(a,b); // function call } // function definition void add1(int a, int b) { int c; c=a+b; printf("nAddition result: %d + %d = %d",a,b,c); } Output: Addition result: 10 + 20 = 30. Function with arguments and no return type
  • 23. #include<stdio.h> int add2(); // Function Declaration void main() { int c; c=add2(); // function call printf("nAddition result: %d",c); } // function definition int add2() { int a=5,b=45; int c; c=a+b; return (c); } Output: Addition result: 50 Function with no arguments and with return type
  • 24. #include<stdio.h> int add3(int x,int y); // Function Declaration void main() { int a,b,c; a=90,b=88; c=add3(a,b); // function call printf("nAddition result: %d + %d = %d",a,b,c); } int add3(int x,int y) // function definition { int z; z=x+y; return z; } Output: Addition result: 90 + 88 = 178 Function with arguments and return type
  • 25. Parameter passing methods • When a function gets executed in the program, the execution control is transferred from calling-function to called function and executes function definition, and finally comes back to the calling function. • When the execution control is transferred from calling-function to called-function it may carry one or number of data values. These data values are called as parameters. Note: Parameters are the data values that are passed from calling function to called function.
  • 26. • In C, there are two types of parameters and they are as follows... Actual Parameters Formal Parameters • The actual parameters are the parameters that are speficified in calling function. The formal parameters are the parameters that are declared at called function. When a function gets executed, the copy of actual parameter values are copied into formal parameters. • In C Programming Language, there are two methods to pass parameters from calling function to called function and they are as follows... 1. Call by Value 2. Call by Reference
  • 27. Call by Value • In call by value parameter passing method, the copy of actual parameter values are copied to formal parameters and these formal parameters are used in called function. • The changes made on the formal parameters does not effect the values of actual parameters. • That means, after the execution control comes back to the calling function, the actual parameter values remains same. For example consider the following program...
  • 28. #include<stdio.h> #include<conio.h> void main() { int num1, num2 ; void swap(int,int) ; // function declaration clrscr() ; num1 = 10 ; num2 = 20 ; printf("nBefore swap: num1 = %d, num2 = %d", num1, num2) ; swap(num1, num2) ; // calling function printf("nAfter swap: num1 = %dnnum2 = %d", num1, num2); printf("nBefore swap: num1 = %d, num2 = %d", num1, num2) ; getch() ; } void swap(int a, int b) // called function { int temp ; temp = a ; a = b ; b = temp ; } Output: Before swap: num1=10, num2=20 After swap: num1=20, num2=10
  • 29. • In the above example program, the variables num1 and num2 are called actual parameters and the variables a and b are called formal parameters. • The value of num1 is copied into a and the value of num2 is copied into b. • The changes made on variables a and b does not effect the values of num1 and num2.
  • 30. Call by Reference • In Call by Reference parameter passing method, the memory location address of the actual parameters is copied to formal parameters. • This address is used to access the memory locations of the actual parameters in called function. • In this method of parameter passing, the formal parameters must be pointer variables.
  • 31. • That means in call by reference parameter passing method, the address of the actual parameters is passed to the called function and is recieved by the formal parameters (pointers). • Whenever we use these formal parameters in called function, they directly access the memory locations of actual parameters. • So the changes made on the formal parameters effects the values of actual parameters. • For example consider the following program...
  • 32. #include<stdio.h> #include<conio.h> void main(){ int num1, num2 ; void swap(int *,int *) ; // function declaration clrscr() ; num1 = 10 ; num2 = 20 ; printf("nBefore swap: num1 = %d, num2 = %d", num1, num2) ; swap(&num1, &num2) ; // calling function printf("nAfter swap: num1 = %d, num2 = %d", num1, num2); getch() ; } void swap(int *a, int *b) // called function { int temp ; temp = *a ; *a = *b ; *b = temp ; } Output: Before swap: num1=10, num2=20 After swap: num1=20, num2=10
  • 33. • In the above example program, the addresses of variables num1 and num2 are copied to pointer variables a and b. • The changes made on the pointer variables a and b in called function effects the values of actual parameters num1 and num2 in calling function.
  • 34. Storage classes Storage Classes in C: auto, extern, static, register class in C What is Storage Class in C? • A storage class represents the visibility and a location of a variable. • It tells from what part of code we can access a variable. • A storage class in C is used to describe the following things: 1. The variable scope. 2. The location where the variable will be stored. 3. The initialized value of a variable. 4. A lifetime of a variable.
  • 35. Who can access a variable? • Thus a storage class is used to represent the information about a variable. NOTE: A variable is not only associated with a data type, its value but also a storage class. • There are total four types of standard storage classes. • The table below represents the storage classes in C. Storage class Purpose auto It is a default storage class. extern It is a global variable. static It is a local variable which is capable of returning a value even when control is transferred to the function call. register It is a variable which is stored inside a Register.
  • 36. #include<stdio.h> #include<conio.h> int x; //External variable static int count=0; //Static Variable void main() { int z; //Auto Variable or Local Variable register int answer; //Register Variable clrscr(); ++count; //This statement equal to count=count+1 printf("Enter the Value 1:"); scanf("%d",&x); printf("Enter the Value2:"); scanf("%d",&z); answer=x+z; printf("%d.Addition: %d",count,answer); getch(); } Output:
  • 37. #include<stdio.h> #include<conio.h> int fun1(); int fun2(); int fun3(); int fun4(); int val2=200; int main() { printf("Welcome to Storage Classn"); fun1();//Auto fun2();//Static fun3();//Extern fun4();//Register return 0; } int fun1() { auto int a=10; printf("nValue of a: %d n",a); a++; return 0; } int fun2() { static int a=10; printf("nValue of a: %d n",a); a++; return 0; } int fun3() { extern int val1; printf("The value of val2 is %d n",val2); printf("This is my value of val1 is %d n",val1); return 0; } int val1=1000; int fun4() { register int number; for(number=1;number<=5;number++) { printf("Value is stored in register %d n:,number); return 0; } }
  • 39. Recursion in c • Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. void recursion() { recursion(); /* function calls itself */ } int main() { recursion(); }
  • 40. • The C programming language supports recursion, i.e., a function to call itself. • But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop. • Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc.
  • 41.
  • 42. Example: Sum of Natural Numbers Using Recursion include <stdio.h> int sum(int n); int main() { int number, result; printf("Enter a positive integer: "); scanf("%d", &number); result = sum(number); printf("sum = %d", result); return 0; } int sum(int n) { if (n != 0) // sum() function calls itself return n + sum(n-1); else return n; } Output Enter a positive integer:3 sum = 6
  • 43. • Recursive Solution: Factorial can be calculated using following recursive formula. n! = n * (n-1)! n! = 1 if n = 0 or n = 1
  • 44. Factorial of a Number Using Recursion Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.
  • 45. #include<stdio.h> long int multiplyNumbers(int n); int main() { int n; printf("Enter a positive integer: "); scanf("%d",&n); printf("Factorial of %d = %ld", n, multiplyNumbers(n)); return 0; } long int multiplyNumbers(int n) { if (n>=1) return n*multiplyNumbers(n-1); else return 1; } Output: Enter a positive integer: 6 Factorial of 6 = 720
  • 46. Fibonacci Series #include <stdio.h> int fibonacci(int i) { if(i == 0) { return 0; } if(i == 1) { return 1; } return fibonacci(i-1) + fibonacci(i-2); } int main() { int i; for (i = 0; i < 10; i++) { printf("%dtn", fibonacci(i)); } return 0; } Output: 0 1 1 2 3 5 8 13 21 34
  • 47. What is pointer to array • Pointer to an array is also known as array pointer. • We are using the pointer to access the components of the array. int a[3] = {3, 4, 5 }; int *ptr = a; We can likewise declare a pointer that can point to whole array rather than just a single component of the array.
  • 48. • When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array. • Base address i.e address of the first element of the array is also allocated by the compiler. • Suppose we declare an array arr, int arr[5] = { 1, 2, 3, 4, 5 }; Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will be stored as follows:
  • 49. • Here variable arr will give the base address, which is a constant pointer pointing to the first element of the array, arr[0]. • Hence arr contains the address of arr[0] i.e 1000. • In short, arr has two purpose - it is the name of the array and it acts as a pointer pointing towards the first element in the array. • arr is equal to &arr[0] by default • We can also declare a pointer of type int to point to the array arr. int *p; p = arr; // or, p = &arr[0]; //both the statements are equivalent.
  • 50. • Now we can access every element of the array arr using p++ to move from one element to another. • NOTE: You cannot decrement a pointer once incremented. • p-- won't work. Pointer to Array: • As studied above, we can use a pointer to point to an array, and then we can use that pointer to access the array elements. Lets have an example,
  • 51. #include <stdio.h> int main() { int i; int a[5] = {1, 2, 3, 4, 5}; int *p = a; // same as int*p = &a[0] for (i = 0; i < 5; i++) { printf("%d", *p); p++; }  In the above program, the pointer *p will print all the values stored in the array one by one.  We can also use the Base address (a in above case) to act as a pointer and print all the values.
  • 52. Pointers and strings • We know that a string is a sequence of characters which we save in an array. • And in C programming language the 0 null character marks the end of a string. • Creating a string In the following example we are creating a string str using char character array of size 6. char str[6] = "Hello";
  • 53. • The above string can be represented in memory as follows. • Each character in the string str takes 1 byte of memory space.
  • 54. Creating a pointer for the string • The variable name of the string str holds the address of the first element of the array i.e., it points at the starting memory address. • So, we can create a character pointer ptr and store the address of the string str variable in it. • This way, ptr will point at the string str. • In the following code we are assigning the address of the string str to the pointer ptr.
  • 55. char *ptr = str; We can represent the character pointer variable ptr as follows. The pointer variable ptr is allocated memory address 8000 and it holds the address of the string variable str i.e., 1000.
  • 56. Accessing string via pointer • To access and print the elements of the string we can use a loop and check for the 0 null character. • In the following example we are using while loop to print the characters of the string variable str.
  • 57. #include <stdio.h> int main(void) { // string variable char str[6] = "Hello"; // pointer variable char *ptr = str; // print the string while(*ptr != '0') { printf("%c", *ptr); // move the ptr pointer to the next memory location ptr++; } return 0; }
  • 58. Using pointer to store string • We can achieve the same result by creating a character pointer that points at a string value stored at some memory location. • In the following example we are using character pointer variable strPtr to store string value.
  • 59. #include <stdio.h> int main(void) { // pointer variable to store string char *strPtr = "Hello"; // temporary pointer variable char *t = strPtr; // print the string while(*t != '0') { printf("%c", *t); // move the t pointer to the next memory location t++; } return 0; }
  • 60. • Note! In the above code we are using another character pointer t to print the characters of the string as because we don't want to lose the starting address of the string "Hello" which is saved in pointer variable strPtr.
  • 61.
  • 62. • In the above image the string "Hello" is saved in the memory location 5000 to 5005. • The pointer variable strPtr is at memory location 8000 and is pointing at the string address 5000. • The temporary variable is also assigned the address of the string so, it too holds the value 5000 and points at the starting memory location of the string "Hello".
  • 63. Pointer Arithmetic • A pointer in c is an address, which is a numeric value. • Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value. • There are four arithmetic operators that can be used on pointers: ++, --, +, and - • To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. • Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer.
  • 64. ptr++ After the above operation, the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer location which is 4 bytes next to the current location. This operation will move the pointer to the next memory location without impacting the actual value at the memory location. If ptr points to a character whose address is 1000, then the above operation will point to the location 1001 because the next character will be available at 1001.
  • 65. Incrementing a Pointer • We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. • The following program increments the variable pointer to access each succeeding element of the array.
  • 66. #include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have array address in pointer */ ptr = var; for ( i = 0; i < MAX; i++) { printf("Address of var[%d] = %xn", i, ptr ); printf("Value of var[%d] = %dn", i, *ptr ); /* move to the next location */ ptr++; } return 0; } Output: Address of var[0] = bf882b30 Value of var[0] = 10 Address of var[1] = bf882b34 Value of var[1] = 100 Address of var[2] = bf882b38 Value of var[2] = 200
  • 67. Decrementing a Pointer • The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type as shown below.
  • 68. #include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have array address in pointer */ ptr = &var[MAX-1]; for ( i = MAX; i > 0; i--) { printf("Address of var[%d] = %xn", i-1, ptr ); printf("Value of var[%d] = %dn", i-1, *ptr ); /* move to the previous location */ ptr--; } return 0; } Output: Address of var[2] = bfedbcd8 Value of var[2] = 200 Address of var[1] = bfedbcd4 Value of var[1] = 100 Address of var[0] = bfedbcd0 Value of var[0] = 10
  • 69. Pointer Comparisons • Pointers may be compared by using relational operators, such as ==, <, and >. • If p1 and p2 point to variables that are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared. • The following program modifies the previous example − one by incrementing the variable pointer so long as the address to which it points is either less than or equal to the address of the last element of the array, which is &var[MAX - 1].
  • 70. #include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have address of the first element in pointer */ ptr = var; i = 0; while ( ptr <= &var[MAX - 1] ) { printf("Address of var[%d] = %xn", i, ptr ); printf("Value of var[%d] = %dn", i, *ptr ); /* point to the next location */ ptr++; i++; } return 0; } Output: Address of var[0] = bfdbcb20 Value of var[0] = 10 Address of var[1] = bfdbcb24 Value of var[1] = 100 Address of var[2] = bfdbcb28 Value of var[2] = 200
  • 71. Pointer Arithmetic on Arrays: • Pointers contain addresses. • Adding two addresses makes no sense because there is no idea what it would point to. • Subtracting two addresses lets you compute the offset between the two addresses. • An array name acts like a pointer constant. • The value of this pointer constant is the address of the first element. • For Example: if an array named arr then arr and &arr[0] can be used to reference array as a pointer. • Below is the program to illustrate the Pointer Arithmetic on arrays:
  • 72. / C program to illustrate the array // traversal using pointers #include <stdio.h> // Driver Code int main() { int N = 5; // An array int arr[] = { 1, 2, 3, 4, 5 }; // Declare pointer variable int* ptr; // Point the pointer to first element in array arr[] ptr = arr; // Traverse array using ptr for (int i = 0; i < N; i++) { // Print element at which // ptr points printf("%d ", ptr[0]); ptr++; } } Output: 1 2 3 4 5
  • 73. Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() • Since C is a structured language, it has some fixed rules for programming. One of it includes changing the size of an array. An array is collection of items stored at continuous memory locations.
  • 74. • As it can be seen that the length (size) of the array above made is 9. • But what if there is a requirement to change this length (size). • For Example, • If there is a situation where only 5 elements are needed to be entered in this array. • In this case, the remaining 4 indices are just wasting memory in this array. So there is a requirement to lessen the length (size) of the array from 9 to 5. • Take another situation. • In this, there is an array of 9 elements with all 9 indices filled. • But there is a need to enter 3 more elements in this array. • In this case 3 indices more are required. • So the length (size) of the array needs to be changed from 9 to 12. • This procedure is referred to as Dynamic Memory Allocation in C.
  • 75. • Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime. • C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are: • malloc() • calloc() • free() • realloc() • Let’s look at each of them in greater detail.
  • 76. C malloc() method • “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with default garbage value. Syntax: ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int)); • Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.
  • 77. • If space is insufficient, allocation fails and returns a NULL pointer.
  • 78. #include <stdio.h> #include <stdlib.h> int main() { // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %dn", n); // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL) { printf("Memory not allocated.n"); exit(0); } else { // Memory has been successfully allocated printf("Memory successfully allocated using malloc.n"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0; } Output: Enter number of elements: 5 Memory successfully allocated using malloc. The elements of the array are: 1, 2, 3, 4, 5,
  • 79. C calloc() method • “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each block with a default value ‘0’. • Syntax: ptr = (cast-type*)calloc(n, element-size); • For Example: ptr = (float*) calloc(25, sizeof(float)); • This statement allocates contiguous space in memory for 25 elements each with the size of the float.
  • 80. • If space is insufficient, allocation fails and returns a NULL pointer.
  • 81. #include <stdio.h> #include <stdlib.h> int main() { // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %dn", n); // Dynamically allocate memory using calloc() ptr = (int*)calloc(n, sizeof(int)); // Check if the memory has been successfully // allocated by calloc or not if (ptr == NULL) { printf("Memory not allocated.n"); exit(0); } else { // Memory has been successfully allocated printf("Memory successfully allocated using calloc.n"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0; } Output: Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5,
  • 82. • “free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. Syntax: free(ptr); C free() method
  • 83.
  • 84. #include <stdio.h> #include <stdlib.h> int main() { // This pointer will hold the // base address of the block created int *ptr, *ptr1; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %dn", n); // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Dynamically allocate memory using calloc() ptr1 = (int*)calloc(n, sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL || ptr1 == NULL) { printf("Memory not allocated.n"); exit(0); } else { // Memory has been successfully allocated printf("Memory successfully allocated using malloc.n"); // Free the memory free(ptr); printf("Malloc Memory successfully freed.n"); // Memory has been successfully allocated printf("nMemory successfully allocated using calloc.n"); // Free the memory free(ptr1); printf("Calloc Memory successfully freed.n"); } return 0; }
  • 85. Output: Enter number of elements: 5 Memory successfully allocated using malloc. Malloc Memory successfully freed. Memory successfully allocated using calloc. Calloc Memory successfully freed.
  • 86. C realloc() method • “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-allocation of memory maintains the already present value and new blocks will be initialized with default garbage value. Syntax: ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.
  • 87. If space is insufficient, allocation fails and returns a NULL pointer.
  • 88. #include <stdio.h> #include <stdlib.h> int main() { // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %dn", n); // Dynamically allocate memory using calloc() ptr = (int*)calloc(n, sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL) { printf("Memory not allocated.n"); exit(0); } else { // Memory has been successfully allocated printf("Memory successfully allocated using calloc.n"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } // Get the new size for the array n = 10; printf("nnEnter the new size of the array: %dn", n); // Dynamically re-allocate memory using realloc() ptr = realloc(ptr, n * sizeof(int)); // Memory has been successfully allocated printf("Memory successfully re-allocated using realloc.n"); // Get the new elements of the array for (i = 5; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } free(ptr); } return 0; }
  • 89. Output: Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5, Enter the new size of the array: 10 Memory successfully re-allocated using realloc. The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,