Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Arrays: Unit - Ii

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 21

UNIT – II

ARRAYS
An array is a group of related data items that share a common name and stored in contiguous
memory locations. Ordinary variables are capable of holding only one value at a time. However,
there are situations in which we would want to store more than one value at a time in a single
variable.

In C, arrays are classified into two types. They are

1. One dimensional arrays

3. Multi-dimensional arrays

1. ONE DIMENSIONAL ARRAYS

One dimensional array Declaration:


Like any other variable, arrays must be declared before they are used. The general form of
array declaration is
datatype variable-name [size];
The type specifies the type of element that will be contained in the array, such as int, float or
char. Size indicates the maximum number of elements that can be stored inside the array.
For example
1) int number[5]; Declares an array number which can store a maximum of 5 integer numbers.
2) float height[50]; Declares an array height which can store a maximum of 50 floating-point
numbers.
3) char name[10]; Declares an array name which can store a maximum of 10 characters.
If we want to represent a set of five numbers say (35, 40, 20, 57, 19) by an array variable num,
then we may declare the variable num as follows.
int num [5];

1
And the computer reserves five storage locations as shown below. We know that memory is
group of memory cells. Each cell can store one byte of information and each cell is accompanied
with some address.

The values to the array elements can be assigned as follows.


num[0]=35;
num[1]=40;
num[2]=20;
num[3]=57;
num[4]=19;
This would cause the array number to store the values as shown below.

INITIALIZING ONE DIMENSIONAL ARRAYS

While declaring an array, we can initialize it with some values. The general format to
initialize one dimensional array is as follows

Syntax: datatye arrayname[size]={v0,v1,v2,-------vn}

Here, v0,v1-----vn are the initial values of the specified array. If we omit the values then
an array contains garbage values. The number of values must be less than or equal to the size of
the array. When there are few values then the remaining elements are assigned with zeros.

We have four options for initializing one dimensional arrays.

2
Option 1: Initializing all memory locations

int temp [5] = {75, 79, 82, 70, 68};

Option 2: initialization without size (Unsized one dimensional arrays)

int temp [] = {75, 79, 82, 70, 68};

Option 3: Partial Array Initialization

int temp [5] = {75, 79, 82};

Option 4 If you do not know any data ahead of time, but you want to initialize

3
everything to 0, just use 0 within { }.

For example:

int temp [5] = {0};

REFERENCING/ACCESSING ONE DIMENSIONAL ARRAY ELEMENTS

A specific element in an array is accessed by an index(subscript or


dimension).The array index starts from 0 i.e ,the first element in the array is numbered 0
and the last element is 1 less than the size of the array. The amount of memory required to
hold an array is directly related to its type and size.

Each subscript must be expressed as non-negative integer. The subscript values must be
enclosed within square brackets. The subscript values can be constant, variable or an
expression.

Example: The ‘n’ elements of an array ‘num’ can be accessed as Follows

num[0], num[1], num[2],------------,num[n-1] Or

The above values can be read using a loo variable as follows

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

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

1./*program to create a single dimensional array & find sum of the elements*/
#include<stdio.h>
4
#include <conio.h>
void main()
{
int a[10],i,n,sum;
clrscr();
printf("enter size" );
scanf("%d",&n);
sum=0;
for (i=0;i<n;i++)
{
printf("enter array element ");
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("the array elements are\n");
for (i=0;i<n;i++)
printf("%d\n",a[i]);
printf("the sum = %d\n",sum);
getch();
}
2./*program to create a single dimensional array and to find large and small of the array
elements */
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10],i,n,large,small;
clrscr();
printf("enter size" );
scanf("%d",&n);
for (i=0;i<n;i++)
5
{
printf("enter array element ");
scanf("%d",&a[i]);
}
large=a[0];
small=a[0];
for (i=1;i<n;i++)
{
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
printf("array elements are\n");
for (i=0;i<n;i++)
printf("%d\n",a[i]);
printf("largest = %d\n",large);
printf("smallest = %d\n",small);
getch();
}

3./* Program To arrange the elements in sorted order */


