0% found this document useful (0 votes)
65 views26 pages

POP Module 3

Bpops103 or bpops203 module5 notes, vtu

Uploaded by

darshangowda0525
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
65 views26 pages

POP Module 3

Bpops103 or bpops203 module5 notes, vtu

Uploaded by

darshangowda0525
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 26

Principles of Programming Using C BPOPS203

Module – 2 – Functions and Arrays :

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

(i) Built-in functions

(ii) User defined functions

C provides various built-in functions, few of them are as follows

1) String manipulation functions:- The header file which includes string manipulation
functions is “#include<string.h>”

Some of the string manipulation functions are:

• strlen( ) :- returns the length of the string.


• strcmp( ) :-used to compare two strings.
• strcpy( ) :-used to copy one string to another
• strcat( ) :- used to concatenate two strings
• strrev( ) :- used to find reverse of the string
• strlwr( ) and strupr( ) :- to convert strings to lower case and uppercase respectively

2) Mathematical functions: - the header file that includes Mathematical functions is


“#include<math.h>”

Some of the Mathematical functions are:

• fabs(n) :- returns absolute value of the floating point number


• ceil(n) :- returns smallest integer value grater than or equal to n
• floor(n) :- returns largest integer value smaller than or equal to n
• exp(n) :- returns e raised to the given power n
• sqrt(n) :- returns the square root of n

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

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

Parts of user defined function.

(i)Function Declaration or Function prototype

(ii)Function call or calling Function

(iii)Function Definition or defining a function

Function Declaration or Function prototype :- It will inform the compiler about


the return type, function name and number of arguments along with the data types.

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:-

int large (int x, int y); → Declaration

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:

function_name(argumement_list); → Calling Function


Information Science and Engineering, JIT
Principles of Programming Using C BPOPS203

Where,

function_name :- descriptive name given to the function

argumement_list :- consist of constant(s) , variable(s), or Expression(s).

Example:-

large (m,n);

The function can be invoked in various ways

• large(m,n); //m and n are variables.


• large(5,8); //5 and 8 are constants
• large(5+2,6); // The first argument is an expression which is evaluated to 7
• large(2*3,5+3); //is an expression which is equivalent to large(6,8);

Function definition or Defining a function :- The declared function must define


the same to perform the specific task.

Syntax

return_type function_name(argument _list)

local_variable_declaration;

Body of the function;

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”

function_name:- is the name of the function.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203
argument _list :- these are also called as parameters. the argument_list refers to the type
order and number of parameters of the function.

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.

Example for Program written using Functions

/* C program to find area of circle using functions */

#include<stdio.h> f

float area(float r);

void main()
{

float r,x;
printf("Enter the radius\n");

scanf("%f",&r);
x=area(r);

printf("Area ofcircle= %f\n",x);

float area(float r)

float x; x=3.142*r*r;

return x;

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Parameter passing mechanism :- There are two methods by which parameters or arguments
can be passed to the function

(i) Call by value or Argument passing by value


(ii) Call by reference or Argument passing by reference

Call by value or Argument passing by value :-When an variable or value is passed to


an function during its invocation such function invocation is called as call by value.

/*C program to demonstrate call by value or Argument passing by value */

#include<stdio.h>

int sum(int n);

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;

Call by reference or Argument passing by reference :- when the address of the


variable is passed to the function during its invocation such a function is called as call by
reference

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.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203
/*C program to demonstrate call by reference or Argument passing by reference */

#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);

printf("After Swapping\n a=%d\t b=%d\n",a,b);

void swap(int *a, int *b)

int temp; temp=*a; *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.

Local variables : - local variables are also called internal variables


Functions including main( ) function declare the variables to store temporary values. These variables are called
local variables.

The scope of the variable is only within the function it is declared with.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203
2) Function Scope: Function scope indicates that a variable is active and visible
from the beginning to the end of a function. In C only goto label has function
scope. In other words function scope is applicable only with goto label names.
This means that the programmer cannot have the same label names inside a
function.

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.

It is the default storage class for variables declared inside a block.


For example,
auto int x;
then x is an integer that has automatic storage. It is deleted when the block in which x is
declared is exited.

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:

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

register int x;

Register are used when quick access tot he variable is needed.

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 int x=10;

Static local variables when defined within a function are initialized at the runtime.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

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

n!= (n) *(n-1)*(n-2)*... .................*1

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.

/* C program to find factorial of the number using recursion */

#include<stdio.h>

int factorial(int n);

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203
void main()
{

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);

Generation of Fibonacci series :- In Mathematics Fibonacci series or Fibonacci numbers are


thenumbers that are displayed in the following sequence:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, .............

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.

/* C program to generate fibonacci series upto N numbers using recursion */

#include<stdio.h>

int fibonacci(int n);

void main()
{

int num,i;
printf("Enter the number up to which you want\n");

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203
scanf("%d",&num);
printf("\nFibonacci Series\n");
for(i=0;i<num;i++)
{

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));

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

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:

#include<stdio.h> void main()


