Vous êtes sur la page 1sur 32

INDEX

Unit -3 CONTENT Page No

Arrays 2
1

Declaration 2
2

Initialization 3
3

One dimensional and Two 3


4 dimensional arrays

String 14
5

String operations 18
6

String Arrays 19
7

Simple programs 22
8

sorting 24
9

searching 26
10

matrix operations 30
11

1
UNIT III ARRAYS AND STRINGS

Arrays - Initialization - Declaration - One dimensional and Two dimensional arrays.


String- String operations - String Arrays. Simple programs- sorting- searching -
matrix operations.

3.1 Array
Array is a collection of similar data items, which are stored under a common
name. A value in an array is identified by Index.
Array is a derived data type. It is very effective when working with large number
of data of same data type or different data types. Array reduces the programming size or
coding.
All elements of an array share the same name, and they are distinguished form
one another with help of an element number.
All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last element.

Array[0] Array[1] Array[2] Array[3] ----

First element Last element

3.1.1 Declaration

To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows:

datatype arrayname [ arraysize ];

ex: int a[10];


where a is the arrayname and its size is 10.
2
3.1.2. Initializing Arrays

You can initialize array in C as follows:

double e[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

int a[5] = {10,2,3,4, 7};

The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ].

int age[4];

age[0]=14;

age[1]=13;

age[2]=15;

age[3]=17;

Arrays are classified as follows.


1. One dimensional array
2. Two dimensional array
3. Multidimensional array
4. Dynamic array

3.1.3. One Dimensional Array:

It is a linear array when working with only one set of data at a time whose
elements are accessed with a single index.

Declaring One Dimensional Array:

3
It is similar to declaring any other primary data type except, the number element
must specified for an array in bracket [ ].

int a[5];

float b[10];

double c[6];

char s[4];

The arrays declared as above. The numbers inside the bracket is the number of elements
for that variable. Therefore a can store 5 int values, b 10 float values, c 6 double values,
and s 4 char values.

Initializing One Dimensional Array

int a[5] = {1,2,3,4,5};

All the array elements are assigned values. The last element for the character
arrays must be provided for NULL character.

char t[6] ={‘a’,’p’,’p’,’l’,’e’};

/* To print all the elements of the array


for (int i=0;i<5;i++)
{
printf("%d", array[i]);
}

4
Reading & assigning an array

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


{
scanf(“%d”, &x[i]);
}

Ex: 1 Reading value to array by program

#include >stdio.h>
Int main(void)
{
int x[5],i;
for (i=0; i<5; ++i)
{
scanf(“%d”, x[i]);
}
Printh(“the elements are: \n”);
for (i=0; i<5; ++i)
{
printf(“%d”, x[i]);
}

Output:
1
2
3
4

5
5
the elements are:
1
2
3
4
5

Ex: 2

/******* Sum of Positive and negative numbers *******/


#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,p=0,n,ne=0;
clrscr();
printf("enter the array size");
scanf("%d",&n);
printf("enter the numbers \n");
for(i=0;i<=n;i++)
scanf("%d",&a[i]);
for(i=0;i<=n;i++)
{
if(a[i]>0)
p=p+a[i];
else
ne=ne+a[i];
}
printf("\nthe sum of positive numbers are %d\n",p);

6
printf("\nthe sum of negative numbers are %d\n",ne);
getch();
}

Output:
enter the array size

Enter the elements

-4

-5

The sum of positive numbers are = 6

The sum of negative numbers are = -9

We find positive and negative numbers put a simple logic here:

If the number is greater than zero, normally we say that it is positive otherwise negative
number.

Similarly we also find how many odd numbers & even numbers in a set,

/******* Sum of odd and even numbers *******/


#include<stdio.h>
#include<conio.h>
void main()
{

7
int a[10],i,o=0,e=0,n;
clrscr();
printf("enter the size of the array:");
scanf("%d",&n);
printf("enter the elements \n");
for(i=0;i<=n;i++)
scanf("%d",&a[i]);
for(i=0;i<=n;i++)
{
if(a[i] % 2 ==0)
o++;
else
e++;
}
printf("\n the sum of odd numbers are %d\n",o);
printf("\n the sum of even numbers are %d\n",e);
getch();
}

Output:
Enter the size of the array : 5

Enter the elements

10

20

30

The sum of odd numbers are : 8

8
The sum of even numbers are : 60

3.1.3. Two Dimensional Aray

Initializing two Dimensional Array

