Module-3 Even
Module-3 Even
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.
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.
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.
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;
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.
0th column 1st column 2nd column 3rd column 4th column
0th Row
1st Row
2nd Row
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.
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.
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.
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.
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));
}
/*Function definition*/
int fact(int k) {
if(k==1)
return k;
else
return (k*fact(k-1));
}
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.
{
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( );
}
printf("\nNot eligible");
}
void print_square(int x)
{
int sqr;
sqr=x*x;
printf("\nSquare = %d",sqr);
}
int print_square(int x)
{
int sqr;
sqr=x*x;
return (sqr);
}
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();
}
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
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
void sample()
{
extern int m,n;
printf("\nValue of m=%d and n=%d",m,n);
m=m+10;
n=n+10;
}
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?