{

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

• List of temperatures recorded every hour in a day, or a month, or a year


• List of employees in an organization
• List of products and their cost sold by a store
• Test scores of a class of students

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.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Any element can be accessed by using

→ name of the array


→ position of element in the array (index)

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

Syntax of Declaring Single Dimensional Arrays

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..

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Memory occupied by 1D array

Total memory=array size * size of datatype For example :int a[5];


Total memory =5*sizeof (int)

= 5*2 =10 bytes.

Storing Values in Arrays – Initialaization of values to array:

The values can be stored in array using following methods:

• 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.

The general syntax of initialization of array is

data_type array_name[array_size]= {List of values};

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.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

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];

b[0]= 10; b[2]=14;

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};

Here the remaining locations in the array will be initialized to zero.

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

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

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.

Example: /* C program to demonstrate run time initialization*/

#include<stdio.h>

void main()
{

int b[5],i;
printf(“Enter 5 elements\n”);

for(i=0;i<5;i++)
{

scanf(“%d”,&b[i]);

Accessing array elements:


Eg: int b[5]={12,14,16,18,20};

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]);

Programming examples on one dimensional array: 1. Write a C program to read and


print n integer elements in an array.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

#include<stdio.h>

void main()
{

int a[20 ],n,i;


printf(“Enter the array size”);

scanf(“%d”,&n);
Printf(“Enter the array elements\n”);

for(i=0;i<n;i++)
{

scanf(“%d”,&a[i]);

printf(“The elements entered in the array are\n”);

for(i=0;i<n;i++)

{
printf(“%d\t”,a[i]);

Example: /* C program to demonstrate run time initialization*/

#include<stdio.h>

void main()
{

2. Write a c program to display first n natural numbers in an array.

#include<stdio.h>

void main()
{
Information Science and Engineering, JIT
Principles of Programming Using C BPOPS203

int a[20 ],n,i;


printf(“Enter the number of elements\n”);

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]);

3. Write a c program to add two one dimensional array

include<stdio.h>

void main()
{

int a[20 ],b[20],c[20],n, i;


printf(“Enter the number of elements\n”);

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”);

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

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.

Example : C program to read and print n integer elements in an array.

• Inserting an element in an array: Inserting an element in an array means adding a new


data element to an already existing array.

Example : C program to insert a number at given location

• Deleting an element from an array : Deleting an element from an array means


removing a exsisting data element from an already existing array.

Example : C program to delete a number at given location

• Merging two array : Combining two arrays in to a single array. Joining oft wo different
array in to one array.

Example: Program to merge two unsorted array.

• Searching an element in an array: Searching means to find whether a particular value


is present in the array or not. If the value is present in the aray then search is said to be
successful and the search process gives the location of that vaule in the array.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

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:

• Less efficient if the array is large


• If the elements are already sorted, linear search is not efficient.

Example : C program to search an element in an array using linear search

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

1. Divides the array into three sections:


o – middle element
o – elements on one side of the middle element
o – elements on the other side of the middle element
2. If the middle element is the correct value, done. Otherwise, go to step 1. using only the

half of the array that may contain the correct value.

3. Continue steps 1. and 2. until either the value is found or there are no more elements to
examine

Advantages:

• Very efficicent searching technique. Disadvantages:

• Array element should be sorted.

Example : C program to search an element in an array using Binary search

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

• Sorting an array in ascending or descending order :

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.

Example : C program to sort n numbers using Bubble sort

Selection sort: This is an in-place comparison based algorithm It is comparison based


algorithm in which list is divided into 2 parts. The sorted part at left and unsorted part at right
end. Initially sorted part is empty and unsorted part is entire list.The smallest element is taken
from the unsorted array and swapped with the leftmost element and the element becomes the
part of sorted array.

Passing an array to functions:

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Passing Individual Elements:

The individual elements of an array can be passed to a function by passing either


their data vaules or their addresses.

Passing Data Values :


The individual elements can be passed in the same manner as we pass variables of any other
data type.

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 (&).

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Passing Entire Array:

When an entire array is to be sent tot he called function, the calling function just needs to pass
the name of array.

Two dimensional array


The simplest form of multidimensional array is two dimensional array. Arrays with two or more
dimensions are called multi-dimensional arrays. (in terms of rows and columns) of same data
type or An array which has two subscripts are known as two dimensional arrays. The first
subscript represents rows and the second subscript represent column.

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.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Example :

int a[2][3];
Represents a is a two dimensional integer array that holds two rows and three columns.

Initialization of two dimensional array :

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}} ;

this initialization can also be written as int a[2][3] ={5,3,4,6,1,2}

Accessing two dimensional array elements:- An element in a two dimensional array is


accessed by using the subscripts i.e. row index and column index of the array.

The feasible way of accessing elements in a two dimensional array is by using nested loops.

Reading and printing 2 dimensional array:-


Reading 2D array

where m-rowsize, n-columnsize, i-row index and j-column index


Information Science and Engineering, JIT
Principles of Programming Using C BPOPS203

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:

An array having 3 or more subscript or dimensions is known as multidimensional array. It is


also known as arrays of arrays or matrix.
The general form of multidimensional array is

data_type array_name[s1][s2][s3]....[sn]; Where s1 is the size of ith dimension.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Representation of Multidimensional Array

Note: Refer text book for programming examples.

Information Science and Engineering, JIT

You might also like