Two dimensional arrays are stored in a row-column, where one index refers the
row and the second index refers column.

int A[3][3] = {{0},{0},{0}};

int a[3][3] = {0,0,0};

In this method the value in the entire array element will be zero.

Col 0 col1 col2

0 0 0
Row 0 0 0 0
Row 0 0 0 1
Row 2

a[0][0]=0; a[0][1]=0; a[0][2]=0;


a[1][0]=0; a[1][1]=0; a[1][2]=0;
a[2][0]=0; a[2][1]=0; a[2][2]=0;

/******* matrix addition *******/


#include<stdio.h>
#include<conio.h>

9
void main()
{
int a[2][2],b[2][2],c[2][2],i,j;
clrscr();
printf("enter the A matrix");
for(i=0;i<=2;i++)
for(j=0;j<=2;i++)
scanf("%d",&a[i][j]);
printf("enter the B matrix");
for(i=0;i<=2;i++)
for(j=0;j<=2;i++)
scanf("%d",&b[i][j]);
printf("sum of matrices");
for(i=0;i<=2;i++)
for(j=0;j<=2;i++)
c[i][j]= a[i][j]+b[i][j];
printf(“Addition of two matrices\n”)’;
for(i=0;i<=2;i++)
for(j=0;j<=2;i++)
printf("%d",c[i][j]);
}

Output:

Enter the A matrix:


2 2
2 2

Enter the B matrix:


2 2
2 2
Addition of two matrices:
4 4
4 4

10
3.1.3. Multidimensional Array
The dimension with three or more called multidimensional arrays.

Initializing multi Dimensional Array


int a[3][3][4];

Multidimensional Array
#include<stdio.h>
#include<conio.h>
 
void main()
{
int i, j, k;
int arr[3][3][3]=  
        {
            {
            {11, 12, 13},
            {14, 15, 16},
            {17, 18, 19}
            },
            {
            
{21, 22, 23},
            {24, 25, 26},
            {27, 28, 29}
            },
            {
            {31, 32, 33},
            {34, 35, 36},
            {37, 38, 39}
            },
        };

11
clrscr();
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
    for(j=0;j<3;j++)
    {
        for(k=0;k<3;k++)
        {
        printf("%d\t",arr[i][j][k]);
        }
        printf("\n");
    }
    printf("\n");
}
getch();
}

Output:
:::3D Array Elements:::

11 12 13

14 15 16

17 18 19

21 22 23

24 25 26

27 28 29

31 32 33

34 35 36

37 38 39

12
3.1.3. Dynamic Array

The process of allocating memory during program execution is called dynamic


memory allocation. The dynamic array can be created during runtime using following C
function.

They are 4 dynamic memory allocation functions in C.

1. malloc
2. calloc
3. realloc
4.free
1. malloc()

malloc () function is used to allocate space in memory during the execution of the
program. The syntax of this

malloc (number *sizeof(int));

2.Calloc()

It initializes the allocated memory to zero.

calloc (number, sizeof(int));

13
3. realloc()

realloc () function modifies the allocated memory size by malloc () and calloc ()
functions to new size.New block is allocated for the full size of reallocation, then copies
the existing data to new block and then frees the old block.

realloc (pointer_name, number * sizeof(int));

 4. free()

 free () function frees the allocated memory by malloc (), calloc (), realloc ()
functions and returns the memory to the system.

free (pointer_name);

These files are located in <stdlib.h.> file. It is used in linked lists, stacks, and queues in
the data structures.

3.2. CHARACTER ARRAYS : STRINGS

String is the collection of characters. Header file used here is string.h

datatype variable_name [] = "ptr";

It is a one dimensional array of characters terminated by a null(‘\o’) character.

Example:

