You are on page 1of 40

Chapter – 4 Arrays and

Strings
 Topics:-

• Concept of Array
• One and Two Dimensional Arrays
• Declaration and Initialization of Arrays
• String
• String Storage
• Built-in-string functions
 What is Array?
• An array is a fixed-size sequential collection of elements of same data types
that share a common name.
• It is simply a group of data types.
• An array is a derived data type.
• An array is used to represent a list of numbers , or a list of names.

 Example of Arrays:

1.List of employees in an organization.


2.Test scores of a class of students.
3.List of customers and their telephone numbers.
4.List of students in the college.
• For Example, to represent 100 students in college , can be written as
student [100]
• Here student is a array name and [100] is called index or subscript.
 Types of Arrays
1. One-dimensional arrays
2. Two-dimensional arrays
3. Multidimensional arrays
 One-dimensional Arrays:
• A variable which represent the list of items using only one index (subscript) is
called one-dimensional array.
• For Example, if we want to represent a set of five numbers say
(35,40,20,57,19), by an array variable number, then number is declared as
follows
int number [5] ;

• and the computer store these numbers as shown below :


number [0]
number [1]
number [2]
number [3]
number [4]
• The values can be assigned to the array as follows :
number [0] = 35;
number [1] = 40;
number [2] = 20;
number [3] = 57;
number [4] = 19;
 Declaration of One-dimensional Arrays :
• The general form of array declaration is :
type array-name[size];
• Here the type specifies the data type of elements contained in the array,
such as int, float, or char.
• And the size indicates the maximum numbers of elements that can be
stored inside the array.
• The size should be either a numeric constant or a symbolic constant.
For example :

int group [10] ;


• here int is type, group is a variable name , 10 is a size of array and the
subscripts (index) is start from 0 to 9.
 Initialization of One-dimensional Arrays :
• An array can be stored in following stages :
1. At compile time
2. At run time

3. Compile time initialization :


• In compile time initialization, the array is initialized when they are declared.
• The general form of initialization of array is :
type array-name[size] = { list of values };
• The list of values are separated by commas.
Example :
int number[3] = {4,5,9};
• Here array number of size 3 and will assign 4 to first element(number[0]), 5
is assign with second element(number[1]) and 9 is assign with third
element(number[2]).
• If the number of values in the list is less than the number of elements, then
only that many elements will be initialized. The remaining elements will be
set to zero automatically.
Example :
int number[ ] = {1,2,3,4};
• The character array can be initialized as follows :
char name[ ] = {‘j’,’o’,’h’,’n’,’\0’};
• The character array can also be initialized as follows :
char name[ ] = “john”;
2. Run time initialization :
• In run time initialization, the array is explicitly initialize at run time.
• This concept generally used for initializing large arrays.
Example:
for(i=0; i < 100; i++)
{
if( i < 50)
sum[i] = 0.0;
else
sum[i] = 1.0;
}
• Here first 50 elements of the array sum are initialized to 0 and the remaining 50
elements are initialized to 1 at run time.
 Two-dimensional Arrays

• A variable which represent the list of items using two index (subscript) is called
two-dimensional array.

• In Two dimensional arrays, the data is stored in rows and columns format.

• For example:
int table[2][3];
Declaration of Two-dimensional Arrays :
• The general form of two dimensional array declaration is :

type array-name[row_size][column_size];

• Here the type specifies the data type of elements contained in the array,
such as int, float, or char.
• The size should be either a numeric constant or a symbolic constant.
Initialization of Two-dimensional Arrays :
• The general form of initializing two-dimensional array is :
type array-name[row_size][column_size] = {list of values};

Example :
int table[2][3] = {0,0,0,1,1,1};
• Here the elements of first row initializes to zero and the elements of
second row initializes to one.
• This above statement can be written as :
int table[2][3] = {{0,0,0}, {1,1,1}};
• In two-dimensional array the row_size can be omitted.

Example :
int table[ ][3] = {{0,0,0}, {1,1,1}};
• If the values are missing in an initializer, they are automatically set to zero.
Example :
int table[2][3] = {1,1,2};
• Here first row initialize to 1,1 and 2, and second row initialize to 0,0 and 0
automatically.
 Memory Layout of Two-dimensional array :
• In Two dimensional arrays, the data is stored in rows and columns format.
• For example:
int table[2][3] = {4,9,6,1,7,3};

