0% found this document useful (0 votes)
4 views

Module-3 Even

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Module-3 Even

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

Module 3 Arrays and Functions in C

CAMBRIDGE INSTITUTE OF TECHNOLOGY-NORTH CAMPUS


Off International Airport Road, Kundana, Bengaluru – 562110
STUDY MATERIAL
Module-3 Arrays and Functions in C
Course Title: Principles of Programming using C Course Code: BPOPS203 Credit: 03
Faculty Name: SUNIL KUMAR B
Department: COMPUTER SCIENCE AND ENGINEERING

Name:________________USN:____________Section/Branch:___________

Why ARRAYS?
Variables are used to store values in a program. However, many times we need to
work with a set of values of the same type. For example, we may need to store the marks
obtained by 100 students in an examination. In this case, it is very difficult to define 100
variables to store the marks of each student. In such a situation, it is better to have a single
variable that can store all the values rather than storing each value in a separate variable. The
simplest way to store a set of values is to use an array.
What is an ARRAY?
 An array is a collection of same type of values stored in consecutive memory
locations. It can be used to store the values of different data types, such as int, float,
double, char, and string.
 Each value in an array is reference by a single name, which is the name of the array,
and a subscript or index, which indicates the position of the value in the array.
 The subscript is a positive integer number, which is enclosed in a pair of square
brackets.
 As subscripts are used in arrays, they are also referred as subscripted variables.
The individual values in an array are called the elements of the array. The structure of an
array, myArray, containing n elements is shown in Fig.1.
myArray[0] myArray[1] myArray[2] ………….. myArray[n-1]
Fig.1. Structure of an Array
In the above fig., myArray[0] represents the first element of the array, myArray[1]
represents the second element of the array, myArray[2] represents the third element of the
array, and myArray[n-1] represents the nth element of the array.

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 1


Module 3 Arrays and Functions in C

For example,
Values in a mathematical set are written as shown below.
x={3.1, 4.5, 4.7, 5.5, 7.7}
These values are referred in mathematics as fallows.
x0, x1, x2 and so on…
In C language they are represented as fallows.
x[0] x[1] x[2] and so on.

It can be imagined that these values are stored in RAM as follows.


Subscript  0 1 2 3 4
Array name x 3.1 4.5 4.7 5.5 7.7

Following are some rules that need to be kept in mind while using arrays:
 The array should be declared with some data type.
 The size of the array should be specified at the time of its declaration.
 In an array, elements are stored sequentially, that is, in contiguous memory locations.
 Only one element can be added or removed from the array at a time.

Types of Arrays
Arrays can be broadly classified into two types: one-dimensional arrays and multi-
dimensional arrays. A one-dimensional array has only one subscript and a multi-dimensional
array has n subscripts, where n represents the dimension of the arrays.
The dimensionality of an array is determined by the number of pairs of square
brackets placed after the array name.
For example, array1[ ] represents one-dimensional array, array2[ ][ ] represents two-
dimensional array, and array3[ ] [ ] [ ] represents a three dimensional array. Each pair of
square brackets contains the number of elements corresponding to a specific dimension.
One –Dimensional Arrays
A one-dimensional array or a single dimensional array is used to store a linear list of
values of the same type. The elements in a one-dimensional array are stored with the index
values starting from zero to one less that the size of the array. Each element in a one-
dimensional array is similar to a row matrix or a column matrix.

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 2


Module 3 Arrays and Functions in C

Declaring a One-Dimensional Array


Similar to an ordinary variable, you need to declare an array before using it. A one-
dimensional array can be declared using the following syntax:
data_type array_name[size];
In the preceding syntax, data_type represents the data type of the array to be
declared, array_name represents the name of the array, and size represents the number of
values of the data_type that can be stored in the array_name array.
The following code snippet declares an integer array, numbers, of size 10:
int numbers[10];
In the preceding example, the numbers array can contain 10 elements, which are indexed 0
to 9.
Note:- If the data type and the number of elements in a one-dimensional array are known,
then total amount of memory that can be allocated to the array can be calculated using the
following formula:
Total amount of memory = size * [sizeof(data_type)]
Using this formula, the total amount of memory required for a one-dimensional array of size
10 is 20 bytes if the array is of type int.

