Notes of Array Functions Structure Union String
Notes of Array Functions Structure Union String
Array is the collection of similar data types or collection of similar entity stored in contiguous memory
location. Array of character is a string. Each data item of an array is called an element. And each
element is unique and located in separated memory location. Each of elements of an array share a
variable but each element having different index no. known as subscript.
An array can be a single dimensional or multi-dimensional and number of subscripts determines its
dimension. And number of subscript is always starts with zero. One dimensional array is known as
vector and two dimensional arrays are known as matrix.
Properties of an array
1. The type of an array is the data type of its elements.
2. The location of an array is the location of its first element.
3. The length of an array is the number of data elements in an array.
4. The size of the array is the length of the array times the size of the elements, but the size of the array
is usually referred as the product of subscript used.
________________________________________________________________________
ADVANTAGES: Array variable can store more than one value at a time where other variable can store
one value at a time.
Example:
int arr[100];
int mark[100];
DECLARATION OF AN ARRAY :
Its syntax is :
Data type array name [size];
int arr[100];
int mark[100];
int a[5]={10,20,30,100,5}
The declaration of an array tells the compiler that, the data type, name of the array, size of the array and
for each element it occupies memory space. Like for int data type, it occupies 2 bytes for each element
and for float it occupies 4 byte for each element etc.
INITIALIZATION OF AN ARRAY:
After declaration element of local array has garbage value. If it is global or static array then it will be
automatically initialize with zero. An explicitly it can be initialize that Data type array name [size] =
{value1, value2, value3…}
Example:
in ar[5]={20,60,90, 100,120}
Array subscript always start from zero which is known as lower bound and upper value is known as
upper bound and the last subscript value is one less than the size of array.
The array elements are standing in continuous memory locations and the amount of storage required for
hold the element depend in its size & type.
Once the array is declared, how individual elements in the array are accessed. This is done with the help
of subscripts (i.e., number specified in the square brackets following the array name).The subscript
specifies the elements position in the array. The array elements are numbered, starting from zero. The
first item stored at the address pointed by the array name itself. This can also be referred as position
0.Thus the first element of the array age is referred as age[0].The fourth element of the array is reoffered
as age[3].
OUTPUT:
Enter a value for arr[0] = 12
Enter a value for arr[1] =45
Enter a value for arr[2] =59
Enter a value for arr[3] =98
Enter a value for arr[4] =21
The array elements are 12 45 59 98 21
Example: From the above example value stored in an array are and occupy its
memory addresses 2000, 2002, 2004, 2006, 2008 respectively.
a[0]=12, a[1]=45, a[2]=59, a[3]=98, a[4]=21
ar[0] ar[1] ar[2] ar[3] ar[4]
12 45 59 98 21
2000 2002 2004 2006 2008
Example 2:
/* Write a program to add 10 array elements */
#include<stdio.h>
void main()
{
int i ;
int arr [10];
int sum=0;
for (i=0; i<=9; i++)
{
printf (“enter the %d element \n”, i+1);
scanf (“%d”, &arr[i]);
}
for (i=0; i<=9; i++)
{
sum = sum + a[i];
}
printf (“the sum of 10 array elements is %d”, sum);
}
OUTPUT:
For example:-
int marks[]={99,78,50,45,67,89};
If during the initialization of the number the initializers is less then size of array, then all the remaining
elements of array are assigned value zero .
For example:-
int marks[5]={99,78};
Here the size of the array is 5 while there are only two initializers so After this initialization, the value of
the rest elements are automatically occupied by zeros such as
Marks[0]=99 , Marks[1]=78 , Marks[2]=0, Marks[3]=0, Marks[4]=0
Again if we initialize an array like
int array[100]={0};
Then the all the element of the array will be initialized to zero. If the number of initializers is more than
the size given in brackets then the compiler will show an error.
For example:-
int arr[5]={1,2,3,4,5,6,7,8};//error
we cannot copy all the elements of an array to another array by simply assigning it to the other array
like, by initializing or declaring as
int a[5] ={1,2,3,4,5};
int b[5];
b=a;//not valid
(note:-here we will have to copy all the elements of array one by one, using for loop.)
Two dimensional array is known as matrix. The array declaration in both the array
i.e.in single dimensional array single subscript is used and in two dimensional array two subscripts are is
used.
Its syntax is
Or we can say 2-d array is a collection of 1-D array placed one below the other.
Example:-
int a[2][3];
Total no of elements=row*column is 2*3 =6
For example:-
20 2 7
8 3 15
For processing 2-d array, we use two nested for loops. The outer for loop
corresponds to the row and the inner for loop corresponds to the column.
For example
int a[4][5];
for example:-
int mat[4][3]={11,12,13,14,15,16,17,18,19,20,21,22};
These values are assigned to the elements row wise, so the values of
elements after this initialization are
While initializing we can group the elements row wise using inner braces.
for example:-
int mat[4][3]={{11,12,13},{14,15,16},{17,18,19},{20,21,22}};
And while initializing , it is necessary to mention the 2nd dimension where 1st
dimension is optional.
int mat[][3];
int mat[2][3];
int mat[][];
int mat[2][]; invalid
If we initialize an array as
int mat[4][3]={{11},{12,13},{14,15,16},{17}};
Then the compiler will assume its all rest value as 0,which are not defined.
Mat[0][0]=11, Mat[1][0]=12, Mat[2][0]=14, Mat[3][0]=17
Mat[0][1]=0, Mat[1][1]=13, Mat[2][1]=15 Mat[3][1]=0
Mat[0][2]=0, Mat[1][2]=0, Mat[2][2]=16, Mat[3][2]=0
String
Array of character is called a string. It is always terminated by the NULL character. String is a one
dimensional array of character.
Here each character occupies 1 byte of memory and last character is always NULL character. Where ’\o’
and 0 (zero) are not same, where ASCII value of ‘\o’ is 0 and ASCII value of 0 is 48. Array elements of
character array are also stored in contiguous memory allocation.
The terminating NULL is important because it is only the way that the function that work with string can
know, where string end.
Here the NULL character is not necessary and the compiler will assume it automatically.
A string constant is a set of character that enclosed within the double quotes and is also called a literal.
Whenever a string constant is written anywhere in a program it is stored somewhere in a memory as an
array of characters terminated by a NULL character (‘\o’).
Example – “m”
“Tajmahal”
“My age is %d and height is %f\n”
The string constant itself becomes a pointer to the first character in array.
1000 1001 1002 1003 1004 1005 1006 1007 1007 1008
T a j m a h a l \o
There are several string library functions used to manipulate string and the prototypes for these functions
are in header file “string.h”.
Several string functions are
strlen() This function return the length of the string. i.e. the number of characters in the string excluding
the terminating NULL character.
It accepts a single argument which is pointer to the first character of the string.
1000 1001 1002 1003 1004 1005 1006 1007 100 1009
T a j M A H a l \o
Example:-
#include<stdio.h>
#include<string.h>
void main()
{
char str[50];
print(”Enter a string:”);
gets(str);
printf(“Length of the string is %d\n”,strlen(str));
}
Output:
strcmp()
This function is used to compare two strings. If the two string match, strcmp() return a value 0 otherwise
it return a non-zero value. It compare the strings character by character and the comparison stops when
the end of the string is reached or the corresponding characters in the two string are not same.
strcmp(s1,s2) return a value:
<0 when s1<s2
=0 when s1=s2
>0 when s1>s2
The exact value returned in case of dissimilar strings is not defined. We only know that if s1<s2 then a
negative value will be returned and if s1>s2 then a positive value will be returned.
/*String comparison…………………….*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[10],str2[10];
printf(“Enter two strings:”);
gets(str1);
gets(str2);
if(strcmp(str1,str2)==0)
{
printf(“String are same\n”);
}
else
{
printf(“String are not same\n”);
}
}
strcpy()
This function is used to copying one string to another string. The function strcpy(str1,str2) copies str2 to
str1 including the NULL character. Here str2 is the source string and str1 is the destination string.
The old content of the destination string str1 are lost. The function returns a pointer to destination
string str1.
Example:-
#include<stdio.h>
#include<string.h>
void main()
{
char str1[10],str2[10];
printf(“Enter a string:”);
scanf(“%s”,str2);
strcpy(str1,str2);
printf(“First string:%s\t\tSecond string:%s\n”,str1,str2);
strcpy(str,”Delhi”);
strcpy(str2,”Bangalore”);
printf(“First string :%s\t\tSecond string:%s”,str1,str2);
strcat()
This function is used to append a copy of a string at the end of the other string. If the first string is
“”Purva” and second string is “Belmont” then after using this function the string becomes
“PusvaBelmont”. The NULL character from str1 is moved and str2 is added at the end of str1. The 2nd
string str2 remains unaffected.
A pointer to the first string str1 is returned by the function.
A function, which is predefined in ‘C’ is known as library function, e.g., printf, scanf, getch, etc.,
are library functions. Appropriate header files must be included in the programme for using the library
functions.
main() is the example of user-defined functions. printf() and scanf() are called the library functions. We
already user other library functions such as sqrt(),cos(),sin(),tan(),strcmp(),strcat() etc.This is greatest
features in C is that there is no conceptual difference between the user-defined functions and library
functions. For example, we can write a series of function to process matrices (such as square of given
number, finding cos value, finding sine value, etc).These are user-defined functions they are written by
user. After user, they can be compiled into libraries and distributed. To the users of the library, these
functions will act as library functions. That is these functions are predefined and precompiled; the users
need not worry about the functions work internally.
____________________________________________________________________________
1.3 NEED FOR USER-DEFINED FUNCTIONS
As discussed earlier, main () is a specially recognized pre-defined function in C.In every
program we have to use main () function to indicate where the program has been executed. While in any
program, does not utilizing the main function, it has face to the number of problems. In C, to write a
program to become too large and complex and the result has been debugging, testing, and maintaining
becomes difficult. In this situation, if a program it‟s large, program is divided into functional parts, then
each part may be independently coded and executed each part of program later combined into single
unit. These subprograms called function, this way to manipulate, the easier to understand, debug and
test.
In C, some time we need certain types of operation or calculations is repeated again and again in
the program. In this situation, we use user-defined functions. This saves both the time and space.
Main()
Fn 2.1 Fn 2.2
___________________________________________________________________________
DEFINITION OF FUNCTIONS
A function is defined as a self-contained program which is written for the purpose of
accomplishing some task.
SYNTAX
returntype functionname(argument list)
{
declaration(s);
statement(s);
return(expression);
}
where
returntype->specifies the data type value to be returned by the function.
The return type is assumed to be of type int by default if it is not specified.
function name-> used to identify the function.
argument list->specified inside the parenthesis after the function name is optional.
Most functions have list of parameters and a return value that provides means for communication
between functions. The arguments in the function reference, which defines the data items that are
actually transferred, are referred as actual arguments or actual parameters.
All variables declared in function definitions are local variables. Their scope is visible known only in the
function in which they are defined. Functions arguments are als0 local variables.
A MULTI-FUNCTION PROGRAM
A function is a self-contained block of code that performs a particular task. Once a function has been
designed and packed, it can be treated as a „block box‟ that takes some data from the main program. All
that the program knows about a function is what goes in and what comes out. Every C program can be
designed using a collection of block boxes known as functions.
1#include<stdio.h>
2void func(); declaration
3void main()
4{
5printf(“Inside the Main Function”);
6func(); calling
7printf(“\n Again Inside Main Function”);
8}
9void func() //fn defi
10{
11printf(“\n Inside func Function”);
12}
The above set of statements defined a function called func(), which calls the function main(),its
exceeded and print the message is again inside main function.
This program will print the following output
Inside main function
Inside func function
Again inside main function
The program execution always begins with the main function. During execution of the main, the first
statements are printed “inside the main function”. Hence the function is called func().After it calls the
user-defined function to print the message inside func function. After again control passes to the main()
function, to print the message is called again the inside the main function.
Any function calls any other function. A „called function‟ also an another function. A function can be
called more than once. This is the main features of using function.
Except the starting point, there are no other predefined relationship, rules of precedence, or hierarchies
among the function that make up a complete program. The functions can be placed in any order. A
called function can be placed in any order. A called function can be placed either before or after the
calling function
Modular Programming
Modular programming is a software design technique breaking a large program down into a
number of functions, each of which performs a specific, well-defined task. This separates task is called
modules. These modules are carefully integrated to become a software system that satisfies the system
requirements. It is basically a “divide-and-conquer” approach to program solving.
Modules are typically incorporated into the program through interfaces. A module interface expresses
the elements that are provided and required by the module. The elements defined in the interface are
detectable by other modules. The implementation contains the working code that corresponds to the
elements declared in the interface.
____________________________________________________________________________
They are three elements that are related to user defined functions are:
1. Function definition
2. Function call
3. Function declaration
The function definition is an independent program module that is specially written to implement the
requirements of the function. In order to use this function we need to invoke it at a required place in the
program. This is known as the function call. The program (or a function) that calls the function is
referred to as the calling program or calling function. The calling program should declare any function
(like declaration of a variable).This is known as function declaration or function prototype.
Function Definition
A function definition, also known as function implementation it‟s include the following elements.
1. Function name
2. Function type
3. List of parameters
4. Local variable declaration
5. Function statements
6. A return statement
All the six elements are grouped into two parts, namely,
Function header
Function body
SYNTAX
return-type function-name(parameters)
{
Declarations;
Statements;
return value;
}
where,
return-type ->type of value returned by function or void if none
And represents external values needed by the function. The list of parameters can be empty.
All declarations and statements that are valid in the main program can be used in the
Function definition, where they make up the function body.
Function Header
The function header consists of three parts: The function type (also known as return type, the function
name and the formal parameters list. Note that a semicolon is not used at the end of the function header.
Function Body
The function body contains the declarations and statements necessary for performing the required task.
The body enclosed in braces, contains three parts, and is given below:
Function Call
A function can be called by simply using the function name followed by a list of actual parameters (or
arguments), if any, enclosed in parentheses.
SYNTAX
Variable=function-name (arguments);
Variable is assigned the return-value of the function.
The arguments are values with types corresponding to the function parameters.
Function Declaration
Like variables all function in a C program must be declared, before they are invoked. A function
declaration (also known as function prototype) consists of four parts.
1. Function type (return type)
2. Function name
3. Parameter list
4. Terminating semicolon
SYNTAX
return-type function-name(parameter types);
The function body is replaced by a semi-colon.
Parameters need not be named, it is sufficient to specify their types.
EXAMPLE
Write a program for sum of two numbers and return the sum to the main function.
#include<stdio.h>
void main()
{
int addnum(int,int);
int sum,a,b;
printf(“\n Enter two number to be summed:”);
scanf(“%d %d”,&a,&b);
sum=addnum(a,b);
printf(“\n The sum of %d and %d is %d”,a,b,sum);
}
int addnum(num1,num2)
{
int tot;
tot=num1+num2;
return(tot);
}
Sample program output:
Enter two numbers to be summed: 15, 17
The of 15 and 17 is 32
The above program consists of two functions,
The required main function
The programmer defined function addnum, which sums the two values.
The function main reads in two integer values, and assigns them to a and b.Then, main calls addnum,
transferring the integer values a and b receiving their sum. The sum is then displayed and the program
terminates.
The integer values are transferred via the arguments num1 and num2,and their sum tot is returned to the
calling portion of the program via the return statement.
____________________________________________________________________
Storage Classes
Storage class in c language is a specifier which tells the compiler where and how to store variables, its
initial value and scope of the variables in a program. Or attributes of variable is known as storage class
or in compiler point of view a variable identify some physical location within a computer where its
string of bits value can be stored is known as storage class.
The kind of location in the computer, where value can be stored is either in the memory or in the
register. There are various storage class which determined, in which of the two location value would be
stored.
Syntax of declaring storage classes is:-
storageclass datatype variable name;
There are four types of storage classes and all are keywords:-
1 ) Automatic (auto)
2 ) Register (register)
3) Static (static)
4 ) External (extern)
Examples:-
auto float x; or float x;
extern int x;
register char c;
static int y;
1.An array demands a homogeneous data type, i.e., the elements of an array must be of the same data type,
where as structure is a heterogeneous data type, since it can have any data type as its member.
2.The difference is that elements in an array are referred by their positions, where as members in a structure
are referred by their unique name.
DECLARING A STRUCTURE
member-type1 member-name1;
member-type2 member-name2;
………
……….
Where
struct->is a keyword
struct type->is a name (tag) that identifies structures of composition member-type1
member name1.member-type2 member name2…are individual declaration.
By defining a structure the programmers derives a new data type composed of a collection of
already known data types and their name. For example, suppose that the information about 10000
business accounts has to be maintained. The information consists of mixed data types, where for each
account the following are required.
EXAMPLE
account number (int)
account type (short)
name (30 char array)
street address (30 char array)
city/state/zip (30 char array)
balance long
last payment (long)
date
struct account
{
int acct_no;
short acct_type;
char name[30];
char street[30];
char city_state[30];
long balance;
long last_payment;
};
DEFINING A STRUCTURE
Declaring a structure is just a skeleton it merely describes the template. It does not reserve
any memory space rather than the declaration creates a new data type. To use the structure you have
to define it. Defining a structure means creating variables to access the members in the structure.
Creating a structure variable allocates sufficient memory space to hold all the members of the
structure. Structures variables can be created during structure declaration or by explicitly using the
structure name.
SYNTAX
struct <structure-name>
{
data type member1;
data type member2;
data type member3;
:
:
data type member;
}structure variable(s);
EXAMPLE
struct employee
{
int empno;
char empname[15];
float salary;
}emp1
SYNTAX
The following figure shows the memory allocation of structure shown in the following figure:
empno 2 bytes
empname 15 bytes
Salary 4 bytes
NOTE
The keyword struct is optional when defining the structure using the structure name.
INITIALIZING A STRUCTURE
Similar to initialization of arrays, we can initialize structure variables also. The initializing a structure
variable expressed is expressed as:
SYNTAX
struct <structure_name>
{
data type member1;
:
:
:
data type member;
}structure_variable={value1,value2,…..valueN};
EXAMPLE
struct employeedet
{
int height;
float weight;
}emp1={165,60};
the above initialization initializes 165 to the structure member height and 60 to the structure member
weight. The value to be initialized for the structure members must be enclosed within a pair of
braces.
NOTE
The constants to be initialized to the structure members must be in the same order in which the
members are declared in the structure.
OPERATIONS ON STRUCUTRES
The number of operations which can be performed over structures is limited. Following are the
permissible operations:
1. Accessing the individual members of a structure variable with the help of members operator (using
dot operator)
EXAMPLE
Where
union->is a keyword.
tag-name->is any user-defined name, which should be valid C identifier.
data-type->is any valid data type supported by C or user-defined type.
member1,member2…member->are the members of the union
A memory location gets allocated, the size of which is equal to that of the largest of the members
member1,member2,member3,…..member n.Accessing the members of a union is similar to
accessing the members of a strucute.Dot operator is used to access each individual member. Dot
operator expects union variable to its left and member name to its right.
EXAMPLE 1
union item
{
int m;
float p;
char c;
}
code;
union item makes a group of three data items of type int, float and char.
union item t;
A variable t declared to be of type union temp. As a result of this; only one memory location
gets allocated. It can be referred to by any one individual member at any point of time. The size
of the memory location is four bytes, which happens to be the size of the largest sized data type
float in the member list.
Example 2
Union var
{
Int m;
Char c;
Float a;
}
Union var x;
Now x is a union containing three members m,c,a. But only one value can be stored
either in x.m, x.c or x.a
1. A structure is a user defined datatype available in C that allows to combine data items of
different kinds.
Union is also a user defined datatype that allows for storing different data types in
the same memory locations. We can define a union with many members, but only one
member can contain a value at any given time.
3. Members of structure do not share memory. So a structure need separate memory space
for all of its members.
Union shares the memory space among its members.So no need to allocate memory
to all members.
5. Size of structure is greater than or equal to sum of the each members size.
Size of union is equal to the size of the members having greater size.