• The memory layout of above example :


table[0][0] = 4;
table[0][1] = 9 table[0][2] = 6;
table[1][0] = 1;
table[1][1] = 7;
table[1][2] = 3;
 Multi-dimensional Arrays
• A variable which represent the list of items using more than two index
(subscript) is called multi-dimensional array.

• The general form of multi dimensional array is :


type array-name[s2][s2][s3]…….[sn];
• Where S is the size. Some examples are :
int survey[3][5][6];
float table[5][4][5][3];
• Here survey is a three-dimensional array and it contain 90 (3*5*6) integer
type elements. And table is a four-dimensional array and it contain 300
floating type elements.
 Applications of arrays
• Using pointers for accessing arrays.
• Passing arrays as function parameters.
• Arrays as members of structures.
• Using structure type data as array elements.
• Arrays as dynamic data structures.
• Manipulating character arrays and strings.
 Example of Matrix
Strings
 What is string?
• A string is a sequence of characters that treated as a single data item.
• The string is defined between double quotation mark.

Example:
“ i teach C language”
 List of strings operation

• The operations performed on strings are follows:


1. Reading and Writing strings
2. Combining string together
3. Comparing two strings
4. Copying one string to another
 Declare and initialize string variables
• C does not support string as data type, so to declare string variable character
array is used.
• Declaration of String:
char string_name[size];
• Here the size determines the number of character in string_name.
• Example :
char city[10];
• When the compiler assigns a character string to character array, it automatically
supplies null character(‘\0’) at the end of string. Therefore the size should be
equal to maximum number of characters in string plus one.
 Declare and initialize string variables
• Initialization of string:
char city[9] = ’’NEW YORK”;
char city[9] = {‘N’,’E’,’W’,’ ’,’Y’,’O’,’R’,’K’,’\0’};
char city[]=”NEW YORK”;

• We can also declare the size larger than the string size in the intializer.
char city[20]=”NEW YORK”;

• We cannot declare the size smaller than the string size in the intializer.
char city[5]=”NEW YORK”;
this will result in a compile time error.

• We cannot separate the initialization from declaration.


char city[9];
city = “NEW YORK”;
it is not allowed.
 Reading strings from terminal

 scanf() function

• Input function scanf is used with %s format specification to read string.


Example : char city[9];
scanf(“%s”,city);
• The problem with scan function is that it terminates reading on the first white
space it finds. A white space includes blanks,tans,carriage returns and new
lines.
• Example : If the NEW YORK is input then only “NEW” will be read, because the
blank space after the word NEW will terminate the reading of string.
• We can also specify the field width using the form %ws in the scanf statement
for reading a specified number of characters from the input string.
Example :
char city[8];
scanf(“%3s”,city);

• The input string MEHSANA will stored as:

M E H \0 ? ? ? ? ?

• here ? indicates garbage value.


 getchar and gets functions :
getchar()

• getchar is the function to read a single character from the terminal.


• The reading is terminated when the new line character (‘\n’) is entered and
the null character is then inserted at the end of the string.
char ch;
ch = getchar( );
• getchar function has no parameters
 gets()

• gets is the function to read characters into string from the terminal.
• gets is the library function and available in <stdio.h> header file.
• The gets function called as under :
gets(str);
• where str is the string variable.
• The reading is terminated when the new line character (‘\n’) is encountered
and the null character is then inserted at the end of the string.
• gets function has one parameter.
 Writing strings to screen

printf function

• Output function printf is used with %s format specification to write string.


Example :
printf(“%s”, name);
 putchar and puts functions :

 putchar
• putchar is the function to print the values of character variables.
• It takes the following form :
char ch = ‘A’ ;
putchar (ch) ;
• The function putchar has one parameter.
• We can use this function repeatedly to print a string of characters stored in
array using a loop.
Example :
char name = “VINAYAK INFOTECH”;
for (i=0; i<=5; i++)
{
putchar(name[i]);
}
 puts functions :
• puts is the function to print the values of string variables.
• puts is the library function and available in <stdio.h> header file.
• The puts function called as under :
puts(str);
• where str is the string variable.
• puts function has one parameter.
Example :
char line[80];
gets(line);
puts(line);
• This example read a line of text from the keyboard and displays it on the
screen.
 String Handling Functions or Built-in String
Functions or String Manipulation Functions
Functions Action

strcat() concatenates(combine) two strings