Initializing a One-Dimensional Array


Once after declaring a one-dimensional array, we can initialize the individual
elements of the array one by one in the same way as we declare ordinary variables. We can
also initialize all the elements of an array at the time of declaring the array. An array element
can take only a constant value. We cannot initialize an array element with a variable or a
function call.
The syntax for initializing an individual element of a one-dimensional array is as
follows:
array_name[index] = value;
In the preceding syntax, array_name represents the name of the array, index
represents the position of the array element in the array, and value represents the value being
assigned to the array element.
The following programming example shows how to initialize array elements dynamically or
at run-time one by one:
#include<stdio.h>
#include<conio.h>

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 3


Module 3 Arrays and Functions in C

void main( )
{
int arr[25] , i, n;
clrscr( );
printf(“Enter the size of the array:\n”);
scanf(“%d”,&n);
printf(“Enter the elements of the array:\n”);
for (i=0; i<n; i++)
printf(“Elements of the array are:\n”);
for (i=0; i<n; i++)
printf(“%d”, arr[i]);
getch( );
}

Output:
Enter the size of the array:
5
Enter the elements of the array:
10 20 30 40 50
Elements of the array are:
10 20 30 40 50

The syntax to initialize all the elements of a one-dimensional array at the same time is as
follows:
Data_type array_name[size] = {value1, value2, value3 ……value n};
In the preceding syntax, data_type represents the data type of the array, array_name
represents the name of the array, size represents the number of elements that can be stored in
the array, and value1, value2, value3,….value n are values assigned to the first, second,
third….nth element of the array, respectively.
The elements values in the right hand side of the preceding syntax must be enclosed in curly
braces and must be separated by comma. These values are assigned to the array elements in
the same order as the order of these values.
For example, value1 is assigned to the first array element, value2 is assigned to the second
array element, and value3 is assigned to the third array element.
The following code snippet declares and initializes an integer array, numbers, of size 5:
int numbers[5] = {10, 20, 30, 40, 50};
Initialization of the array elements in the preceding code snippet is equivalent to initializing
each array element separately, as shown in following code snippet:
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 4


Module 3 Arrays and Functions in C

numbers[3] = 40;
numbers[4] = 50;
The following programming example shows how to initialize array elements at the time of
array declaration:
#include<stdio.h>
#include<conio.h>
void main( )
{
int arr[5] = {10, 20, 30, 40, 50}; //array declaration and initialization
int i;
clrscr( );
printf(“Elements of the array are:\n”);
for(i=0; i<5; i++)
printf(“%d”, arr[i]);
getch( );
}
Output:
Elements of the array are:
10 20 30 40 50

Note:- If an array is initialized at the time of declaration, it is not necessary to specify its size.
The number of elements assigned to the array automatically becomes the size of the array.
For example,
int numbers[ ] = ( 5, 7, 11, 17};
Note:-For more programming examples, refer text and class notes.

Two-Dimensional Arrays
In one-dimensional arrays the data are organized linearly in only one direction. A
two-dimensional array is used to store a table of values of the same type. It is similar to a
matrix containing rows and columns. We can perform a number of operations on matrices
using two-dimensional arrays. Some of these operations are as follows:
 Reading and displaying elements of matrix
 Adding and subtracting the corresponding elements of two matrices
 Multiplying two matrices
 Searching and sorting elements in a matrix

Therefore, a two-dimensional array is used to store a table of values of the same data
type. It is similar to a matrix containing rows and columns. A two-dimensional array is as
shown in the fig.2.

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 5


Module 3 Arrays and Functions in C

0th column 1st column 2nd column 3rd column 4th column
0th Row
1st Row
2nd Row

Fig.2. Table containing rows and columns