#include <stdio.h>
#include <conio.h>
void main()
{
int a[10],i,j,n,temp;
clrscr();
printf("enter size" );
scanf("%d",&n);
for (i=0;i<n;i++)
{
6
printf("enter array element ");
scanf("%d",&a[i]);
}
for (i=0;i<n-1;i++)
for (j=0;j<n-i-1;j++)
if (a[j] > a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
printf("the sorted array elements are\n");
for (i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}

MULTI-DIMENSIONAL ARRAYS

An array which has more than one dimension is called a “multidimensional array”.
Multi-dimensional arrays are classified as two dimensional, three-dimensional, and four-
dimensional and so on.

TWO DIMENSIONAL ARRAYS

When an array uses only two subscripts then it is called ”Two dimensional”. A two-
dimensional array is an array of one-dimensional arrays. It can be viewed as table of
elements which contains rows and columns. A two-dimensional array is useful for matrix
operations.

DECLARATION OF TWO DIMENSIONAL ARRAYS

The general format of declaring a two dimensional array is as follows


7
dataType arrayName [rowsize][columnsize];

In the above syntax

The data type is any valid data type of C language.

The ‘array name’ is an identifier that specifies name of the array variable. All the
elements will share this variable name.

The ‘row size’ indicates maximum number of rows and ‘column size’ indicates number of
columns in a row.

Example:

int a[4][3];

Two-dimensional arrays are stored in memory as shown below.

INITIALIZING TWO DIMENSIONAL ARRAYS:


Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces.
int num [2][3] = {0, 0, 0, 1, 1, 1};
This declaration initiates the elements of first row to zero and second row to 1. The Initialization
is done row by row. The above statement is equivalently written as
int num [2][3] = {{0,0,0}, {1,1,1}};
By surrounding the elements of each row by braces we can also initialize a two-dimensional
array in the form of a matrix.
8
int num [2][3] = {
{0,0,0},
{1,1,1}
};
If the values are missing in an initializer, they are automatically set to zero. For instance the
statement
int num[2][3] = {
{1,1},
{2}
};
will initialize the first two elements of the first row to one, the first element of the second row to
two. And all other elements to zero. Memory map of a two dimensional array:
int num[2][3] = {1,2,3,4,5,6};

1./*program to create a two dimensional array of size mxn and print it in matrix form */
#include<stdio.h>
#include <conio.h>
void main()
{
int a[5][5],m,n,i,j;
clrscr();
printf("enter a size of the array:" );
scanf("%d%d",&m,&n);
printf("enter the elements of two dimensional array\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("The two dimensional array\n");
for(i=0;i<m;i++)
9
{
for(j=0;j<n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
getch();
}
2. /* program to add two matrices */
#include<stdio.h>
#include <conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],m,n,i,j;
clrscr();
printf("enter a size of the array :" );
scanf("%d%d",&m,&n);
printf("enter the elements of matrix A\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("enter the elements of matrix B\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&b[i][j]);
for (i=0;i<m;i++)
for (j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("The two dimensional array\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
10
printf("%d ",c[i][j]);
printf("\n");
}
getch();
}
enter a size of the array :2 2                                                                                                 
enter the elements of matrix A                                                                                                 
1 0 0 1                                                                                                                        
enter the elements of matrix B                                                                                                 
1 0 0 1                  
The two dimensional array                                                                                                      
2 0                                                                                                                            
0 2    

3.program to multiply two matrices matrix A of size M XN matrix B of size P XQ Resultant


matrix of size M x Q
#include<stdio.h>
#include <conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;
clrscr();
printf("enter a size of the array A:" );
scanf("%d%d",&m,&n);
printf("enter the elements of matrix A\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("enter a size of the array B:" );
scanf("%d%d",&p,&q);
printf("enter the elements of matrix B\n");
for (i=0;i<p;i++)
for (j=0;j<q;j++)
scanf("%d",&b[i][j]);

11
if (n==p)
{
for (i=0;i<m;i++) /*initialisation of C*/
for (j=0;j<q;j++)
c[i][j]=0;
for (i=0;i<m;i++)
for (j=0;j<n;j++)
for (k=0;k<q;k++)
c[i][k]=c[i][k]+a[i][j]*b[j][k];
printf("The Resultant array\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d ",c[i][j]);
printf("\n");
}
}
else
printf("Matrix multiplication is not possible\n");
getch();
}

12
STRINGS
 C Strings are nothing but array of characters ended with null character (‘\0’).
 This null character indicates the end of the string.
 Strings are always enclosed by double quotes. Whereas, character is enclosed by single
quotes in C.

Declaration of strings

Strings are declared in C in similar manner as arrays. Only difference is that, strings
are of char type.

char s[5];

13
Initialization of strings

In C, string can be initialized in different number of ways.

char c[]="abcd";

OR,

char c[5]="abcd";

OR,

char c[]={'a','b','c','d','\0'};

OR;

char c[5]={'a','b','c','d','\0'};

 Difference between above declarations are, when we declare char as “c[5]“, 5 bytes of
memory space is allocated for holding the string value.
 When we declare char as “c[]“, memory space will be allocated as per the requirement
during execution of the program.

Write a C program to how to read string from terminal.


#include <stdio.h>
main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
}

Output:
Enter name: yamini                                                                                                             
Your name is yamini. 
14
Example program for displaying string:
#include <stdio.h>
main ()
{
char string[20] = "dbsGroups";
printf("The string is : %s \n", string );
getch();
}
Output:
The string is : dbsGroups 

STRING HANDLING FUNCTIONS

The string-handling functions are implemented in libraries.  They are

1. Strcpy()

2. Strcmp()

3. Strcat()

4. Strlen()

5. Strlwr()

6. Strupr()

7. Strchr()

8. Strstr()

9. Strrev()

1. Strcpy()

15
This library function is used to copy from one string to another string.

Syntax: strcpy (destination, source)

Example:

main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
strcpy ( target, source ) ;
printf ( "\ntarget string after strcpy( ) = %s", target ) ;
}
Output:
target string after strcpy( ) = fresh2refresh 

2. Strcmp()

This library function is used to compare two strings.

Syntax: strcmp(str1, str2).

Ex :

main()
{
char str1[20] = “cse”;
char str2[20] = “eee”
int ch;
clrscr();
ch=strcmp(str1,str2);
if(ch==0)
printf("\n the strings are equal:");
else
printf("\n the strings are not equal:");
16
getch();
}

3. Strcat()

This library function concatenates a string onto the end of the other string. 

Syntax: strcat(string1,string2)

Ex :

main()
{
char str1[30]="www.cprogramming";
char str2[15]="expert.com";
clrscr();
strcat(str1,str2) :
printf(" %s ”, str1);
getch();

4. Strlen()

This library function returns the length of a string. 

Syntax: strlen(string);

Ex:
#include <stdio.h>
#include <string.h>
main()
{
char name[80] = “ programming” ;
int l;
17
l= strlen( name );
printf("The lenght is %d", l );
}

5. Strlwr():

It converts string to lowercase.

Syntax: strlwr(string)

Ex:
#include <stdio.h>
#include <string.h>
main()
{
char name[80] = “ PROGRAMMING ”
strlwr( name );
printf("The name is lower case is %s", name );
}
6. Strupr()

It converts string to uppercase.

Syntax: strupr(string)

Ex:

#include <stdio.h>
#include <string.h>

main()
{
char name[80] = “ programming”
strupr( name );
printf("The name is uppercase is %s", name );
18
}
7. Strchr()

The strchr function returns a pointer to the first occurrence of character c in string or a null
pointer if no matching character is found.

Syntax: strchr(char string[], int c);


 str -- This is the C string to be scanned.

 c -- This is the character to be searched in str.

Ex:
main()
{
char s[];
char buf [] = "This is a test";

s = strchr (buf, 't');

if (s != NULL)
printf ("found a 't' at %s\n", s);
}

8. Strstr()

The strstr function returns a pointer within string2 that points to a string identical to string1. If no
such sub string exists in source a null pointer is returned.

Syntax: strstr(char string2[], char string1[]);


Ex:
#include <stdio.h>

main()
{
char s1 [] = "My House is small";
char s2 [] = "My Car is green";
19
printf ("Returned String 1: %s\n", strstr (s1, "House"));
printf ("Returned String 2: %s\n", strstr (s2, "Car"));
}
9. strrev() function

 strrev( ) function reverses a given string in C language. Syntax for strrev( ) function is
given below.

Syntax: strrev(string);

Ex:

main()
{
char name[30] = "Hello";
printf("String before strrev( ) : %s\n",name);
printf("String after strrev( ) : %s",strrev(name));
getch();
}

Strings using two dimensional arrays (Array of strings)

To create a array of strings we use a two dimensional character array.

Syntax: char string[number of strings][length of each string]

To read a strings we use gets().

20
21

You might also like