/* Welcome message*/
#include <stdio.h>
int main ()
{
char g[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

14
printf("message: %s\n", g );
return 0;
}

Output:
Hello
‘\0’ is not necessary. C language automatically insert at the end of the string.

Consider the following program,

/* ******* array of characters ******* */


#include <stdio.h>
main()
{
static char name1[] = {'H','e','l','l','o'};
static char name2[] = "Hello";
printf("%s\n", name1);
printf("%s\n", name2);
}

Output:
H
E
L
L
O

Hello

15
3.2.1. Built in functions for string handling

The following macros are built into the file string.h

strcat Appends a string

strchr Finds first occurrence of a given character

strcmp Compares two strings

strcmpi Compares two strings, non-case sensitive

strcpy Copies one string to another

strlen Finds length of a string

strlwr Converts a string to lowercase

strncat Appends n characters of string

strncmp Compares n characters of two strings

strncpy Copies n characters of one string to another

strnset Sets n characters of string to a given character

strrchr Finds last occurrence of given character in string

strrev Reverses string

strset Sets all characters of string to a given character

strspn Finds first substring from given character set in string

Strupr Converts string to uppercase

C allows us to manipulate characters the same way we do with numbers. Whenever a


character constant or character variable is used in an expression, it is automatically converted
into integer value by the system.

16
The C library supports a function that converts a string of digits into their integer
values.
The function takes the form
x = atoi(string)

For eg, if the machine uses the ASCII representation, then,

x = ‘a’;
printf(“%d \n”,x);

will display the number 97( ie., ASCII) on the screen.

Example:1

/* ******* To convert a string to uppercase****** */


#include <stdio.h>
#include <string.h>
main()
{
char name[80];
printf("Enter in a name in lowercase\n");
scanf( "%s", name );
strupr( name );
printf("The name in uppercase is %s", name );
}

Output:
Enter in a name in lowercase
madhus
the name in uppercase is : MADHUS

17
Example:2

/* string operations */
#include <stdio.h>
#include <string.h>

int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;

/* copy str1 into str3 */


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}

Output:
HelloWorld
Strlen(“HelloWorld”): 10

18
Example:3

/* TO FIND THE LENGTH OF THE STRING */


#include<stdio.h>
#include<string.h>
 
main()
{
char s[50];
int len;
 
printf("Enter a string to calculate it's length\n");
gets(s);
  len = strlen(a);
  printf("Length of entered string is = %d\n",len);
  return 0;
}

Output:
Enter the string to calculate it’s length : saravanan
Length of entered string is = 9

Example:4

/* to find the length of the string without using function */


#include <stdio.h>
void main()
{
char s[50],i;
printf("Enter a string: ");
scanf("%s",s);
for(i=0; s[i]!='\0'; ++i);
printf("Length of string: %d",i);

19
}

Output:
Enter a string ; abirami
Length of a string : 7

Example:5
/* to concate two strings with out using string function */
#include <stdio.h>
int main()
{
char s1[50], s2[50], i, j;
printf("Enter first string: ");
scanf("%s",s1);
printf("Enter second string: ");
scanf("%s",s2);
for(i=0; s1[i]!='\0'; i++)
for(j=0; s2[j]!='\0'; j++)
s1[i]=s2[j];

s1[i]='\0';
printf("After concatenation: %s",s1);
return 0;
}

Output:
Enter the first string: vijaya
Enter second string: lakshmi
After concatenation : vijayalakshmi

Example:6
/* sorting a word in order */
#include<stdio.h>

20
#include<string.h>

 void main()
 {
   char s[20],s1[20];
   int i,j,n,temp;
   clrscr();
   printf("\n Enter any string : ");
   gets(s);
   n=strlen(s);
   for(i=0;i<n;i++)
    {
     for(j=0;j<n-i;j++)
      {
       if(a[j]>a[j+1])
          {
           temp=a[j];
           a[j]=a[j+1];
           a[j+1]=temp;
          }
}
}
          printf("\n The sorted string is :");
    for(i=0;i<=n;i++)
    printf("%c",a[i]);
   getch();
 }

21
Output:

Enter any string : abirami


The Sorted string is : aabiimr

3.3. Simple Programs


Program 1 : Write a program to multiply two matrices.

/* Matrix Multiplication*/
#include <stdio.h>
#include <conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5];
int row1,col1,row2,col2,i,j,k;
clrscr();
printf("Enter the row value of first matrix");
scanf("%d",&row1);
printf("\nEnter the column value of first matrix");
scanf("%d",&col1);
printf("\nEnter the row value of second matrix");
scanf("%d",&row2);
printf("\nEnter the column value of second matrix");
scanf("%d",&col2);
if(row1==col2)
{
printf("Enter the values of I matrix\n");
for(i=1;i<=row1;i++)
{
for(j=1;j<=col1;j++)
{
scanf("%d",&a[i][j]);

22
}
}
printf("Enter the values of II matrix\n");
for(i=1;i<=row2;i++)
{
for(j=1;j<=col2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=1;i<=row1;i++)
{
for(j=1;j<=col2;j++)
{
c[i][j]=0;
for(k=1;k<=col2;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
for(i=1;i<=row1;i++)
{
for(j=1;j<=col2;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
else
printf("Multiplication cannot be performed");
getch();
}

23
Output:

Enter the row value of I matrix: 2


Enter the row value of I matrix: 2
Enter the row value of II matrix: 2
Enter the row value of II matrix: 2
Enter the values of I matrix
1111
Enter the values of II matrix
1111
The resultant matrix is
2 2
2 2

Program 2 : Write a program to sort strings.

/* Sort String */
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
int i,j,n;
char name[10][10],temp[10];
clrscr();
printf("\n Enter the size");
scanf("%d",&n);
printf("Enter the Names :");
for(i=0;i<n;i++)
scanf("%s",&name[i]);
for(i=0;i<=n;i++)
for(j=i+1;j<=n;j++)
if(strcmp(name[i],name[j])>0)

24
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
printf("The sorted Order is.....\n");
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
getch();
}
Output

Enter The size:4


Enter the Names:
viji
Abi
Selva
vanitha

The sorted order is


Abi
selva
vanitha
viji

25
Program 3 : Write a program to search strings.

/* Linear Search*/

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,ele,a[100],f=0;
clrscr();
printf("Enter the n limit :");
scanf("%d",&n);
printf("Enter the elements :");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("enter the element to be searched");
scanf( "%d",&ele);
for(i=1;i<=n;i++)
{
if(a[i]==ele)
f=f+1;
}
if(f!=0)
printf("present");
else
printf("not present");
getch();
}

Output:

Enter the n Limit:5


Enter the Elements:
12

26
23
34
45
56
Enter the elements to be searched:12
Present
Enter the element to be searched:78
Not present

27
UNIT III ARRAYS AND STRINGS

Program 4 : Write a program to search strings by using binary search method.

/* Binary Search*/
#include <stdio.h>
#include <conio.h>
void main()
{
int a[100],i,n,c,m,ele,f=1;
clrscr();
printf("Enter the size of the array");
scanf("%d",&n);
printf("\nEnter the elements in ascending order");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the elements to be searched");
scanf("%d",&ele);
low=0;
high=n-1;
while(low<=high)
{
m=(low+high)/2;
if(ele<a[m])
high=m-1;
else if(ele>a[m])
low=m+1;
else
{
printf("\nEntered element %d is in position %d",ele,m+1);
f=2;
break;
}
}
if(f==1)
printf("\nEntered element is not in the array");

28
UNIT III ARRAYS AND STRINGS

getch();
}
Output:

Enter the size of the array: 5


Enter the elements in ascending order: 11 31 51 71 91
Enter the element to be searched: 71
Entered element 71 is in position 4

29
UNIT III ARRAYS AND STRINGS

Matrix operations
#include <stdio.h>
 void main()
{
int i, j,n,m,c, d, a[5][5],t[5][5];
printf("Enter the number of rows and columns of matrix ");
scanf("%d%d",&m,&n);
printf("Enter the elements of matrix \n");
 
for( i = 0 ; i < m ; i++ )
{
for( j = 0 ; j < n ; j++ )
{
scanf("%d",&a[i][j]);
}
}
 
for( i = 0 ; i < m ; i++ )
{
for( j = 0 ; j < n ; j++ )
{
t[i][j] = a[i][j];
}

printf("Transpose matrix is :-");
 
for( i = 0 ; i < n ; i++ )
{
for( j = 0 ; j < m ; j++ )
{
printf("%d\t",t[i][j]);
}
printf("\n");
}

30
UNIT III ARRAYS AND STRINGS

  }

Output:
Enter the number of rows and columns of matrix
2
2
Enter the elements of matrix
1
2
1
2
Transpose matrix is :
2
1
2
1

31
UNIT III ARRAYS AND STRINGS

UNIT-3

PART-A

1. What is an array? What are the classifications of arrays?


2. Why use arrays?
3. Write an example code to declare two dimensional arrays.
4. List any four string handling functions.
5. How strings are represented in C language?
6. Mention the various types of searching techniques in C
7. What are the limitations of arrays.
8. What is the difference between scanf() and gets() function?

PART-B
1. Describe how to declare two dimensional array using pointers. And write a for loop to store
information and later modification to the declared pointer.
2. Write a C program to arrange the numbers in ascending order.
3. Write a C program to multiply two matrices.
4. Write a C program to search an element using binary search.
5. Write a C program to sort the given names [bubble sort].
6. Explain in detail about various string operations with examples.
7. What is a two dimensional array. Explain its declaration, assignment and various initialization
methods with examples.

32

Vous aimerez peut-être aussi