Two dimensional arrays are identified by their names and the number of rows and
columns in them. For example, x[3][5] is a valid two dimensional array, where the first
number within the bracket denotes number of rows in the array while the second number
denotes number of columns in the array. Thus, x[3][5] denotes an array, x which comprises of
3 rows and 5 columns.

Declaring Two Dimensional Arrays


A two-dimensional array is declared using the following syntax:
data_type array_name[size1][size2];
data_type represents the data type of the array to be declared,
array_name represents the name of the array, size1 represents the number or rows, and size2
represents the number of columns.
The following line of code declares a two-dimensional integer array, number:
int number[5][7];

Initializing a two dimensional array


Similar to one-dimensional array, the elements of a two-dimensional array can be initialized
either one at a time or all at once. The syntax is:
data_type array_name[size1][size2] = {value1, value2, …….., value n}
The following line of code declares and initialize a two-dimensional integer array, number:
int number[2][3] = {10, 20, 30, 40, 50, 60};
Initialization of the array elements in the preceding line of code is equivalent to initializing
each array element separately as follows:
number[0][0] = 10;
number[0][1] = 20;
number[0][2] = 30;
number[1][0] = 40;
number[1][1] = 50;
number[1][2] = 60;

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 6


Module 3 Arrays and Functions in C

Limitations of Arrays
Although arrays provide an easy way to store multiple values of the same type together, they
have certain limitations.
1. The size of an array that you specify at the time of creation cannot be altered later. In
other words, you cannot add more elements to an array than specified in its size.
2. It is very difficult to insert an element between two existing elements. If you want to
insert a new element between two existing elements, you first need to make space for
the new element by moving all the existing elements up by one index.
3. The amount of memory taken by an array depends on the size specified for the array
and not on the number of elements stored in the array.
Note:-For more programming examples, refer text and class notes.

Using Arrays with Functions / Passing Arrays to functions as Arguments


As we pass variables to the function, whole array can also be passed to the function
but in a slightly different way. Making use of the functions involves following:
1. Function definition.
2. Calling the function.
3. Sometimes function prototype.
Function Definition
If array is being passed as argument then function definition is written in the following
format:
data_type function_name (data_type array_name[ ])
The array_name could be any name (same or different than that being passed by the
calling function). Note that, array name is to be followed by [ ] but with nothing written in it.
For example.
void select_color (char color[ ])
{
Statements;
}

Calling the Function


To call a function, which accepts array as arguments, following format is used:
function_name(array_name);

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 7


Module 3 Arrays and Functions in C

Here function name is the name of that function, which is to be called and array_name is the
name of that array, which is to be passed as argument to the function. Note that no bracket or
number is written along with the array name.
Following are the two statements, which would be used for calling the functions mentioned in
definition section:
select_color(array);
Prototype Function
If the function definition appears, after the calling function then we would required to make
use of function prototypes. Function prototypes are used in the following format:
data_type function_name(data_type array_name[ ]);
For example,
void select_color(char c[ ]);

*Note:- For more programming examples, refer text books and class notes.

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 8


Module 3 Arrays and Functions in C

FUNCTIONS
Function
Definition: A function in C (including main) is an independent module that will be
called to do a specific task.
A called function receives control from a calling function. When the called function
completes its task, it returns to the calling function. It may or may not return a value to the
caller. The function main is called by the operating system; main in turn calls other functions.
When main is complete, control returns to the OS.

Functions and program structure.


Function Definition.
The function definition of a function contains the actual code that performs the intended task.
Therefore, we must provide the function definition, before it is invoked or called in a
program.
Syntax:-
return_type function_name (formal_argument_list)
{
local variable declarations;
executable statement 1;
executable statement 2;
----------------------
executable statement n;
return (expression);
}
In the preceding code snippet, return_type is the data type that the function returns.
Function_name refers to the name of the function. The formal_ argument_list is a comma
separated list of variables that receive the values from the main program when a function is
called. The return statement returns the result of the function.
Function Invocation
Invoking or calling a function means executing the code of a function from a program. A
function can be called by specifying its name followed by a list of arguments enclosed in the
parentheses and separated by commas.
The arguments appearing in the function call are referred to as actual arguments.

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 9


