Unit3 Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

UNIT – 3: ARRAYS AND FUNCTIONS

ARRAYS
C supports a derived data type known as array that can be used to
handle large amounts of data(multiple values) at a time.

Definition

An array is a group (or collection) of related data items that


share a common name and data type.
Or

An array is a collection of data that holds fixed number of values


of same type.
Or

Array is a collection or group of elements (data). All the elements


of array are homogeneous (similar). It has contiguous memory
location.

Or

An array is a data structured that can store a fixed size sequential


collection of elements of samedata type.

Advantages of arrays
1. It is capable of storing many elements at a time.
2. It allows random access of elements.
Disadvantages of arrays
1. Predetermining the size of array is must
2. Memory wastage will be there.

Types of arrays
Arrays can be mainly three types one dimensional, two dimensional and multi
dimensional arrays.
One‐Dimensional Arrays
Declaration of an Array
data-type variable-name[size/length of array];
For example:
int arr[10];

After an array is declared it must be initialized. Otherwise, it will contain


garbage value(anyrandom value). An array can be initialized at either compile
time or at runtime.
Compile time Array initialization

Compile time initializtion of array elements is same as ordinary variable


initialization.

Syntax : data_type array_name[size]={v1,v2,…vn/list of values} ;


Example
int age[5]={22,25,30,32,35};

int marks[4]={ 67, 87, 56, 77 }; //integer array initialization

float area[5]={ 23.4, 6.8, 5.5 }; //float array initialization

int str[9]={ ‘C’,’O’,’M’,’P’,’U’,’T’,’E’,’R’,’\0’ };//char array initialization

Different ways of initializing arrays :

1 : Initializing all specified memory

locations2 : Partial array initialization.

3 : Initialization without size.

1 : Initializing all specified memory locations : If the number of values to b e


initialized is equal to size of array. Arrays can be initialized at the time of
declaration. Array elements can be initialized with data items of type int, float,
char, etc.
Ex:
int a[5]={10,20,30,40,50};

2 : Partial Array Initialization : partial array initialization is possible in C


language. If the number of values to be initialized is less than the size of the
array, then the elements are initialized in the order from 0th location. The
remaining locations will be initialized to zero automatically
Ex: int a[5]={10,15};

3 : Initialization without Size: The array size may be omitted. In such cases, the
compiler allocates enough space for all initialized elements.
Ex: int counter[ ]={1,1,1,1,1};

will declare the counter array to contain five elements with initial values 1.

Accessing Array Elements

You can access elements of an array by indices/index. You can use array
subscript (or index) to access any element stored in array. Subscript starts with 0,
which means array_name[0] would beused to access first element in an array.
In general array_name[n-1] can be used to access nth element of an array. where
n is any integer number.
Ex:
int a[ ]={10,20,30,40 }; → here array size is 4.
To read one dimensional array:
for(i=0;i< size;i++)
scanf(“ % d”, &a[i]);
To print one dimensional array
for(i=0;i< size;i++)
printf(“ % d”, a[i]);

Two‐Dimensional Arrays

The two dimensional array in C language is represented in the form


of rows and columns, also known as matrix. It is also known as array
of arrays or list of arrays.

Declaration of two dimensional Array

data_type array_name[row_size][col_size];

Example

int a[3][4];

Initialization of 2D Array

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Accessing Two-Dimensional Array Elements

An element in a two-dimensional array is accessed by using the


subscripts, i.e., row indexand column index of the array.

To read two dimensional arrays:


for(i=0;i<row;i++)
for(j=0;j<col;j++)
Scanf(“% d”, &a[i][j]);
Multidimensional Arrays
You can initialize a three dimensional array in a similar way like a
two dimensional array. Three dimensional arrays uses three indexes.Here's
an example

int test[2][3][4] = {

{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },

{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }

};

DYNAMIC ARRAYS
An array created at compile time by specifying size in the source code has
a fixed size and cannot be modified at run time. The process of allocating memory
at compile time is known as static memory allocation and the array created at
compile time are called static arrays.
In C it is possible to allocate memory to arrays at run time. This feature is
known as dynamic memory allocation and the array created at run time are called
as dynamic arrays. The dynamic arrays are created using pointer variables and
memory management allocation functions malloc(), calloc() and realloc().

FUNCTIONS

Function: A function is a reusable block of statements that gets executed on calling.


It can be treated as subprogram.
Advantages:
1. It allows reusability (a function can be called any no. of times).
2. It reduces the program code.
3. Functions allows calls of other functions within.

Types of Functions
1). System defined functions: These are also called as built in or
library functions. They are defined by C compiler and included in header
files.
Ex: pow() //power function
sqrt() //square root function.
printf(), scanf() and string functions etc.