strcmp() compares two strings
strcpy() copies one string over another
strlen() finds the length of a string
1. strcat( ) Function
• It takes the following form :
strcat(string1, string2);
• where string1 and string2 are character arrays.
• Here the strcat function joint string2 with string1.
• The strcat function remove the null character at the end of string1 and
placing string2 from there. The string2 remains unchanged.

• Example :
String2= B Y E \0
Sting1= G O O D \0
after execution of the statement strcat(string1, string2); will result in:

String 1= G O O D B Y E \0
String2= B Y E \0
• C also permits nesting of strcat function.

Example : strcat(strcat(string1,string2), string3);

• The strncat function takes the form :


strncat(string1, string2, n);
• Where string1, string2 are character arrays and n is integer constant.
• Here the strncat function concatenate only the left most n characters of
string2 to the end of string1.
2. strcmp( ) function :-
• It takes following form :
strcmp(string1, string2);
• Where string1 and string2 are character arrays.
• Here the strcmp function compares string1 with string2.
• If both strings are equal then this function return 0.
• If both strings are not equal then it return the numeric difference between
first non matching characters in the strings.

Example:
strcmp(“there”, “there”);
will return 0.
strcmp(“their”, “there”);
• will return the value -9 which is the numeric difference between ASCII “i”
and ASCII “r”.

• Note : ASCII of a = 97, z = 122, A = 65, Z = 90


• It takes the form :
strncmp(string1, string2, n);
• Where string1, string2 are character arrays and n is integer constant.
• Here it compares the left most n characters of string1 to string2 and
returns.
• 0 if both strings are equal.
• negative number, if string1 is less than string2
• positive number, if string1 is greater than string2.
3. strcpy( ) function :-

• It takes following form :


strcpy(string1, string2);
• Where string1 and string2 are character arrays.
• Here content of string2 will copied into string1.
Example :
string1 = ”vinayak”;
string2 = ”infotech”;
• After execution this statement,
strcpy(string1,string2);
string1 = “infotech”;
string2 = “infotech”;
Example : 
• string1 = “VINAYAK”;
• string2 = “INFOTECH”; 
strcpy(string1,string2,4);
will return
• string1 = “INFO”;
• string2 = “INFOTECH”;
4. strlen( ) function :-
• It takes the form :
n = strlen(string1);
• where n is integer variable and string1 is a character array.
• Here the strlen function will return the number of characters in a string1.

Example :
• After execution this statement,
n = strlen(“VINAYAK INFOTECH”);
n = 16
• The strncpy function takes the form : 
strncpy(string1, string2, n);
• Where string1, string2 are character arrays and n is integer constant.
• Here the strncpy function copies only the left most n characters of
string2 to string1.
 Find length of string using strlen( ) function

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int str1;
char str;
clrscr();
printf("\nEnter the string: ");
gets(str);
str1=strlen(str);
printf("\nThe length of the string is %d.",strlength);
getch();
}

OUTPUT:
Enter the string: hello world
The length of the string is 11
 Write a program to join two strings
#include <stdio.h>
#include <string.h>
void main()
{
char a[100], b[100];
clrscr();
printf("Enter the first string:\n");
scanf(“%s”,&a);
printf("Enter the second string:\n");
scanf(“%s”,&b);
strcat(a,b);
printf("String obtained on concatenation is %s\n",a);
getch();
}
OUTPUT:
Enter the first string:
Hello
Enter the second string:
World
String obtained on concatenation is World
 Write a program convert character into ToggLe character

#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf("Enter any character : ");
scanf("%ch", &ch);
if(ch>='A' &&ch<='Z')
{
ch=ch+32;
}
else if(ch>'a' &&ch<='z')
{
ch=ch-32;
}
printf("Convert case of character : %c",ch);
getch();
}
OUTPUT:

Enter any character : D


Convert case of character : d
Enter any character : d
Convert case of character : D
 Write a program to copy one string to another string

#include<stdio.h>
#include<conio.h>
void main()
{
char s1[100],s2[100];
int i;
printf("\nEnter the string :");
gets(s1);
i=0;
while(s1[i]!=' ')
{
s2[i]=s1[i];
i++;
}
s2[i]=“'';
printf("\nCopied String is %s ",s2);
getch();
}
OUTPUT:
Enter the string : hello
Copied String is hello
THANK YOU

You might also like