Module 3 Arrays and Functions in C

Syntax:-
Variable = function_name (actual_argument_list); /*Function call*/
Let us consider the example to call a function.
i) ncr = fact(n)/(fact(n-r) * fact(r));
ii) printf(“%d” factorial is %d”, m, fact(m));
Note function fact() is called thrice to find the value of ncr.

Function Prototype/ Function Declaration


When a C program is complied, the compiler does not check for the data type
mismatch of actual arguments in the function call and the formal arguments in the function
declaration. To enable the compiler to check the same, a function prototype declaration is
used in the main program.
A function prototype declaration is similar to the first line of a function declaration and has
the following form.
data_type fun_name(type d1, type d2, …..type dn);
int fact(int k); /*Function Prototype*/

Actual and Formal Arguments


Passing of values between the main program and the function takes place through
arguments. The argument listed in the function calling statement is referred to as actual
arguments. They are the actual values passed to a function to compute a value or to perform a
task.
For ex.:-
ncr = fact(n)/(fact(n-r) * fact(r));

Actual arguments
The arguments used in the function declaration are referred as formal arguments. They are
simply formal variables that accept or receive the values supplied by the calling program. For
ex.:-
int fact(int k)
{ Formal argument
if(k==1)
return k;
Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 10
Module 3 Arrays and Functions in C

else
return (k*fact(k-1));
}

Example program to demonstrate the use of Function in program.


#include<stdio.h>
#include<conio.h>
int fact(int k); /*Function Prototype*/
int main()
{
long n,factorial;
clrscr();
printf("Enter the number:");
scanf("%d",&n);
factorial=fact(n); /*Function call*/
printf("The Factorial of the given number is:%d", factorial);
getch();
return 0;
}

/*Function definition*/
int fact(int k) {
if(k==1)
return k;
else
return (k*fact(k-1));
}

Arguments/Parameter passing mechanism


Passing parameters to functions
A pointer can be used as an argument in function declaration. When a function with a
pointer argument is called, the calling program will pass the address (not the value) of a
variable to the argument.
In C, a function can be called by the calling program in 2 ways:
1. Call by Value
2. Call by Reference
Call by Value

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 11


Module 3 Arrays and Functions in C

When a function is called by the calling program, the values to the arguments in the
function are supplied by the calling program. The values supplied can be used inside the
function.
Any alterations to the value inside the function are not accepted in the calling program but the
change is locally available in the function. This method is referred as calling a function by
value.
Example:
#include<stdio.h>
#include<conio.h>
void add10(int x, int y);
void main()
{
int a=25, b=10;
clrscr();
printf("Before function call a=%d b=%d",a,b);
add10(a,b);
printf("\nAfter function call a=%d b=%d",a,b);
getch();
}
void add10(int x, int y)
{
x=x+10;
y=y+10;
printf("\nInside the function a=%d b=%d",x,y);
}

OUTPUT:-
Before function call a=25 b=10
Inside function call a=35 b=20
After function call a=25 b=10

*Note:- For programming examples, refer text books and class notes.

Scope of variables /Void and Parameter less functions


A function which does not return a value directly to the calling program is referred as a void
function.
The void functions are commonly used to perform a task and they can return many values
through the global variable declaration.
It is declared with the keyword void.
Example program:-
#inlcude<stdio.h>
int m,n;
main( )

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 12


Module 3 Arrays and Functions in C

{
void add(void); /*Function prototype*/
m = 10, n = 20;
printf(“Values before function call”);
printf(“m = %d and n = %d”, m ,n);
add( ); /*Function call*/
printf(Values after function call”);
printf(“m = %d and n = %d”);
getch( );
}

/* Void function or Parameter less function*/


void add( void)
{
m = m +10;
n = n+10;
}

