Array and String in C
Array and String in C
- Prof. S. S. Lamkane
Definition:
“An array is a collection of elements of the same data type. An array is also called
as subscript variable.”
Declaration of array:
Like any other normal variable, an array has to be declaring before it is used in a
program. The general form of array declaration is:
Datatype Array_name[size];
Here,
Size indicates the maximum number of elements that can be stored in an array.
Example:
int a[10];
Declares the ‘a’ as array variable of type integer & which is able to store 10 integer
numbers. When array is declared, continuous memory is allocated for the array elements.
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
1000 1002 1004 1006 1008 1010 1012 1014 1016 1018
Assume that the starting address of array is 1000. Every integer requires 2 bytes
memory. So next address is 1002, 1004 & so on.
Initialization of an Array:
After the declaration of array, its element must be initialized. Otherwise, they will
contain ‘garbage’ value. An array can be initialized at either of the following ways.
1. At compile time
2. At run time.
We can initialize the elements of array in the same way as the ordinary variable
when they are declared. Compile time initialization is also known as Static Binding or
early binding. The general form of initialization of array is:
1
Example: 1. float total [5]={1.5, 15.70, -10.0};
It will initialize the first three elements to 1.5, 15.70, -10.0 & the remaining two elements to
zero.
Here, size of array is omitted. In such case the compiler allocates enough space for
initializes elements.
Declares the name to be an array of five characters, initialized with string “John” & ending
with the null character back slash zero ‘\0’.
It is illegal in c, because if we have more initialization than the declared size, the compiler
will produce an error.
An array can be explicitly initialized at the run time. This type of initialization is
usually applicable in large array. Run time initialization is also known as dynamic binding
or late binding. Consider the following c code which is used to initialize array as run time.
int a[10];
for( i=0; i<10; i++ )
{
scanf(“%d”, &a[i]);
}
With initialization, array elements with the values entered through the keyboard.
Sample programs:
1. Write a c program to accept ‘n’ numbers. Store this numbers in an array & display
only even numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int no[50], n, i;
clrscr();
printf(“\n Enter how many numbers: ”);
scanf(“%d”, &n);
printf(“\n Enter the numbers: ”);
for(i=0;i<n;i++)
{
scanf(“%d”,&no[i]);
printf(“\n The even numbers are: ”);
for(i=0;i<n;i++)
{
2
if(no[i]%2==0)
printf(“\t %d ”, no[i]);
}
}
getch();
}
O/P
Enter how many numbers : 5
Enter the numbers : 6 5 8 10 9
The Even Numbers are : 6 8 10
#include<stdio.h>
#include<conio.h>
void main()
{
int no, Bin[16], i;
clrscr();
for(i=0;i<16;i++)
{
Bin[i]=0;
printf(“\n Enter the Decimal Number: ”);
scanf(“%d”, &no);
i=0;
while(no>0)
{
Bin[i]=no%2;
i++;
no=no/2;
}
}
printf(“\n The Binary equivalent is: ”);
for(i=15;i>=0;i--)
{
printf(“\n %d”, Bin[i]);
}
getch();
O/P
Enter the Decimal Number: 15
The Binary equivalent is : 0000000000001111
3
Two Dimensional Array:
Two dimensional array has 2 subscripts. One indicates the row & other indicates the
column. i.e. two dimensional array is used to store elements in the form of table. Tabular
representation of array is also known as matrix.
Here, ‘a’ is declared as a two dimensional array having 3 rows & 2 columns. i.e. used to
store 6 elements.
Like a one dimensional array, two dimensional array can be initialized in two ways.
Col 0 col 1 col 2
a. int a[3][2]= {
{ 1, 2 },
{ 5, 3 },
{ 4, 2 }
};
b. int a[3][2]={ 1, 2, 5, 3, 4, 2 };
both represented logically as,-
Col 0 Col 1
Row 0 1 2
Row 1 5 3
Row 2 4 2
int a[3][2];
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
scanf(“%d”, &a[i][j]);
}
}
4
Here, two for loops are used to initialize two dimensional array. First for loop
represents rows & second for loop represents column.
Like a one dimensional array, continuous memory is allocated for two dimensional array as
for above example:
|------------Row1----------- |-------------Row2------------|------------Row3-----------|
1 2 5 3 4 2
1000 1002 1004 1006 1008 1010
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int m[5][5], trans[5][5], r, c, i, j;
clrscr();
printf(“\n How many rows & columns in the matrix: ”);
scanf(“%d%d”, &r, &c);
printf(“\n Enter the array elements: ”);
for(i=0;i<r;i++)
{
for(j=0;j<r;j++)
{
scanf(“%d”, &m[i][j]);
trans[j][i]=m[i][j];
}
}
printf(“\n The transpose matrix is: ”);
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
printf(“%d \t”,trans[i][j]);
}
}
getch();
}
O/P
How many rows & columns in the matrix: 3 3
Enter the array elements: 1 2 3
4 5 6
7 8 9
5
The transpose matrix is:
1 4 7
2 5 8
3 6 9
String:
String Operations:
char StringName[size];
For example:
char name[20];
char city[25];
What is the string? Explain the syntax of initialization, declaration & example.
Initialization:
Like numeric array, character array (i.e. string) may be initialized when they are
declared. Character array can be initialized in either of the following two forms.
char city[10]=”phaltan”;
char city[10]={ ’p’, ’h’, ’a’, ’l’, ’t’, ’a’, ’n’, ’\0’ };
The input function scanf() can be used with %s format specification to read in a
string of character.
For example:
char city[10];
Scanf(“%s”,city);
6
The problem with the scanf() function is that, it is terminates it’s input on the first
white space it finds. Therefore, if the following line of text is typed in at the terminal,
New York
Then only the string “New” will be read into the array city, since the blank space after the
word “New” will terminate the string reading.
Another library function gets() is used to read input string from terminal including
white space. The general form of gets() function is,
gets(str);
Here, str is a string variable. It read characters into str from the keyboard until a
new line character is encountered & then appends null character to the string.
The output function printf() is used with %s format to print strings to the screen.
Another & more convenient way of printing string values is to use the function
puts() declared in the header file <stdio.h>.following are the syntax of puts() function.
puts(str);
7
1. strcat() function:
The strcat() function jobs two strings together. It takes the following form:
strcat(string1, string2);
string1 & string2 are character array when the function strcat is executed string2 is
appended to string1.
For example:
Part1 V E R Y \0
Part2 G O O D \0
Execution of statement:
strcat(part1, part2);
with result:
Part1 = V E R Y G O O D \0
Part2= G O O D \0
We must make sure that the size of string1 is larger enough to accommodate
the final string.
2. strcmp() function:
The strcmp() function compares two string.
If they are not equal, it returns numeric difference between the first non-matching
characters in the string. It takes following form.
strcmp(string1, string2);
string1 & string 2 are string variables or string constants.
For example:
strcmp(“their”, “there”);
will return a value -9 which is the numeric difference between ASCII “i" & ASCII ”r”.
strcmp(“RAM”, “RAM”);
will return a value 0. Because above strings are equal.
3. strcpy() function:
The strcpy() function copies one string into another string.
It takes the following form:
strcpy(string1, sting2);
here, contents of string2 is copied into string1.
For example:
strcpy(city, “phaltan”);
will assign the string “phaltan” to the string variable city.
8
4. strlen() function:
This function counts & returns the number of characters in a string.
It takes following form:
n=strlen(string);
where, n is an integer variable, which stores the value of the length of a string
returned by strlen() function.
5. strrev() function:
This function is used to reverse the string & returns the reversed string.
It takes following form:
s=strrev(string1);
where, s is a string variable that stores reverse string of string1.
For example:
string1=”Phaltan”;
s=strrev(string1);
Now, s contains “natlahp”.
Program:
s1, s2 & s3 are three string variables. Write a program to read two string constant
into s1 & s2 & compare whether they are equal or not? If they are not equal join
them together. Then copy the contents of s1 to the variable s3. Then reverse the
string s1 & check whether it is palindrome or not? Finally print the contents of all
the 3 variables & there lengths.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[20], s2[20], s3[20];
int x, l1, l2, l3;
clrscr();
printf(“\n Enter two strings: ”);
scanf(“%s%s”, s1, s2);
x=strcmp(s1, s2); /* compare string */
if(x==0)
{
Printf(“\n String s1 & s2 are equal ”);
}
else
{
printf(“\n Strings are not equal ”);
9
}
strcpy(s3, s1);
x=strcmp(s2, strrev(s2));
if(x==0)
printf(“\n String s2 is palindrome “);
else
printf(“\n String s2 is not palindrome “);
l1 = strlen(s1);
l2=strlen(s2);
l3=strlen(s3);
printf(“\n s1 = %S \t length = %d “, s1, l1);
printf(“\n s2 = %S \t length = %d “, s2, l2);
printf(“\n s3 = %S \t length = %d “, s3, l3);
getch( );
}
10