Unit-2 C - MCA
Unit-2 C - MCA
Every C program must contain at least one function called main(). However, a program
may also contain other functions.
1) Function Declaration: The function declaration tells the compiler about function name, the data
type of the return value and parameters. The function declaration is also called a function
prototype. The function declaration is performed before the main function or inside the main
function or any other function.
• returnType functionName(parametersList);
In the above syntax, returnType specifies the data type of the value which is sent as a return
value from the function definition. The functionName is a user-defined name used to identify the
function uniquely in the program. The parametersList is the data values that are sent to the
function definition.
2) Function Definition: The function definition provides the actual code of that function. The
function definition is also known as the body of the function. The actual task of the function is
implemented in the function definition. That means the actual instructions to be performed by a
function are written in function definition. The actual instructions of a function are written inside
the braces "{ }". The function definition is performed before the main function or after the main
function.
returnType functionName(parametersList)
{
Actual code...
3) Function Call : The function call tells the compiler when to execute the function definition.
When a function call is executed, the execution control jumps to the function definition where the
actual code gets executed and returns to the same functions call once the execution completes. The
function call is performed inside the main function or any other function or inside the function
itself.
functionName(parameters);
Advantages:
• Using functions we can implement modular programming.
• Functions make the program more readable and understandable.
• Using functions the program implementation becomes easy.
• Once a function is created it can be used many times (code re-usability).
• Using functions larger programs can be divided into smaller modules.
In C Programming Language, based on providing the function definition, functions are divided
into two types. Those are as follows...
a) System Defined Functions: These pre-defined functions are known as system defined
functions. The system defined function is defined as follows...
The function whose definition is defined by the system is called as system defined function.
The system defined functions are also called as Library Functions or Standard
Functions or Pre-Defined Functions. The implementation of system defined functions is already
defined by the system. Example : printf(), scanf(), sqrt(), abs(), pow() etc.
b) User Defined Functions: In C programming language, users can also create their own
functions. The functions that are created by users are called as user defined functions. The user
defined function is defined as follows...
The function whose definition is defined by the user is called as user defined function.
II) Purpose Return statement: The return statement is used to terminate the execution of a
function and transfer program control back to the calling function. In addition, it can specify a
value to be returned by the function. A function may contain one or more return statements. The
general format of the return statement is given below.
return expr or value ;
Example:
void main()
{
int sum = sumDigits();
printf("%d\n", sum);
return;
}
int sumDigits()
{
int sum = 0; int digit;
for(digit = 0; digit <= 9; ++digit)
{
sum += digit;
}
return sum;
}
III) Types of user Defined functions:
• Function without Parameters and without Return value
• Function with Parameters and without Return value
• Function without Parameters and with Return value
• Function with Parameters and with Return value
1) Function without Parameters and without Return value: In this type of functions there is no data
transfer between calling function and called function. Simply the execution control jumps from calling-
function to called function and executes called function, and finally comes back to the calling function. For
example, consider the following program...
#include<stdio.h>
#include<conio.h>
void main(){
void addition() ; // function declaration
clrscr() ;
addition() ; // function call
getch() ;
}
void addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}
2) Function with Parameters and without Return value : In this type of functions there is data
transfer from calling-function to called function (parameters) but there is no data transfer from
called function to calling-function (return value). The execution control jumps from calling-
function to called function along with the parameters and executes called function, and finally
comes back to the calling function. For example, consider the following program...
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
getch() ;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
3) Function without Parameters and with Return value: In this type of functions there is no
data transfer from calling-function to called-function (parameters) but there is data transfer from
called function to calling-function (return value). The execution control jumps from calling-
function to called function and executes called function, and finally comes back to the calling
function along with a return value. For example, consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int result ;
int addition() ; // function declaration
clrscr() ;
result = addition() ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}
4) Function with Parameters and with Return value
In this type of functions there is data transfer from calling-function to called-function (parameters)
and also from called function to calling-function (return value). The execution control jumps from
calling-function to called function along with parameters and executes called function, and finally
comes back to the calling function along with a return value. For example, consider the following
program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
clrscr() ;
getch() ;
Points to be Remembered
• Call by Value
• Call by Reference
1) 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 do 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...
Example 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\nnum2 = %d", num1, num2);
getch() ;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a=b;
b = temp ;
}
2) 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...
Example :
#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 ;
}
V) Storage Classes:
In C programming language, storage classes are used to define things like storage
location (whether RAM) scope, lifetime and the default value of a variable.
In C programming language, there are FOUR storage classes and they are as follows...
• auto storage class
• extern storage class
• static storage class
• register storage class
1) Auto storage class: The default storage class of all local variables (variables declared inside
block or function) is auto storage class. Variable of auto storage class has the following
properties...
Property Description
Keyword auto
Life time Till the control remains within the block in which variable is
defined
Example :
#include<stdio.h>
#include<conio.h>
int main(){
auto int a=10;
{
auto int a=20;
printf("%d",a);
}
printf(" %d",a);
return 0;
}
2) External storage class : The default storage class of all global varibles (variables declared
outside function) is external storage class. Variable of external storage class has the following
properties...
Property Description
Keyword extern
Life time As long as the program’s execution does not comes to end
Example:
#include<stdio.h>
#include<conio.h>
int i; //By default it is extern variable
int main(){
printf("%d",i);
return 0;
}
3) Static storage class : The static storage class is used to create variables that hold value beyond
its scope until the end of the program. The static variable allows to initialize only once and can be
modified any number of times. Variable of static storage class has the following properties...
Property Description
Keyword static
Life time The value of the persists between different function calls (i.e.,
Initialization is done only once)
Example:
void sum()
{
static int a = 10;
static int b = 24;
printf("%d %d \n",a,b);
a++;
b++;
}
void main()
{
int i;
for(i = 0; i< 3; i++)
{
sum(); // The static variables holds their value between multiple function calls.
}
}
4) Register storage class : The register storage class is used to specify the memory of the variable
that has to be allocated in CPU Registers. The memory of the register variable is allocated in CPU
Register but not in Computer memory (RAM). The register variables enable faster accessibility
compared to other storage class variables. As the number of registers inside the CPU is very less
we can use very less number of register variables. Variable of register storage class has the
following properties...
Property Description
Keyword register
Life time Till the control remains within the block in which variable is
defined.
Example:
#include<stdio.h>
#include<conio.h>
int main(){
scanf("%d%d",&a,&b);
printf("%d %d",a,b);
VI) Recursion:
In C programming language, function calls can be made from the main() function, other
functions or from the same function itself. The recursive function is defined as follows...
A function called by itself is called recursive function.
There are 2 type of recursion:
• Direct Recursion
• Indirect Recursion
1) Direct Recursion: When a function calls itself within the same function repeatedly, it is
called the direct recursion.
Example:
#include<stdio.h>
#include<conio.h>
int factorial( int ) ;
int main()
{
int fact, n ;
printf("Enter any positive integer: ") ;
scanf("%d", &n) ;
fact = factorial( n ) ;
printf("\nFactorial of %d is %d\n", n, fact) ;
return 0;
}
int factorial( int n )
{
int temp ;
if( n == 0)
return 1 ;
else
temp = n * factorial( n-1 ) ; // recursive function call
return temp ;
}
Explanation:
2) Indirect recursion: When a function is mutually called by another function in a circular manner, the
function is called an indirect recursion function.
Example :
int fact1(int);
int fact2(int);
void main()
{
printf("%d", fact1(5));
getch();
}
int fact1(int n)
{
if(n==1)
return 1;
else
return n*fact2(n-1);
}
int fact2(int n)
{
if(n==1)
return 1;
else
return n*fact1(n-1);
}
Pointers
I) Introduction Pointers:
In the c programming language, we use normal variables to store user data values. When we
declare a variable, the compiler allocates required memory with the specified name. In the c
programming language, every variable has a name, datatype, value, storage class, and address. We
use a special type of variable called a pointer to store the address of another variable with the same
datatype. A pointer is defined as follows...
Pointer is a special type of variable used to store the memory location address of a variable.
In the c programming language, we can create pointer variables of any datatype. Every
pointer stores the address the variable with same datatype only. That means integer pointer is used
store the address of integer variable only.
Accessing the Address of Variables: In c programming language, we use the reference operator
"&" to access the address of variable. For example, to access the address of a
variable "marks" we use "&marks". We use the following printf statement to display memory
location address of variable "marks"...
Example Code
datatype *pointerName ;
Example Code
int *ptr ;
clrscr();
ptr = &a ;
AddressAtPointer + ( NumberToBeAdd *
BytesOfMemoryRequiredByDatatype )
Example Program
void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000
1) Void Pointers : Till now, we have studied that the address assigned to a pointer should be of
the same type as specified in the pointer declaration. For example, if we declare the int pointer,
then this int pointer cannot point to the float variable or some other type of variable, i.e., it can
point to only int type variable. To overcome this problem, we use a pointer to void. A pointer to
void means a generic pointer that can point to any data type. We can assign the address of any
data type to the void pointer, and a void pointer can be assigned to any type of the pointer
without performing any explicit typecasting.
Example :
#include<stdio.h>
int main()
{
int a=56; // initialization of a integer variable 'a'. float
b=4.5; // initialization of a float variable 'b'. char c='k'; //
initialization of a char variable 'c'. void *ptr; //
declaration of void pointer.
// assigning the address of variable 'a'.
ptr=&a;
printf("value of 'a' is : %d",*((int*)ptr));
// assigning the address of variable 'b'.
ptr=&b;
printf("\nvalue of 'b' is : %f",*((float*)ptr));
// assigning the address of variable 'c'.
ptr=&c;
printf("\nvalue of 'c' is : %c",*((char*)ptr)); return
0;
}
Output:
2) NULL pointer : A Null Pointer is a pointer that does not point to any memory location. It
stores the base address of the segment. The null pointer basically stores the Null value while void
is the type of the pointer.
A null pointer is a special reserved value which is defined in a stddef header file. Here, Null
means that the pointer is referring to the 0th memory location.
If we do not have any address which is to be assigned to the pointer, then it is known as a null
pointer. When a NULL value is assigned to the pointer, then it is considered as a Null pointer.
Example :
Example :
#include<stdio.
h> int *call();
int
main(){
int *ptr;
ptr=call()
;
fflush(std
in);
printf("%d",*p
tr); return 0;
}
int * call(){
static int
x=25;
++x;
return &x;
}
3) Function Pointers :
Function Pointers point to code like normal pointers.
In Functions Pointers, function’s name can be used to get function’s address.
A function can also be passed as an arguments and can be returned from a function.
Example :
#include<stdio.h>
int subtraction (int a, int b)
{
return a-b;
}
int main() {
int (*fp) (int, int)=subtraction;
//Calling function using function pointer
int result = fp(5, 4);
printf(" Using function pointer we get the result: %d",result);
return 0;
}
Sometimes the size of the array you declared may be insufficient. To solve this issue,
you can allocate memory manually during run-time. This is known as dynamic memory
allocation in C programming. To allocate memory dynamically, library functions are
malloc(), calloc(), realloc() and free() are used. These functions are defined in the
<stdlib.h> header file.
1) C malloc() : The name "malloc" stands for memory allocation. The malloc()
function reserves a block of memory of the specified number of bytes. And, it returns
a pointer of void which can be casted into pointers of any form.
4) free(): Dynamically allocated memory created with either calloc() or malloc() doesn't
get freed on their own. You must explicitly use free() to release the space.
Example: free(ptr);
Program on malloc() :
#include<stdli.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be
allocated if(ptr == NULL)
{
printf("Error! memory not
allocated."); exit(0);
}
printf("Enter elements: ");
Program on realloc();
#include<stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%u\n",ptr + i);
printf("\nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));
V) Pointer to Array:
Use a pointer to an array, and then use that pointer to access the array elements. For example,
#include<stdio.h>
void main()
{
int a[3] = {1, 2, 3};
int *p = a;
Array of Pointers
EXAMPLE :
#include<stdio.
h> int main()
{
int *arr[5];
int a = 10, b = 20, c = 30, d = 40, e = 50, i;
arr[0] = &a;
arr[1] = &b;
arr[2] = &c;
arr[3] = &d;
arr[4] = &e;
printf("Address of a = %p\n",arr[0]);
printf("Address of b = %p\n",arr[1]);
printf("Address of c = %p\n",arr[2]);
printf("Address of d = %p\n",arr[3]);
printf("Address of e = %p\n",arr[4]);
for(i = 0; i < size; i++)
printf("value stored at arr[%d] = %d\n",i,*arr[i]);
return 0;
}
Structures and Unions
I) Introduction to Structures:
In C programming language, a structure is a collection of elements of the different data
type. The structure is used to create user-defined data type in the C programming language.
As the structure used to create a user-defined data type, the structure is also said to be “user-
defined data type in C”.
Structure is a collection of different type of elements under a single name that acts as
user defined data type in C.
Generally, structures are used to define a record in the c programming language. Structures
allow us to combine elements of a different data type into a group. The elements that are
defined in a structure are called members of structure.
struct <structure_name>
{
data_type member1;
data_type member2, member3;
.
.
};
Following is the example of creating a structure called Student which is used to hold student
record.
Creating structure in C :
struct Student
{
char stud_name[30];
int roll_number;
float percentage;
};
Creating and Using structure variables:
In a c programming language, there are two ways to create structure variables. We can create
structure variable while defining the structure and we can also create after terminating
structure using struct keyword.
To access members of a structure using structure variable, we use dot (.) operator.
Consider the following example code...
struct Student
char stud_name[30];
int roll_number;
float percentage;
void main(){
printf("Name : ");
scanf("%s", stud_1.stud_name);
scanf("%d", &stud_1.roll_number);
printf("Percentage : ");
scanf("%f", &stud_1.percentage);
Memory allocation of Structure: When the structures are used in the c programming
language, the memory does not allocate on defining a structure. The memory is allocated
when we create the variable of a particular structure. As long as the variable of a structure is
created no memory is allocated. The size of memory allocated is equal to the sum of memory
required by individual members of that structure. In the above example program, the
variables stud_1 and stud_2 are allocated with 36 bytes of memory each.
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
return 0;
}
III) Structure Pointer:
The structure pointer points to the address of a memory block where the Structure is
being stored. Like a pointer that tells the address of another variable of any data type (int,
char, float) in memory. And here, we use a structure pointer which tells the address of a
structure in memory by pointing pointer variable ptr to the structure variable.
Declare a Structure Pointer
The declaration of a structure pointer is similar to the declaration of the structure
variable. So, we can declare the structure pointer and variable inside and outside of the
main() function. To declare a pointer variable in C, we use the asterisk (*) symbol before the
variable's name.
struct structure_name *ptr;
Access Structure member using pointer: There are two ways to access the member of the
structure using Structure pointer:
1. Using ( * ) asterisk or indirection operator and dot ( . ) operator.
2. Using arrow ( -> ) operator or membership operator.
Union is a collection of different type of elements under a single name that acts as user
defined data type in C.
To create union in c, we use the keyword called "union". We use the following syntax to create
unions in c programming language.
union <structure_name>
{
data_type member1;
data_type member2, member3;
.
.
};
Following is the example of creating a union called Student which is used to hold student record.
Creating union in C
union Student
char stud_name[30];
int roll_number;
float percentage;
};
Creating and using union variables : In a c programming language, there are two ways to
create union variables. We can create union variable while the union is defined and we can
also create after terminating union using union keyword.
TO access members of a union using union variable, we use dot (.) operator. Consider
the following example code...
Structure Union
You can use a struct keyword to define a You can use a union keyword to define a
structure. union.
Every member within structure is assigned a In union, a memory location is shared by
unique memory location. all the data members.
Changing the value of one data member
Changing the value of one data member will
will change the value of other data
not affect other data members in structure.
members in union.
It enables you to initialize several members It enables you to initialize only the first
at once. member of union.
The total size of the structure is the sum of The total size of the union is the size of
the size of every data member. the largest data member.
It is mainly used for storing various data It is mainly used for storing one of the
types. many data types that are available.
It occupies space for each and every member It occupies space for a member having the
written in inner parameters. highest size written in inner parameters.
You can access one member at a time in
You can retrieve any member at a time.
the union.
It supports flexible array. It does not support a flexible array.