Output:- Values before function call m = 10 and n =20


Values after function call m= 20 and n=30

Classification of Functions based on arguments and return values.


It is not mandatory on function‟s part to always receive and return values from or to calling
program.
1. Function with No arguments and No return values.
These functions neither take any input from the main( ), nor they return any values to it.
Ex:-
#include<stdio.h>
#include<conio.h>
void remarks();
void main()
{
int i,roll,age;
char name[20];
clrscr();
printf("Enter name");
scanf("%s",name);
printf("Enter age");
scanf("%d",&age);
if(age < 21)
remarks(); /* call with no arguments*/
getch();
}
void remarks()
{

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 13


Module 3 Arrays and Functions in C

printf("\nNot eligible");
}

2. Function with Argument and No return values.


These functions receive values from the calling function and do not send back any
value to the calling program. They work upon the received-values within their body and
generate some results.
Example:
#include<stdio.h>
#include<conio.h>
void print_square(int x);
void main()
{
int i, number;
clrscr();
printf("Give a number");
scanf("%d",&number);
print_square(number);
getch();
}

void print_square(int x)
{
int sqr;
sqr=x*x;
printf("\nSquare = %d",sqr);
}

3. Function with Argument and Return value


Such function receives values from the calling program through arguments and return results
to the calling program.
Example:-
#include<stdio.h>
#include<conio.h>
int print_square(int x);
void main()
{
int i, number,result;
clrscr();
printf("Give a number");
scanf("%d",&number);
result=print_square(number);
printf("\n The square is %d",result);
getch();
}

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 14


Module 3 Arrays and Functions in C

int print_square(int x)
{
int sqr;
sqr=x*x;
return (sqr);
}

4. Function with NO arguments and Return values


Such function do not get any input from the calling program but still provide some output to
it.
Example:-
#include<stdio.h>
#include<conio.h>
int print_square();
void main()
{
int i,result;
clrscr();
result=print_square();
printf("\n The square is %d",result);

getch();
}

int print_square()
{
int sqr,x;
printf("Give a number");
scanf("%d",&x);
sqr=x*x;
return (sqr);
}

*Note:- For programming examples, refer text books and class notes.

Recursion
A function calling itself again and again to compute a value is referred to recursive function
or recursion. Normally, a function is called by main program or by some other function, but
in recursion the same function is called by itself repeatedly. For ex:-
/*Recursive Function to find the factorial of a number*/
int fact(int k)
{
if(k = = 1)
return k;
Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 15
Module 3 Arrays and Functions in C

else
return (k*fact(k-1)); /*Recursive Function call*/
}

/*Example program */
#include<stdio.h>
void main()
{
int n,r,res,ncr;
clrscr();
printf("Enter any number:\n");
scanf("%d",&n);
res=fact(n); /*Function call */
printf("%d!=%d",n,res);
printf("Enter a value for N and R\n");
scanf("%d%d",&n,&r);
ncr=fact(n)/(fact(r)*fact(n-r)); /*Function call */
printf("The Binomial co-efficient of NCR=%d",ncr);
getch();
}

int fact(int n) /*Function definition*/


{
if (n==0) /*Base condition*/
return 1;
else
return (n*fact(n-1)); /* Recursive Function call */
}
Return Statements
The return statement terminates the execution of the called function and returns control to the
calling function.
The syntax is: return <expression>;
It is used to return the control to the calling function with/without a value. For example, if a
function is not returning any value, use the return keyword
return;
If a function is returning a value, then return value;
Storage classes in C
Variables used in C program are stored in RAM or CPU memory register. There are 4 storage
classes.
1. auto or Automatic storage class

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 16


Module 3 Arrays and Functions in C

 Variables declared in this class are stored in RAM. This is the default storage class
and the keyword auto is used to declare the variable.
 Auto variables are active in a block in which they are declared.
 When a block in C program is executed, the variables inside the block are created
automatically and destroyed automatically when the execution is transferred to
another block or function in the same program.
 For example. Consider the following program.
