POP Module 3
POP Module 3
Functions:
Definition :
A function is a collection of statements that perform a specific task
These functions are very useful to read write and debug complex programs
Types of Functions
These can be broadly classified into two types
1) String manipulation functions:- The header file which includes string manipulation
functions is “#include<string.h>”
User defined functions: - The user defined function is defined by the user according
to its requirements instead of relying only on the built-in functions C allows us to create
our own function called user defined function
syntax:
return_type function_name(argument _list);
Where,
return_type :- is the data type of the value that is returned or sent from the function.
function_name :-function should be given a descriptive name
argument _list :- contains type and names of the variables that must be passed to the
function. Example:-
is a function declaration with function_name “large” with return _type “integer” and has
two arguments “x” and “y” of integer type.
NOTE:-
if we define a function before main ( ) function the there is no need of function
declaration
if we define the function after main ( ) function then it is mandatory to declare the
function because it will inform the compiler.
Function call or calling function :- invoking the function with valid number of
arguments and valid data type is called as function call.
To call a function one simply needs to pass the required parameters along with the function
name and if the function returns the value then one can store the returned value.
Syntax:
Where,
Example:-
large (m,n);
Syntax
local_variable_declaration;
Where,
return type :- when the function is called the function may or may not return a value
If the function returns a value then the return_type will be any appropriate data type
(int, float, char etc) and we use the keyword “return” to return the value.
If the function does not return a value then the return_type will be “void” and no need to
use the keyword “return”
local_variable_declaration:- these are temporary variables which are required only within this
function.
function _body:- The body of the function contains the collection of statements that define
what the function does.
when the program makes the function call the program control is transferred to the called
function. This called function performs the defined task and returns the program control back to
the main( ) function.
#include<stdio.h> f
void main()
{
float r,x;
printf("Enter the radius\n");
scanf("%f",&r);
x=area(r);
float area(float r)
float x; x=3.142*r*r;
return x;
Parameter passing mechanism :- There are two methods by which parameters or arguments
can be passed to the function
#include<stdio.h>
void main()
{
int n,x;
printf("Enter the value of n\n");
scanf("%d",&n);
x=sum(n);
printf("Sum of natural numbers=%d\n",x);
}
int sum(int n)
int res=0,i;
for(i=1;i<=n;i++)
res=res+i;
return res;
C does not support directly passing by reference. It is done indirectly by passing the address of
the variable and changing the value of the variable through its address.
#include<stdio.h>
void swap(int *a,int *b);
void main()
{
int a,b;
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
printf("Before Swapping\n a=%d\t b=%d\n",a,b);
swap(&a, &b);
*b=temp;
Scope of Variables :
In C, all constants and variables have a defined scope. By scope we mean the accessibility and
visibility oft he variables at different points in the program.
1) Block Scope: If a variable is declared within a statement block then as soon as the
control exits that block, the variable will cease to exist. Such a variable also known
as local variable is said to have a block scope.
The scope of the variable is only within the function it is declared with.
3) Program Scope : Global variables :- global variables are also called external
variables These are the variables which are used by or accessible from any
function present in the program These variables are declared before the main( )
function.
4) File Scope: When a global variable is accessible until the end oft he file, the
variable is said to have file scope. To allow a variable to have file scope, declare
that variable with the static keyword before specifying ist data type:
Static int x= 10;
A global static variable can be used anywhere from the file in which it is declared
but it is not accessible by any other file. Such variables are useful when the programmer writes
his own header file.
Storage Classes:
Storage class defines the scope and lifetime of variables and/or functions declared within a C
program. In addition it also gives the following information about the variable or function
• Determine the part of memory where storage space will be allaocted for variable or
function.
• Specifies how long storage will continue to exist
• Specifies the scope of variable or function
• Specifies whether variable or function has internal, external or no linkage
• Specifies whether the variable will be automatically initialized to zero or to any
indeterminate value.
Types:
1. auto Storage Class : The auto storage class specifier is used ot explicitly declare a
variable with automatic sotrage.
2. register Storage Class: When a variable is declared using register as its storage class
class, it is stored in a CPU register instead of RAM. Since the variable is stored in a
register, the maxmium size of a the variable is equal to the register size.
A register variable is declared in the following manner:
register int x;
3. extern Storage Class: A large C program can be broken down in to smaller programs.
When these smaller programs are compiled, they are joined together to form a large
program. However, these smaller programs may need to share certain variables for
processing.
The extern storage class is used to give a reference of a global variable that is visible to all
the program files. When there are multiple files in a program and we need to use a
particular fucntion or variable in a file apart from which it is declared, then use the extern
keyword.
extern int x ;
External variables may be declared outside any function in a source code file as any other
variable is declared.
4. Static Storage Class: While auto is the default storage class for all local variables,
static is the default storage class for all global variables. Static variables have a lifetime
over the entire program, Memory for the static variables is allocated when the program
begins running and is freed when the program terminates.
Static local variables when defined within a function are initialized at the runtime.
Recursive Functions:
when a function calls itself again and again it is called as recursion
Here the calling function and called function are same.It is a powerful technique of writing
complex algorithms in an easier way. The recursive function must always have a stopping
condition or an exit condition in the function else the program will go into infinite loop
Factorial of a given Number:-we can calculate the factorial of a given number using the
formula
There are several approaches to solve a given problem like useage of while do- while or for
loop. Now, let us try to find the solution to this classic example using the concept of recursion.
#include<stdio.h>
int n,res;
printf("Enter the value of n\n");
scanf("%d",&n);
res=factorial(n);
printf("The factorial of the number=%d\n",res);
int factorial(int n)
if(n==0)
return 1;
else
return n*factorial(n-1);
If you observe the above pattern sequence the First number is 0 the Second number is 1and the
subsequent number is the result of sum of the previous two numbers,(Example Third number is
0+1=1,Fourth number is 1+1=2 and so on..) There are several approaches to solve a given
problem like useage of while do- while or for loop. Now, let us try to find the solution to this
classic example using the concept of recursion.
#include<stdio.h>
void main()
{
int num,i;
printf("Enter the number up to which you want\n");
printf("%d\t",fibonacci(i));
int fibonacci(int n)
if(n==0)
return 0;
else if(n==1)
return 1;
else
return (fibonacci(n-1)+fibonacci(n-2));
Arrays :
Why Arrays ?
Consider a situation, where we need to store 5 integer numbers. If we use simple variable and
data type concepts, then we need 5 variables of int data type and program will be something as
follows:
int number1;
int number2;
int number3;
int number4;
int number5;
number1 = 10;
number2 = 20;
number3 = 30;
number4 = 40;
number5 = 50;
printf( "number1: %d \n", number1); printf( "number2: %d \n", number2); printf( "number3:
%d \n", number3); printf( "number4: %d \n", number4); printf( "number5: %d ", number5);
It was simple, because we had to store just 5 integer numbers. Now let's assume we have to
store 5000 integer numbers, so what is next???
To handle such situation, C language provides a concept called the ARRAY Examples where
arrays can be used are
Definition of an Array:- Array is a collection of elements of same data type. The elements
are stored sequentially one after the other in memory.
Types of Array
• Single dimensional array or One dimensional array
• Two dimensional array
• Multi dimensional array
Single Dimensional Array :- An Array which has only one subscript is known as
Single dimensional array or One dimensional array
The individual array elements are processed by using a common array name with
different index values that start with Zero and ends with array_size-1
data_type array_name[array_size];
where,
data_type: can be int, float or char
array_name: is name of the array
array_size : an integer constant indicating the maximum number of data elements to be
stored. Example: int a[5];
Here a is an Integer Array that can hold up to 5 values in it.
Array Representation
Here
a[0] holds the first element in the array
a[1] holds second element in the array a[2] holds third element in the array and so on..
• Static initialization
• Initialization of array elements one by one.
• Partial initialization of array
• Array initialization without specifying the size
• Run Time array Initialization
•
1. Static initialization:- We can initialize the array in the same way as the ordinary
values when they are declared.
Example:
int b[4]={10,12,14,16};
Here each value will be stored in respective index values of the array.
i.e in location b[0] we store the value 10, in location b[1] we store the value 12 and so on...
Suppose if we try to insert more values then the size of the array it will give us an error “Excess
elements in array initializer”
Example:
int b[4]={10,12,14,16,18};
Here the size of the array b is 4 but we are trying to store 5 values hence we will be getting the
error in this case.
2. Initialization of array elements one by one:- Here the user has the liberty to select the
locations and store values and the array. This type of initialization is not used much practically
Example
int b[4];
Only the array locations specified by the user will contain the values which the user wants the
other locations of array will either be 0 or some garbage value.
3. Partial initialization of array :- If the number of values initialized in the array is less than
the size of the array then it is called partial initialization. The remaining locations in the array
will be initialized to zero or NULL(‘\0’) value automatically
Example:
int b[4]={10,12};
4. Array initialization without specifying the size :- Here the size or the array is not specified
by the user, the compiler will decide the size based on the number of values declared in the
array.
Example:
int b[ ]={6,12,18};
Here the size of the array is specified and the compiler will set the array size as 3 for this
example
5. Run Time array Initialization:- If the values are not known by the programmer in advance
then the user makes use of run time initialization. It helps the programmer to read unknown
values from the end users of the program from keyboard by using input function scanf().
Here we make use of a looping construct to read the input values from the keyboard and store
them sequentially in the array.
#include<stdio.h>
void main()
{
int b[5],i;
printf(“Enter 5 elements\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&b[i]);
We can access the elements of array using index or subscript of element. An index gives the
portion of element in the array .To access an array element make use of array_name[index]
To access value 16 we write b[2]=16 similarly if we wish to print the value 18 we write
printf(“%d”,b[3]);
#include<stdio.h>
void main()
{
scanf(“%d”,&n);
Printf(“Enter the array elements\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
for(i=0;i<n;i++)
{
printf(“%d\t”,a[i]);
#include<stdio.h>
void main()
{
#include<stdio.h>
void main()
{
Information Science and Engineering, JIT
Principles of Programming Using C BPOPS203
scanf(“%d”,&n);
printf(“The first %d natural numbers are:\n”,n);
for(i=0;i<n;i++)
{
a[i]=i+1;
printf("a[%d]=%d\n",i,a[i]);
include<stdio.h>
void main()
{
scanf(“%d”,&n);
printf(“Enter the elements of Array A\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“Enter the elements of Array B\n”);
for(i=0;i<n;i++)
scanf(“%d”,&b[i]);
printf(“Array Addition\n”);
for(i=0;i<n;i++)
c[i]=a[i]+b[i];
printf(“The resultant array is \n”);
for(i=0;i<n;i++)
printf(“%d\n”,c[i]);
Operations on Array:
1) Traversing an array
2) Inserting an element in an array
3) Deleting an element from an array
4) Merging two array
5) Searching an element in an array
6) Sorting an array in ascending or descending order
• Traversing an array : Traversing an array means accessing each and every element oft
he arry for a specific purpose.
• Merging two array : Combining two arrays in to a single array. Joining oft wo different
array in to one array.
Searching Techniques:
The process of finding a particular element in the large amount of data is called searching.
Linear search:- A Linear search is also called as sequential Search. In this technique we search
for a given specific element called as key element in the large list of data in sequential order. If
the key element is present in the list of data then the search is successful otherwise search is
unsuccessful.
Benefits:
• Simple approach
• Works well for small arrays
• Used to search when the elements are not sorted
Disadvantages:
Binary Search: It is fast search algorithm which works on the principle of divide and conquer.
for this algorithm to work properly the data collection should be in the sorted form
3. Continue steps 1. and 2. until either the value is found or there are no more elements to
examine
Advantages:
The Process of arranging the elements in ascending or descending order is called sorting
Bubble sort: The sorting algorithm is a comparison based algorithm in which each pair of
adjacent elements is compared and the elements are swapped if they are not in order. This
algorithm is not suitable for large datasets as its average and worst case time complexity are of
O(n2). where n is the number of items.
Passing Addresses :
Like ordniary variables, we can pass the address of an individual array element by preceding
the indexed array element with the address operator (&).
When an entire array is to be sent tot he called function, the calling function just needs to pass
the name of array.
Syntax:
data_type array_name [size1] [size2];
where,
data_type: is the type of data to be stored and processed in the computer’s memory
array_name: is a valid identifier representing name of the array , [size1]: indicates number of
rows in the array, [size2]: indicates the number of columns in the array.
Example :
int a[2][3];
Represents a is a two dimensional integer array that holds two rows and three columns.
1)Initializing all elements row wise:- A multidimensional array can be initialized by specifying
bracketed values for each row.
Example:
int[2][3]={{5,3,4} {6,1,2}} ;
The feasible way of accessing elements in a two dimensional array is by using nested loops.
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d", &a[i][j]);
Printing 2D array
where m-rowsize, n-columnsize, i-row index and j-column index
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d", a[i][j]);
printf(“\n”)
Multidimensional Array: