Sie sind auf Seite 1von 22

3 Arrays and Strings

PIC-17212

Chapter 3: Arrays and Strings


3.1 Arrays
Declaration and initialization of one dimensional, two dimensional and character arrays, accessing array elements.
(10 Marks)

3.2 Declaration and initialization of string variables, string handling functions from standard library
(strlen( ), strcpy( ), strcat( ), strcmp( )).
(08 Marks)

Array:
An array is a collection of similar type elements. These elements are sequentially stored one
after the other in memory. These elements could be all ints, all floats, or all chars etc. Usually, the
array of characters is called a string whereas an array of ints or floats is called simply an array.
Suppose we want to store marks obtained by 100 students and arrange them in ascending order.
There are two options for this:
1) construct 100 variables to store marks of 100 students
2) construct one variable capable of storing all 100 variables.
Obviously, second option is better. But when you will store second value in a simple variable, its
first value is lost. e.g.
int x;
x=10; // current value of x is 10
x=15; // now value of x is 15
In the above example, first we are storing value 10 in variable x. When third statement is
executed, the old value (i.e.10) stored in variable x will be lost and x will now store value 15. In this
situation, arrays can be used to store all the desired values.

Declaration of single dimensional array:


The syntax for declaring single dimensional array is as follows:
data_type array_name[size];
e.g.
int marks[100];
In the above example, an array marks is declared with size 100. The array is of type int.
Therefore in this array, 100 different integer values can be stored. Individual elements of the array
can be accessed by using subscript or index value. e.g. If you want to access first element of the

Computer Department, Jamia Polytechnic (0366)

3 Arrays and Strings

PIC-17212

above array, you have to use marks[0] statement, to access second element of array, marks[1]
statement is used and so on. The last element can be accessed by using marks[99] statement.
marks [0] = 50;

name of array

subscript or index

value to store

In the statement,
int marks[100];
array is declared with one subscript, therefore it is called single dimensional array. Subscript of
array starts from zero. Following are some examples of declaring single dimensional arrays:
float salary[25];
char stud_name[30];
double average[10];

Initialization of one dimensional array:


If array is not initialized, all elements of array contain garbage values. Array can be
initialized in two ways:
1) At the time of declaration
2) At run-time
Following is the general form in which array elements are initialized at the time of declaration:
type array-name[size] = {list of values};

or

type array-name[ ] = {list of values};


In the first statement size is optional. If size is not used then an array is created with the same
size as number of elements in the list. For example,
int arr[5] = {7,9,10,6,11};
or

Computer Department, Jamia Polytechnic (0366)

3 Arrays and Strings

PIC-17212

int arr[ ]={7,9,10,6,11}; // array size is 5


The pictorial representation of the array elements after initialization is as follows:
arr[0]

arr[1]

arr[2]

10

arr[3]

arr[4]

11

Like integer arrays, array of any type can be initialized. e.g.


float salary[ ]={5000.0,6000.25,6575.0,7500.0,7825.0};
char stud_name[ ]={s,c,o,t,t};
Character arrays can be initialized using another method as follows:
char stud_name[]=scott;
Array elements can be initialized at run-time. For example, after declaring an array
int arr[5]; its elements can be initialized as follows:

int arr[5];
arr[0]=71;
arr[1]=5;
arr[2]=15;
arr[3]=-97;
arr[4]=1000;
Values can be accepted from user and stored in array e.g.
int arr[3];
printf(Enter value of first element:);
scanf(%d,&arr[0]);
printf(Enter value of second element:);
scanf(%d,&arr[1]);
printf(Enter value of third element:);
scanf(%d,&arr[2]);
//

Computer Department, Jamia Polytechnic (0366)

3 Arrays and Strings

PIC-17212

Program #1: Write a program in C to initialize and print the contents of an integer array of size 5.
Ans.
#include<stdio.h>
#include<conio.h>
void main( )
{
int marks[ ]={37,59,63,25,71};
int i;
clrscr( );
for(i=0;i<5;i++)
{
printf(\n%d,arr[i]);
}
getch( );
}

Program #2: Write a program in C to declare a float array of size 4.Accept values from user and
store them in array. Print the average of all values.
Ans.
#include<stdio.h>
#include<conio.h>
void main( )
{
float f[4];
float average;
int i;
clrscr( );
printf("Enter the elements of array:\n");
for(i=0;i<4;i++)
{
printf(\nEnter value :);
scanf(%f,&f[i]);
}
average=(f[0]+f[1]+f[2]+f[3])/4;
printf(Average=%f,average);
getch( );
}

OR

Computer Department, Jamia Polytechnic (0366)

3 Arrays and Strings

PIC-17212

In this program loop is used:


#include<stdio.h>
#include<conio.h>
void main( )
{
float f[4];
float sum=0.0, average;
int i;
clrscr( );
printf("Enter the elements of array:\n");
for(i=0;i<4;i++)
{
printf(\nEnter value :);
scanf(%f,&f[i]);
}
for(i=0;i<4;i++)
{
sum=sum+f[i];
}
average=sum/4;
printf(Average=%f,average);
getch( );
}

OR
In this program two loops are combined into single loop:
#include<stdio.h>
#include<conio.h>
void main( )
{
float f[4];
float sum=0.0, average;
int i;
clrscr( );
printf("Enter the elements of array:\n");
for(i=0;i<4;i++)
{
printf(\nEnter value :);
scanf(%f,&f[i]);
sum=sum+f[i];
}
average=sum/4;
printf(Average=%f,average);
getch( );
Computer Department, Jamia Polytechnic (0366)

3 Arrays and Strings

PIC-17212

Program #3: Write a program in C to find the smallest and largest numbers from array.
Ans.
#include<stdio.h>
#include<conio.h>
void main( )
{
int size=0;
int arr[20];
int i;
int smallest, largest;
clrscr( );
printf("Enter the size of array(<20):");
scanf("%d",&size);
printf("Enter the elements of array:\n");
for(i=0;i<size;i++)
{
printf("Enter the element:");
scanf("%d",&arr[i]);
}
smallest=arr[0];
largest=arr[0];
for(i=1;i<size;i++)
{
if(arr[i]<smallest)
smallest=arr[i];
if(arr[i]>largest)
largest=arr[i];
}
printf("%d is smallest.",smallest);
printf("%d is largest.",largest);
getch( );
}
Program #3.1: Write a program in C to search a given number in array.
Ans.
#include<stdio.h>
#include<conio.h>
void main( )
{
Computer Department, Jamia Polytechnic (0366)

3 Arrays and Strings

PIC-17212

int size=0, num;


int arr[20];
int i;
int pos=-1;
clrscr( );
printf("Enter the size of array(<20):");
scanf("%d",&size);
printf("Enter the elements of array:\n");
for(i=0;i<size;i++)
{
scanf("%d",&arr[i]);
}
printf("Enter the number to search:");
scanf("%d",&num);
for(i=1;i<size;i++)
{
if(arr[i]==num)
{
pos=i;
break;
}
}
if(pos!=-1)
{
printf("%d is present at index %d.",num,i);
}
else
{
printf("%d not found.",num);
}
getch( );
}
Program #4: Write a program in C to copy one array into another array.
Ans.
#include<stdio.h>
#include<conio.h>
void main( )
{
int arr[20], arr_copy[20];
int i;
clrscr( );
printf("Enter the size of array(<20):");
scanf("%d",&size);
Computer Department, Jamia Polytechnic (0366)

3 Arrays and Strings

PIC-17212

printf("Enter the elements of array:\n");


for(i=0;i<size;i++)
{
printf(Enter value:);
scanf(%d,&arr[i]);
}
for(i=1;i<size;i++)
{
arr_copy[i]=arr[i];
}
printf("Elements of array:\n");
for(i=0;i<size;i++)
{
printf(%d\n,arr[i]);
}
printf("Elements of copied array:\n");
for(i=0;i<size;i++)
{
printf(%d\n,arr_copy[i]);
}
getch( );
}

Program #5: Write a program in C to arrange elements of array in ascending order:


Ans.
#include<stdio.h>
#include<conio.h>
void main( )
{
int size=0;
int arr[20];
int i,temp;
clrscr( );
printf("Enter the size of array(<20):");
scanf("%d",&size);
printf("Enter the elements of array:\n");
for(i=0;i<size;i++)
{
scanf("%d",&arr[i]);
}
printf("Elements of unsorted array:\n");
for(i=0;i<size;i++)
{
printf("%d\n",arr[i]);
Computer Department, Jamia Polytechnic (0366)

3 Arrays and Strings

PIC-17212

}
for(i=0;i<size;i++)
{
for(int j=0;j<size-1;j++)
{
if(arr[j+1]<arr[j])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf("Elements of sorted array(ascending order):\n");
for(i=0;i<size;i++)
{
printf("%d\n",arr[i]);
}
getch( );
}

Two dimensional arrays:


An array having two subscripts is called two dimensional array. Similarly, an array having
three subscripts is called two dimensional array and so on.
The two dimensional array is also called as a matrix. In two dimensional array, data is stored
in the form of rows and columns. The first subscript or dimension of array gives row and second
dimension gives column of the matrix.
The general form for declaring two dimensional array is:
type array_name[size1][size2];
For example,
int stud[4][2];
In the above statement, an array having 4 rows and two columns is created. In this array total 4x2=8
values can be stored. The array elements are as follows:
1) stud[0][0];
2) stud[0][1];
3) stud[1][0];
4) stud[1][1];

Computer Department, Jamia Polytechnic (0366)

3 Arrays and Strings

PIC-17212

5) stud[2][0];
6) stud[2][1];
7) stud[3][0];
8) stud[3][1];

Initialization of two dimensional array:


Like one dimensional arrays, two dimensional array can be initialized when it is declared.
Following is the general form for declaring and initializing two dimensional arrays:
type array_name[m][n] = { {list-1 of n values},
{list-2 of n values},
.
.
{list-m of n values} };
e.g. Following statement declares and initializes an array with of 3x3.
int A[3][3]={ {1,2,3},
{9,6,13},
{0,4,7} };
In the above example, the array elements and their respective values are as follows:
A[0][0]=1
A[0][1]=2
A[0][2]=3
A[1][0]=9
A[1][1]=6
A[1][2]=13
A[2][0]=0
A[2][1]=4
A[2][2]=7
Elements of two dimensional arrays can be initialized by accepting values from user e.g. the
element of the above array can store value entered by user using following statement:
scanf(%d,&A[0][0]);
Likewise any element of the array can be accessed and initialized.

Computer Department, Jamia Polytechnic (0366)

10

3 Arrays and Strings

PIC-17212

Program #6: Write a program in C to initialize a 2x2 array and print its elements.
Ans.
#include<stdio.h>
#include<conio.h>
void main( )
{
int matrix[2][2]={ {1,2},
{7,8} };
clrscr( );
printf(Elements of array\n);
printf(%d,matrix[0][0]);
printf(\t%d,matrix[0][1]);
printf(\n%d,matrix[1][0]);
printf(\t%d,matrix[1][1]);
getch( );
}
Program #7: Write a program in C to add two matrices of size 2x2 and print the result.
Ans.
#include<stdio.h>
#include<conio.h>
void main( )
{
int A[2][2], B[2][2], C[2][2];
int i,j;
clrscr( );
printf(Enter elements of matrix A:\n);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf(%d,&A[i][j]);
}
}
printf(Enter elements of matrix B:\n);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf(%d,&B[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
Computer Department, Jamia Polytechnic (0366)

11

3 Arrays and Strings

PIC-17212

{
C[i][j]=A[i][j]+B[i][j];
}
}
printf(Elements of matrix C=A+B:\n);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf(%d ,C[i][j]);
}
printf(\n);
}
getch( );
}
Program #8: Write a program in C to find transpose of 3x3 matrix.
Ans.
#include<stdio.h>
#include<conio.h>
int main( )
{
int A[3][3], B[3][3];
int i,j;
clrscr( );
printf("Enter elements of matrix :\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("The matrix before transpose:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",A[i][j]);
}
printf("\n");
}
for(i=0;i<3;i++)
{
Computer Department, Jamia Polytechnic (0366)

12

3 Arrays and Strings

PIC-17212

for(j=0;j<3;j++)
{
B[i][j]=A[j][i];
}
}
printf("The matrix after transpose:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",B[i][j]);
}
printf("\n");
}
getch( );
return 0;
}
Program #9: Write a program in C to multiply two matrices of size 3x3 and print the result.
Ans.
#include<stdio.h>
#include<conio.h>
int main( )
{
int A[10][10], B[10][10], C[10][10];
int i,j,k;
clrscr( );
printf(Enter elements of matrix A:\n);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(%d,&A[i][j]);
}
}
printf(Enter elements of matrix B:\n);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(%d,&B[i][j]);
}
}
for(i=0;i<3;i++)
Computer Department, Jamia Polytechnic (0366)

13

3 Arrays and Strings

PIC-17212

{
for(j=0;j<3;j++)
{
C[i][j]=0;
for(k=0;k<3;k++)
{
C[i][j]= C[i][j]+A[i][k]*B[k][j];
}
}
}
printf(Elements of matrix C=AxB:\n);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(%d ,C[i][j]);
}
printf(\n);
}
getch( );
return 0;
}

Program #10: Write a program in C to multiply two matrices of size nxn and print the result.
Ans.
#include<stdio.h>
#include<conio.h>
int main( )
{
int A[10][10], B[10][10], C[10][10];
int i,j,k,r1,c1,r2,c2;
clrscr( );
printf(Enter size of matrix A (rows & columns:\n);
scanf(%d%d,&r1,&c1);
printf(Enter size of matrix B (rows & columns:\n);
scanf(%d%d,&r2,&c2);
if(c1!=r2)
{
printf(Matrix multiplication not possible.);
getch();
return 1;
}
printf(Enter elements of matrix A:\n);
for(i=0;i<r1;i++)
Computer Department, Jamia Polytechnic (0366)

14

3 Arrays and Strings

PIC-17212

{
for(j=0;j<c1;j++)
{
scanf(%d,&A[i][j]);
}
}
printf(Enter elements of matrix B:\n);
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf(%d,&B[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
C[i][j]=0;
for(k=0;k<c1;k++)
{
C[i][j]= C[i][j]+A[i][k]*B[k][j];
}
}
}
printf(Elements of matrix C=AxB:\n);
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf(%d ,C[i][j]);
}
printf(\n);
}
getch( );
return 0;
}

Strings:
String is a collection of characters. In C language character array is called string. When we
write a word or sentence, it is treated as string. A string constant is one dimensional character array
terminated by a null (\0) character.

Computer Department, Jamia Polytechnic (0366)

15

3 Arrays and Strings

PIC-17212

String declaration:
The general form to declare a string variable is as follows:
char array_name[size];
e.g.

char sname[30];
char address[50];
char dept_name[20];

String Initialization:
Strings can be initialized in two ways as follows:
1) char array_name[size]=string value;
e.g.
char str[20]=Hello World;
2) char

array_name[size]={comma separated list of characters terminated by null};

e.g.
char str[20]={H,e,l,l,o, , w,o,r,l,d,\0,};
In the first form, there is no need to use null character in last. C automatically inserts the
null character.

Program to print string:


1) This program prints one character of string at a time.
#include<stdio.h>
#include<conio.h>
void main( )
{
char str[ ]=Programming in C;
int i;
clrscr( );
for(i=0;i<16;i++)
{
printf(%c,str[i]);
}
getch( );
}
2) This program makes use of %s to print the string.
#include<stdio.h>
#include<conio.h>
void main( )
{
char str[ ]=Programming in C;
Computer Department, Jamia Polytechnic (0366)

16

3 Arrays and Strings

PIC-17212

int i;
clrscr( );
printf(%s,str);
getch( );
}
Accepting string from user:
Strings can be read from user in many ways. One character of a string can be read at a time
using scanf( ) or getch( ) functions, or the whole string can be read from user using scanf( )or gets( )
functions.

Program #11: Write a program in C to accept string from user and print it.
Ans.
#include<stdio.h>
#include<conio.h>
void main( )
{
char name[15];
clrscr( );
printf(Enter name : );
scanf(%s,name);
//Note:
printf(\You entered : %s,name);
getch( );
}

& sign is not used.

Program #12: Write a program in C to calculate length of string.


Ans.
#include<stdio.h>
#include<conio.h>
void main( )
{
char str[20];
int len=0;
clrscr( );
printf(Enter string : );
scanf(%s,str);
while(str[len]!=NULL)
{
len++;
}
printf(\nString length=%d,len);
getch( );
Computer Department, Jamia Polytechnic (0366)

17

3 Arrays and Strings

PIC-17212

Program #13: Write a program in C to print reverse of string.


Ans.
#include<stdio.h>
#include<conio.h>
void main( )
{
char s[20];
int i=0;
int length=0;
clrscr( );
printf(Enter string : );
scanf(%s,s);
while(s[length]!=NULL)
{
length++;
}
printf(The reverse of string is : );
for(i=length-1;i>=0;i--)
{
printf(%c,s[i]);
}
getch( );
}

gets( ) function:
If string contains spaces then it cannot be fully read by using scanf( ) function. Because when
space is encountered, scanf( ) function assumes that the value after space is for next variable.
Therefore in order to read strings with spaces gets() function can be used. Its general form is:
gets(string_variable);
e.g.
char my_str[20];
gets(my_str);

String related library functions:


Following functions can be used to manipulate strings:
1) strlen( ):

Gives length of string

2) strcpy( ):

Copies one string into another

Computer Department, Jamia Polytechnic (0366)

18

3 Arrays and Strings

3) strcmp( ):

Compares two strings

4) strcat( ):

Concatenates (joins) two strings

PIC-17212

Above functions are present in header file string.h. Therefore if you want to use these
functions string.h must be included in the program.

1) strlen( ):
This function returns length of string i.e. how many characters are there in a string. Its
general form is
strlen(string);
e.g.
int length;
char str[20]=graphics;
length=strlen(str);
After executing above block of code length variable will get a value 8 which is equal to no. of
characters in the string.

2) strcpy( ):
This function copies one string into another. Its general form is:
strcpy(str1,str2);
Here str1 & str2 are two strings. str2 will be copied into str1.
e.g.
char s1[20];
char s2[ ]=microprocessor;
strcpy(s1,s2);
printf(%s, s1);
The output will be microprocessor because s2 is copied in s1.

3) strcmp( ):
This function compares two strings. The comparision is based on ASSCII value of characters.
Its general form is:
strcmp(str1,str2 );

Computer Department, Jamia Polytechnic (0366)

19

3 Arrays and Strings

PIC-17212

str1 & str2 are two strings. If the two strings are equal, the function will return 0 (zero). If str1 is less
than str2, a value less than zero (i.e. negative value) is returned. If str1 is greater than str2, a value
greater than zero (i.e. positive value) is returned by the function.
4) strcat( ):
This function concatenates or joins two strings. Its general form is:
strcat(str1,str2);
str1 & str2 are two strings. str2 will be joined with str1. The length of str1 must be greater than or
equal to the number of characters present in str1and str2.

Program #14: Write a program in C to print string length using strlen( ) function..
Ans.
#include<stdio.h>
#include<conio.h>
#include<string.h> //include string.h header file
void main( )
{
char arr[25];
int len=0;
clrscr( );
printf(Enter string: );
scanf(%s,arr);
len=strlen(arr);
printf(Length of string is : %d,len);
getch( );
}

Program #15: Write a program in C to copy one string into another by using strcpy( ) function..
Ans.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main( )
{
char s1[20], s2[20];
clrscr( );
printf(Enter string 1: );
gets(s1);
Computer Department, Jamia Polytechnic (0366)

20

3 Arrays and Strings

PIC-17212

strcpy(s2,s1);
printf(String 2 is : %s,s2);
getch( );
}

Program #16: Write a program in C to compare two strings.


Ans.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main( )
{
char str1[20], str2[20];
int compare;
clrscr( );
printf(Enter string 1: );
scanf(%s,str1);
printf(Enter string 2: );
scanf(%s,str2);
compare=strcmp(str1,str2);
if(compare==0)
printf(Strings are equal.);
else
if(compare<0)
printf(String1 is smaller.);
else
if(compare>0)
printf(String1 is greater.);
getch( );
}

Program #17: Write a program in C to concatenate two strings.


Ans.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main( )
{
char str1[25], str2[10];
clrscr( );
printf(Enter first string : );
scanf(%s,str1);
Computer Department, Jamia Polytechnic (0366)

21

3 Arrays and Strings

PIC-17212

printf(Enter second string : );


scanf(%s,str2);
strcat(str1,str2);
printf(String 1 after concatenation : %s,str1);
getch( );
}
End of Chapter 3

Computer Department, Jamia Polytechnic (0366)

22

Das könnte Ihnen auch gefallen