2). User defined functions: these are defined by the user. User can include
any number of functions in the program, for which declaration and definition must
be provided.
Structure of a function
Return-type function-name(arguments list….)
{
local declarations
……..
…..code…
……..
}
example:
void sum (int,int); /*function declaration (prototype)*/
main()
{
sum(10,20); /*calling function*/
}
void sum(int x,int y) /*function definition*/ /* Called function */
{
printf(“sum=%d”,x+y);
}
Function prototype: Declaration of a function can be called as function prototype.
This gives the clear picture of the function i.e which type of arguments it
takes and how many arguments and what will be return value with the function
name.
Syntax: Return-type function-name(arguments list….);

Function definition: It defines the behavior of function in terms of instructions.


It may include list of the arguments, return variable and local declarations.

Argument : (parameter) : Argument is a value that is sent from calling function to


a called function(definition). It is possible to send any no. of arguments to a
function.
In C user defined functions can be written in four different ways.
1. No Argument, No Return Value
2. Argument, No Return Value
3. No Argument, Return Value
4. Argument, Return Value

1. No Argument, No Return Value: A function which does not take any


arguments and does not return any value that function can be said as No Argument,
No Return type function.
Example:
void show();
main()
{
show( );
}
void show()
{
printf(“no argument no return”);
}
2. Argument, No Return Value: a function which takes arguments but do not return
any value that function can be said as Argument, No Return type function.
Example:
void sum(int, int);
main()
{
sum(10,20);
}
void sum(int x, int y)
{
printf(“ sum=%d”, x+y);
}
3. No Argument, Return Value: a function which takes arguments but do not return
any value that function can be said as Argument, No Return type function.
Example:
int sum( );
main()
{
int n;
n = sum();
printf(“sum=%d”,n);
}
int sum()
{
int a=10,b=20;
return a+b;
}
4. Argument, Return Value: a function which takes arguments and returns a
value that function can be said as Argument, Return type function.
Example:
int sum(int, int );
main()
{
int n;
n = sum(10,20);
printf(“sum=%d”,n);
}
int sum(int x, int y)
{
return x+y;
}
PASSING PARAMETERS TO FUNCTIONS
There are two ways to pass value or data to function in C language:
1 : Pass by value (OR) Call by value.
2: Pass by reference (OR) Call by Reference.
Original value is not modified in call by value but it is modified in call by
reference.
1 : Pass by value (OR) Call by value :
In call by value, value being passed to the function is locally stored by the function
parameter in stack memory location. If you change the value of function parameter, it
is changed for the current function only. It will not change the value of variable inside
the calling function such as main().
Or
When a function is called with actual parameters, the values of actual parameters
are copied into formal parameters. If the values of the formal parameters are
changed in the function, the values of the actual parameters are not changed. This
way of passing parameters is called pass by value or call by value.
Ex : /* Call by Value */
#include<stdio.h>
#include<conio.h>
void swap(int ,int );
void main()
{
int i,j;
printf("Enter i and j values:");
scanf("%d%d",&i,&j);
printf("Before swapping:%d%d\n",i,j);
swap(i,j);
printf("After swapping:%d%d\n",i,j);
getch();
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
Output
Enter i and j values: 10 20
Before swapping: 10 20
After swapping: 10 20
2 : Pass by reference (OR) Call by Reference : In pass by reference, a function
is called with addresses of actual parameters. In the function header, the formal
parameters receive the addresses of actual parameters. Now the formal parameters
do not contain values, instead they contain addresses. Any variable if it contains
an address, it is called a pointer variable. Using pointer variables, the values of the
actual parameters can be changed. This way of passing parameters is called call
by reference or pass by reference.
Ex : /* Call by Reference */
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main()
{
int i,j;
printf("Enter i and j values:");
scanf("%d%d",&i,&j);
printf("Before swapping:%d%d\n",i,j);
swap(&i ,&j);
printf("After swapping:%d%d\n",i,j);
}
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output
Enter i and j values: 10 20
Before swapping:10 20
After swapping: 20 10
Difference between Call by value and Call by reference
Call by value Call by Reference
1 : When a function is called the values of 1 : When a function is called the address
variables are passed of variables are passed.
2 : Change of formal parameters in the 2 : The actual parameters are changed
function will not affect the actual since the formal parameters indirectly
parameters in the calling function. manipulate the actual parameters.
3 : Execution is slower since all the values 3 : Execution is faster since only address
have to be copied into formal parameters. are copied.

NESTED FUNCTION CALL


C permits nesting of functions freely. Main() function can call function1(), which
calls function2(), which calls function3(),…. And so on.
Example:
#include <stdio.h>
void function_a(); // function declaration
void function_b(); // function declaration
void main()
{
function_a();
printf(“\nIn main() function”);
}
void function_a() // function definition
{
printf(“\nIn function_a()”);
function_b();
}
void function_b() // function definition
{
printf(“\nIn function_b()”);
}
OUTPUT
In function_a()
In function_b()
In main() function
In the example, main() function calls function_a(), which in turn calls another
function_b().
Recursion
A function that calls itself is known as a recursive function. And, this technique is
known as recursion.
Features :
• There should be at least one if statement used to terminate recursion.
• It does not contain any looping statements.

Advantages :
• It is easy to use.
• It represents compact programming structures.

Disadvantages :
• It is slower than that of looping statements because each time function is
called.

Note: while using recursion, programmers need to be careful to define an exit


condition from the function, otherwise it will go into an infinite loop. Recursive
functions are very useful to solve many mathematical problems, such as calculating
the factorial of a number, generating Fibonacci series, etc.
Example of recursion

void recurse()
{
……
recurse();//calling self function
……
}
int main()
{
……
recurse();//calling recursion function
……
}

Example: // print factorial of a number using recursion


#include<stdio.h>
#include<conio.h>
int factorial (int n)
{
int fact;
if (n == 1)
return (1); /*Terminating condition*/
else
fact = (n * factorial (n -1));
return (fact);
}

void main()
{
int fact=0;
clrscr();
fact = factorial(5);
printf("\n factorial of 5 is %d", fact);
getch();
}

OUTPUT
factorial of 5 is 120

fact = 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
=5*4*3*2*1
= 120
STORAGE CLASSES
In C language, each variable has a storage class which is used to define scope and
life time of a variable. Storage classes in C are used to determine the lifetime,
visibility, memory location, and initial value of a variable.
There are four storage classes in C programming

1. auto
2. register
3. static
4. extern

1: Automatic (or auto) Storage class : To define a variable as automatic storage


class, the keyword “auto‟ is used. By defining a variable as automatic storage
class, it is stored in the memory. The default value of the variable will be garbage
value. Scope of the variable is within the block where it is defined and the life of
the variable is until the control remains within the block.
Syntax : auto data_type variable_name;
auto int a,b;
The variables a and b are declared as integer type and auto. The keyword auto is
not mandatory. Because the default storage class in C is auto.
Note: A variable declared inside a function without any storage class specification,
is by default an automatic variable. Automatic variables can also be called
local variables because they are local to a function.
2: Register Storage class : To define a variable as register storage class, the
keyword “register‟ is used. When a variable is declared as register, it is stored
in the CPU registers. The default value of the variable will be garbage value.
Scope of the variable within the block where it is defined and the life of the
variables is until the control remains within the block.
Register variable has faster access than normal variable. Frequently used variables
are kept in register. Only few variables can be placed inside register.
Sytax : register data_type variable_name;
register int i;
3 : Static Storage class : When a variable is declared as static, it is stored in the
memory. The default value of the variable will be zero. Scope of the variable is
within the block where it is defined and static variable hold or retain their value
between the multiple function calls. To define a variable as static storage class,
the keyword “static‟ is used. A static variable can be initialized only once, it
cannot be reinitialized.
Syntax : static data_type variable_name;
Ex: static int i;
void demo();
void main()
{
demo();
demo();
demo();
}
void demo()
{
static int i=20;
printf(“%d \t”,i);
i++;
}
OUTPUT
20 21 22
4 : External Storage class : When a variable is declared as extern, it is stored in
the memory. The default value is initialized to zero. The scope of the variable is
global and the life of the variable is until the program execution comes to an end. To
define a variable as external storage class, the keyword “extern‟ is used. An extern
variable is also called as a global variable. Global variables remain available
throughout the entire program. One important thing to remember about global variable
is that their values can be changed by any function in the program.

Systax : extern data_type variable_name;


extern int i;

Storage Storage Default Scope Lifetime


Classes Place Value

auto RAM Garbage Local Within function


Value

extern RAM Zero Global Till the end of the main


program Maybe
declared anywhere in
the program

static RAM Zero Local Till the end of the main


program, Retains value
between multiple
functions call

register Register Garbage Local Within the function


Value
STRINGS
String Concepts
String is an array of characters that is terminated by \0 (null character). This null
character indicates the end of the string. Strings are always

Or
In “C‟ language the group of characters, digits, and symbols enclosed within
double quotation ( " " ) marks are called as string otherwise a string is an array of
characters and terminated by NULL character which is denoted by the escape
sequence “\0‟.
Declaration of String: C does not support string as a data type. However, it allows
us to represent strings as character arrays. In C, a string variable is any valid C
variable name and it is always declared as an array of characters.
The general form of declaration of a string variable is :
Syntax: char string_name[size];
The size determines the number of characters in the string name.
Note: In declaration of string size must be required to mention otherwise it gives
an error.
Ex: char str[]; // Invalid
char str[0]; // Invalid
char str[-1]; // Invalid
char str[10]; // Valid
char a[9]; //Valid
Using this declaration the compiler allocates 9 memory locations for the variable a
ranging from 0 to 8.

Initializing Array string


Syntax : char string_name[size]={“string” };
Note: In Initialization of the string if the specific number of character is not
initialized it then rest of all character will be initialized with NULL.
char str[5]={'5','+','A'};
str[0]; ---> 5
str[1]; ---> +
str[2]; ---> A
str[3]; ---> NULL
str[4]; ---> NULL
Note: In initialization of the string we can not initialized more than size of string
elements.
Ex:
char str[2]={'5','+','A','B'}; // Invalid

Different ways of initialization can be done in various ways :


1 : Initilizing locations character by character.
Ex:
Char b[9]={‘C’,’O’,’M’,’P’,’U’,’T’,’E’,’R’,’\0’};
The compiler allocates 9 memory locations ranging from 0 to 8 and these locations
are initialized with the characters in the order specified.

C O M P U T E R \0

0 1 2 3 4 5 6 7 8

2 : Partial array initialization.


3 : Intilization without size.
4 : Array initialization with a string .

2 : Partial Array Initilization : If the characters to be initialized is less than the


size of the array, then the characters are stored sequentially from left to right. The
remaining locations will be initialized to NULL characters automatically

Ex : Consider the partial initilization


int a[10]={‘R’,’A’,’M’,’A’ };
The compiler allocates 10 bytes for the variable a ranging from 0 to 9 and initializes
first four locations with the ASCII characters of ‘R’,’A’,’M’,’A’.The remaining
locations are automatically filled with NULL characters (i.e,\0).

R A M A \0 \0 \0 \0 \0 \0

0 1 2 3 4 5 6 7 8 9

3 : Initilization without size :


Ex: consider the declaration along with the initialization
char b[]={‘C’,’O’,’M’,’P’,’U’,’T’,’E’,’R’,’\0’};
4) Array Initilization with a String :
consider the declaration with string initialization.
char b[ ] = “COMPUTER”;
Here, the string length is 8 bytes. But, string size is 9 bytes. So the compiler reserves
8+1 memory locations and these locations are initialized with the characters in the
order specified. The string is terminated by \0 by the compiler.
Reading and Writing Strings : The “%s‟ control string can be used in scanf()
statement to read a string from the teriminal and the same may be used to write
string to the terminal in printf() statement.
Example : char name[10];
scanf(“%s”,name);
printf(“%s”,name);