/*Program to demonstrate auto storage classes*/
#include<stdio.h>
#include<conio.h>
void main()
{
void sample(void);
auto int m=40;
/*consider an inner block*/
{
auto int m=50;
clrscr();
printf("\nValue of m inside inner block is %d\n",m);
}
/*calling the function*/
sample();
printf("\nValue of m in outer block is %d\n",m);
getch();
}

void sample(void)
{
auto int m=65;
printf("\nValue of m in function block is %d",m);
}
Output: Value of m in inner block is 50
Value of m in function block is 65
Value of m in outer block is 40

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 17


Module 3 Arrays and Functions in C

2. static storage Class


 Variables declared in this class are stored in RAM. Keyword static is used to
declare these variables.
 Static variables are active in the block they are declared and they retain the latest
values.
 Consider the following example.
/*Program to demonstrate STATIC storage class*/
#include<stdio.h>
#include<conio.h>
void main()
{
void sample(void);
clrscr();
printf("First function call\n");
sample();
printf("\nSecond function call\n");
sample();
getch();
}

void sample()
{
static int m=5, n=10;
printf("Initial value = %d, %d",m,n);
m = m+10;
n = n+10;
printf("\nValue of m = %d and n = %d", m, n);
}
OUTPUT:-First function call
Value of m=15 and n=20
Second function call
Value of m=25 and n=30

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 18


Module 3 Arrays and Functions in C

3. extern storage class:


 Global variables are declared using this class and they are stored in RAM. The
keyword extern is used to declare these variables.
 Extern storage class can be used to consider a local variable in a block as a
global variable.
 Consider the following example.
/*Program to demonstrate EXTERN Storage Class*/
#include<stdio.h>
#include<conio.h>
void main()
{
extern int m,n;
void sample();
m=5;
n=10;
clrscr();
sample();
printf("\nValue of m = %d and n = %d",m,n);
getch();
}

void sample()
{
extern int m,n;
printf("\nValue of m=%d and n=%d",m,n);
m=m+10;
n=n+10;
}

4. register storage class:


 Variables declared using this class are stored in the CPU memory register. The
keyword register is used to declare these variables.

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 19


Module 3 Arrays and Functions in C

 These variables behave the same as auto variables, except that their storage
locations are different.
 Consider the following example.
main( )
{
register int n =5;
register char ch = „Y‟;
printf(“Value of n = %d:,n);
printf(“Value of choice ch=%c”, ch);
}
OUTPUT: Value of n =5
Value of choice ch = Y

Question Bank
Arrays
1. What is an Array? Example it with suitable syntax and example program?
2. What is an Array? Briefly explain the different types of Arrays with ex.
3. What is one dimension array? Explain how it is declared and initialized with suitable
examples.
4. What is two dimensional array? Explain how it is declared and initialized with
suitable examples.
5. How arrays can be used in Functions? Demonstrate with a suitable example program.
6. What are multi-dimensional arrays? Explain with an example.

Strings
1. What are Strings? Explain how strings are declared and initialized?
2. Explain how strings are read and displayed?
3. Explain the function which helps in reading any string and displaying any string.
4. Explain the various functions available in C to manipulate the strings with suitable
examples.
5. What are string handling or string manipulation functions in C?
6. What are sting input and output functions?
7. What are arrays of strings? Demonstrate with an example program?

Functions
1. What is a Function? Explain how functions are used in a C program?
2. What are functions in C? Why they are used and what is the advantage in using them?
3. What is a Function? How they are declared and initialized?
4. What is argument passing or parameter passing in C? How many types of passing are
there and explain anyone.
5. What is argument passing or parameter passing in C? Explain call by value with a
suitable example program?
6. Define function definition, prototype and function call in C?

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 20


Module 3 Arrays and Functions in C

7. What is void function or parameter less functions in C?


8. What is Recursion? Explain with a suitable example program?

Sunil Kumar B, Dept. of CSE, CITNC, Bengaluru. 21

You might also like