String Input/output Functions


The strings can be read from the keyboard and can be displayed onto the monitor
using various functions.
The various input and output functions that are associated with can be classified as

I / O Functions

Formated I/O Functions Unformated I/O Functions

Inpu Outpu
t t Inpu Outpu
t t

scanf( print(
) ) getc() putc(
)
fscanf( fprintf(
) ) getchar( putchar(
) )
gets( puts(
) )
getch()

getche(

Unformated I/O Functions


1 : getchar() function : A single character can be given to the computer using
“C‟ input library function getchar().
Syntax : char_ variable=getchar();
The getchar() function is written in standard I/O library. It reads a single character
from a standard input device. This function do not require any arguments.
2 : putchar() function :The putchar() function is used to display one character at a
time on the standard output device.
Syntax : putchar(character_varaiable);
3 : getch() function :The getch function reads a single character directly from the
keyboard, without echoing to the screen.
Syntax : int getch();
4 : getche() function :The getche() function reads a single character from the
keyboard and echoes it to the current text window.
Syntax : int getche();
5 : getc() function : This function is used to accept a single character from the
standard input to a character variable.
Syntax : character_variable=getc();
6 : putc() function :This function is used to display a single character in a character
variable to standard output device.
Syntax : putc(character_variable);
7 : gets() : The gets() function is used to read a string of text from the standard input
device (keyboard) until a new-line character is encountered and then appends a null
character to the string.
Syntax : gets(char_ type_ of_ array_ variable);
char line[80];
gets(line);
8 : puts() :The puts() function is used to display the string to the standard output
device (Monitor).
Syntax : puts(char_ type_ of_ array_ variable);
char line[80];
gets(line);
puts(line);
reads a line of text from the keyboard and displays it on the screen.
String Manipulation Functions/ String Handling Functions
The various string handling functions that are supported in C language are as shown

String Function Description

strlen(str) Returns the length of the string str.

strcpy(str1,str2) Copies the string str2 to string str1

strcat(str1,str2) Append string str2 to string str1.

strrev(str) Reverse the string str.

strcmp(str1,str2) Compare two strings str1 and str2 and


returns the ASCII difference between
first unmatching character of two strings.
Array of Strings
An array of strings is a 2-D array of characters. Just like we can create a 2-D array
of int, float, etc., we can also create a 2-D array of character or array of strings.
Ex:
Char city[][] = { “Puducherry”,
“Karaikal”,
“Mahe”,
“Yanam”
};

You might also like