0% found this document useful (0 votes)
3 views16 pages

Array Nonnumeric

Uploaded by

lokeshdevathati
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

Array Nonnumeric

Uploaded by

lokeshdevathati
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction

Variables of type char can hold only a single character, so they have limited usefulness. We also
need a way to store strings, which are sequences of characters. A person's name and address are
examples of strings. Although there is no special data type for strings, C handles this type of
information with arrays of characters.

A string is an array of characters terminated by a NULL character

e.g., “AMRITA” is a string. Whenever a string is stored in memory, the compiler automatically
inserts a NULL character (\0) at the end of string. This NULL character is a string terminator,
i.e., it denotes the end of string. This NULL character is the first ASCII character which has a
value of zero.

The string that can hold an array of characters can be declared with the following syntax:

<Storage_class> char <array_name>[size];

In this syntax:
<Storage_class> is any one of auto, extern, static or register, an optional one.
char is the data type that determines the type of elements in the array are as characters.
<array_name> is any valid identifier.
size, a positive integer constant or integer constant expression, determines the number of
characters in the string.
Ex: char name[20]; //can hold a string of 19 characters; one location is for NULL
char a [35]; //can hold a string of 34 characters; one location is for NULL
When we declare a character array, a memory location should be reserved for the NULL
character.
Initializing a string
This one-dimensional array of characters can be initialized by using assignment operator as
follows:
char a[13]= {‘A’,’M,’R’,’I’,’T’,‘A’};
is equivalent to
char a[13]=”AMRITA”;
In both of the cases, the NULL character can be appended to the string automatically. If the length
of the string is exceeded than the specified size in square brackets, then the compiler gives the
error. This error can be rectified with the help of the following initialization statement that
automatically allocates memory based on the number of characters in that string:
char a[]={‘A’,’M,’R’,’I’,’T’,‘A’,\0’} ;
is equivalent to
char a[]=”AMRITA”;

If I can say
char a[]=”AMRITA”;
Why can’t I say
char a[13];
a=”AMRITA”;
As we know that strings are arrays. As we can’t assign arrays directly, strings can’t be assigned
directly. Instead, we can use strcpy() like this:
strcpy(a,”AMRITA”);

This is how static initialization takes place to assign string to character [Link] let us look into
how dynamic initialization is done.
Reading and printing a string
There are 3 ways to read a string using keyboard:
By using scanf() function (formatted input function)
By using gets() function (unformatted input function)
By using getchar() repeatedly (with the help of loops)
There are 3 ways to print a string onto the monitor:
By using printf() function (formatted output function)
By using puts() function (unformatted output function)
By using putchar() repeatedly (with the help of loops)
By using the scanf() and printf() functions
The scanf() function with the conversion character %s can be used to read a string using
keyboard. The printf() function with the same conversion character can be used to print a string
onto monitor.
E.g.,
#include<stdio.h>
int main()
{ char str[25];
printf("\n Enter your name:");
scanf("%s",str);
printf("\n Your Name=%s",str);
}
Usually, scanf() statement expects an address of the variable. Because the name of the array itself
is an address of it, we don’t use an ampersand (&) before the name of the string. The %s option
uses a blank space as a delimiter and hence it considers the character separated by blank space
as two strings.
The disadvantage of scanf() function is that there is no way to read a multi-word string
(i.e., string with spaces) into a single variable. The scanf() function terminates the input string
when it finds blank space in input string. E.g., if the input for scanf() function is “AMRITA
College”, the string variable str holds only the string AMRITA
To read a multi-word, we can use the following form of scanf():

#include<stdio.h>
int main()
{
char str[25];
printf("\n Enter your name:");
scanf("%[^\n]s",str); //[^\n] means read set of characters except new line character
printf("\n Your Name=%s",str);
}
By using the gets() and puts() functions
The gets() function can also be used to read a string using keyboard. It reads and assigns the
input string to the character array until the ENTER key is pressed. The input string can consist
of blank spaces and tabs as part of it. The puts() function is used to print that string which was
read by using gets() or scanf().
Ex:
#include<stdio.h>
int main()
{
char str[25];
printf("\n Enter your name:");
gets(str);
puts(str);
}
The string can be entered until the ENTER key is pressed and can be stored in string variable.
Now, suppose that we input the string “Amrita college”. Then the variable str holds the whole
string “Amrita college”.
The disadvantage of gets() function is that it can be used to read only one string at a
time. E.g., the following gets() statement is invalid:
gets(str1,str2); //invalid
The gets() function expects only one string as an argument. If more than one string is input to this
function, the compiler gives an error “too many arguments to function gets”
However, a scanf() function can be used to read more than one string at a time.
E.g., scanf(“%s%s%s”,str1,str2,str3); can be used to read 3 strings.
By using a loop
A string can be read character by character by using a for loop (or any loop). Each time the loop
runs, the getchar() function takes the character from the keyboard and that character will be
assigned to the one of character array’s locations. The loop should be stopped when the new line
character is encountered or any other delimiter specified. When the repetition has stopped, the
last location should occupy the NULL character for denoting the end of string.
For printing the string using a loop, the iterative process should start at 0th location and should
terminate before the NULL character. In each iteration, the character should be printed with the
help of putchar() or printf() with %c conversion specifier.
#include<stdio.h>
int main()
{ char str1[23],ch;
int i;
printf("\n Enter any string:");
for(i=0;(ch=getchar())!='\n';i++)
str1[i]=ch;
str1[i]='\0';
for(i=0;str1[i]!=’\0’;i++)
putchar(str1[i]);
}

Some examples::
/*A program to check whether given string is palindrome or not*/
#include<stdio.h>
int main()
{
char str[30];
int len=0,flag=0,i,j;
printf("\n Enter a string:");
gets(str);
for(i=0;str[i]!='\0';i++)
len++;
for(i=0,j=len-1;i<j;i++,j--)
if(str[i]!=str[j])
{
flag=1; OUTPUT:
break; Enter a string:madam
}
if(flag==0) Given string is palindrome
printf("\n Given string is palindrome");
else
printf("\n Given string is not a palindrome");
}

/*Program to count [Link] vowels and consonants in a line of text*/


#include<stdio.h>
#include<ctype.h>
int main()
{
char text[50];
int nv=0,nc=0,i;
printf("\n Enter a line of text:");
gets(text);
for(i=0;text[i]!='\0';i++)
{
text[i]=tolower(text[i]);
if(text[i]=='a'||text[i]=='e'||text[i]=='o'||text[i]=='i'||text[i]=='u'
)
nv++; OUTPUT:
else Enter a line of text:Engineering
nc++; [Link] vowels=5
} [Link] consonants=6
printf("\n [Link] vowels=%d",nv);
printf("\n [Link] consonants=%d",nc);
}

/*Program to convert the case of text*/

#include<stdio.h>
int main()
{
char text[50];
int i;
printf("\n Enter a line of text:");
gets(text);
for(i=0;text[i]!='\0';i++)
{
if(text[i]>='A' && text[i]<='Z') OUTPUT:
text[i]=text[i]+32; Enter a line of text:AmRiTa
else
text[i]=text[i]-32;
}
converted text=aMrItA
printf(“\n converted text=%s”,text);
}

/*Program to count [Link] lines, words and characters in multiple lines of


text*/
#include<stdio.h>
int main()
{
char text[150],ch;
int nl=0,nw=0,nc=0,i;
printf("\n Enter multiple lines of text (end with #):");
for(i=0;(ch=getchar())!='#';i++)
{
nc++;
if(ch==' ')
nw++;
else if(ch=='\n')
{
nw++;
nl++; OUTPUT:
} Enter multiple lines of text (end with #):AMRITA
else ; college
} amaravathi#
nl++;
nw++; [Link] lines=3
printf("\n [Link] lines=%d",nl); [Link] words=3
printf("\n [Link] words=%d",nw); [Link] characters=25
printf("\n [Link] characters=%d",nc);
}
String-handling functions
C supports a number of string handling functions. All of these built-in functions are aimed at
performing various operations on strings. All of these built-in functions are defined in the header
file string.h. Therefore, whenever we use one of these string handling functions, we should add
the preprocessor statement #include<string.h> to our program. Some of the string- handling
functions are:

strlen() strrev() strcpy() strcat() strcmp()


strlwr() strupr() strncpy() strncat() strncmp()

1. strlen() function: This function is used to find the length of the string excluding the NULL
character. In other words, this function is used to count the number of characters in a string. Its
syntax is as follows:

int strlen(string1);

where string1 is the one-dimensional array of characters.


This function returns an integer value that is the count of characters in the string. E.g.,
string1 contains “AMRITA college” then strlen(string1) function returns the value 14.

/* A program to calculate length of string by using strlen()


function*/
#include<stdio.h>
#include<string.h>
int main()
{
char string1[50];
int length;
printf("\n Enter any string:");
OUTPUT:
Enter any string:AMRITA college
gets(string1);
length=strlen(string1); The length of string=14
printf("\n The length of string=%d",length);
}
/* A program to calculate length of string without using strlen()
function*/
#include<stdio.h>
int main()
{
char string[50];
int length,i;
printf("\n Enter any string:\n"); OUTPUT:
gets(string); Enter any string:AMRITA college
for(i=0;string[i]!='\0';i++)
length++; The length of string=14
printf("\n The length of string=%d",length);
}

2. strrev() function: This function is used to find the reversed string of a given string. Its syntax is
as follows:
strrev(string1);

where string1 is the one-dimensional array of characters.


This function stores the reversed string of string1 in that argument string1 only. E.g.,
string1 contains master then the same string1 contains retsam after execution of strrev() .
/* A program to reverse a string using strrev() function*/
#include<stdio.h>
#include<string.h>
int main()
{
char string1[30];
printf("\n Enter any string:");
gets(string1);
strrev(string1);
printf("\n Reversed string=%s",string1);
}
/* A program to reverse a string without using strrev() function*/
#include<stdio.h>
int main()
{
char str[30],temp;
int length=0,i,j;

printf("\n Enter any string:");


gets(str); OUTPUT:
printf("\n Original string=%s",str); Enter any string:amrita
for(i=0;str[i]!='\0';i++)
length++; Original string=amrita
for(i=0,j=length-1;i<j;i++,j--) Reversed string=atirma
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
printf("\n Reversed string=%s",str);
}

3. strcpy() function:
This function is used to copy one string to the other. Its syntax is as follows:

strcpy(string1,string2);

where string1 and string2 are one-dimensional character arrays.


This function copies the content of string2 to string1. E.g., string1 contains master and
string2 contains madam, then string1 holds madam after execution of the strcpy(string1,string2)
function.
/* A program to copy one string to another using strcpy()
function*/
#include<stdio.h>
#include<string.h>
int main()
{
char string1[30],string2[30];
printf("\n Enter first string:");
gets(string1);
printf("\n Enter second string:");
gets(string2);
strcpy(string1,string2);
printf("\n First string=%s",string1);
printf("\n Second string=%s",string2);
}

/* A program to copy one string to another without using strcpy()


function*/
#include<stdio.h>
int main()
{ char str1[30],str2[30];
int i;
printf("\n Enter first string:"); OUTPUT:
gets(str1); Enter first string:amrita
printf("\n Enter second string:");
gets(str2); Enter second string:madam

for(i=0;str2[i]!='\0';i++) First string=madam


str1[i]=str2[i]; Second string=madam
str1[i]='\0';
printf("\n First string=%s",str1);
printf("\n Second string=%s",str2);
}

This function is used to concatenate two strings. i.e., it appends one string at
the end of the specified string. Its syntax as follows:
strcat(string1,string2);

where string1 and string2 are one-dimensional character arrays.


This function joins two strings together. In other words, it adds the string2 to string1 and the
string1 contains the final concatenated string. E.g., string1 contains prog and string2 contains
ram, then string1 holds program after execution of the strcat() function.
/* A program to concatenate one string with another using
strcat() function*/
#include<stdio.h>
#include<string.h>
int main()
{
char string1[30],string2[15];
printf("\n Enter first string:");
gets(string1);
printf("\n Enter second string:");
gets(string2);
strcat(string1,string2);
printf("\n Concatenated string=%s",string1);
}

/* A program to concatenate one string with another without


using strcat() function*/
#include<stdio.h>
int main()
{ char string1[30],string2[15];
int i,j;
printf("\n Enter first string:");
gets(string1); OUTPUT:
printf("\n Enter second string:"); Enter first string:prog
gets(string2);
Enter second string:ram
for(i=0;string1[i]!='\0';i++);
Concatenated string=program
for(j=0;string2[j]!=0;j++)
string1[i+j]=string2[j];
string1[i+j]='\0';
printf("\n Concatenated string=%s",string1);
}

This function compares two strings character by character (ASCII


comparison) and returns one of three values {-1,0,1}. Its syntax is as follows:

int strcmp(string1,string2);

where string1 and string2 are one-dimensional arrays of characters.


When this function is invoked with two strings as arguments, then:
This function returns -1 or negative integer, if the ASCII value of the character of the first string is
less than that of second string;
It returns 0 (zero), if both strings are equal;
It returns 1 or a positive integer, if the ASCII value of the character of first string is greater than
that of the second string.
E.g., string1 contains master and string2 contains minds, then strcmp(string1,string2); returns a
negative value; since the ASCII value of ‘a’ is lesser than the ASCII value of ‘i’.
/* A program to compare two strings using strcmp() function*/
#include<stdio.h>
#include<string.h>
int main()
{
char string1[30],string2[15];
int x;
printf("\n Enter first string:");
gets(string1);
printf("\n Enter second string:");
gets(string2);
x=strcmp(string1,string2);
if(x==0)
printf("\n Both strings are equal");
else if(x>0)
printf("\n First string is bigger");
else
printf("\n Second string is bigger");
}
/* A program to compare two strings without using strcmp()
function*/

#include<stdio.h>

int main()
{ char str1[20],str2[20];
int x,i,c;
printf("\n Enter first string:");
scanf("%s",str1);
printf("\n Enter second string:");
scanf("%s",str2);
for(i=0;str1[i]!='\0'||str2[i]!='\0';i++)
{
if(str1[i]>str2[i])
{
c=1;
break;
}
else if(str1[i]<str2[i])
{
c=-1;
break;
}
}
if(c==0) OUTPUT:
printf("\n Both strings are equal"); Enter first string:master
else if(c>0)
printf("\n First string is bigger"); Enter second string:minds
else
printf("\n Second string is bigger"); Second string is bigger
}

This function converts all the uppercase alphabets into lowercase. Its syntax
is as follows:
strlwr(string1);

where string1 is the one-dimensional array of characters.


e.g., string1 holds AmRiTA, then strlwr() converts all the uppercase alphabets of string1
to lowercase. The string1 holds the lowercase string amrita.
/* A program to convert an uppercase string to lower case string
using strlwr() function*/
#include<stdio.h>
#include<string.h>
int main()
{
char string[30];
printf("\n Enter any string:");
scanf("%s",string);
strlwr(string);
printf("\n lower case string=%s",string);
}

/* A program to convert an uppercase string to lowercase string


without using strlwr() function*/
#include<stdio.h>
int main()
{ char str[30];
int i;
printf("\n Enter any string:");
scanf("%s",str); OUTPUT:
for(i=0;str[i]!='\0';i++) Enter any string:AmRIta
if(str[i]>='A' && str[i]<='Z') lower case string=amrita
str[i]=str[i]+32;
printf("\n lower case string=%s",str);
}

7. strupr() function: This function converts all the lowercase alphabets into uppercase. Its syntax
is as follows:
strupr(string1);
where string1 is the one-dimensional array of characters.

/* A program to convert an lowercase string to upper case string


using strupr() function*/
#include<stdio.h>
#include<string.h>
int main()
{
char string[30];
printf("\n Enter any string:");
scanf("%s",string);
strupr(string);
printf("\n lower case string=%s",string);
}

/* A program to convert an lowercase string to uppercase string


without using strupr() function*/
#include<stdio.h>
int main()
{ char str[30];
int i;
printf("\n Enter any string:");
scanf("%s",str); OUTPUT:
for(i=0;str[i]!='\0';i++) Enter any string:AMriTa
if(str[i]>='a' && str[i]<='z')
str[i]=str[i]-32; upper case string=AMRITA
printf("\n upper case string=%s",str);
}

Two-Dimensional array of characters(referred as array of strings or string of strings)


By using one-dimensional array, only one string (including spaces) is accepted and processed.
Some times, it is necessary for us to process a group of strings. In such situations, we need a two-
dimensional array. A two-dimensional array of characters is an array of one-dimensional arrays
of characters. This means that, a two-dimensional character array consists of strings (i.e., one-
dimensional arrays of characters) as its individual elements.
Declaration: Like Two-dimensional numeric arrays, Two-dimensional character arrays should be
declared before it is used. A Two-dimensional array of characters can be declared as follows:
<Storage_class> char <array_name>[row][column];
where <Storage_class> is any one of auto, extern, static or register, an optional one.
char is the data type that determines the type of elements in the array.
<array_name> is any valid identifier.
row, a positive integer, determines the number of strings in the array.
Column, a positive integer, determines the number of characters a string can hold.
Ex: char a[5][10]; //can hold 5 input strings, each input string should be of length 9 chars.

Initialization: Like One-dimensional character array, a Two-dimensional character array can


also be initialized with the help of assignment operator as follows:
char names[3][10]={ {‘R’,’a’,’j’,’k’,’u’,’m’,’a’,’r’},
{‘S’,’a’,’n’,’j’,’a’,’n’,’a’},
{‘P’,’o’,’o’,’j’,’a’}};
is equivalent tochar names[3][10]={“Rajkumar”,”Sanjana”,”Pooja”};
When this Two-dimensional character array is initialized, it will be in memory as follows:

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

names[0] R a j k u m a r \0
names[1] S a n j a n a \0
names[2]
P o o j a \0

Reading and printing multiple strings: The above three methods will be very helpful in reading
and printing each string with the help of a loop. The loop is used for keeping track of loop
counter of rows of two-dimensional array.
The following example clears this concept:
Method 1 using scanf() and printf()::
#include<stdio.h>
#include<string.h>

int main()
{ char names[10][15];
int n,i;
printf("\n How many strings:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter %d string:",i+1);
scanf("%s",names[i]);
}
printf("\n Given strings are:");
for(i=0;i<n;i++)
printf("%s\t",names[i]);
}

Method 2 using gets() and puts()::


#include<stdio.h>
#include<string.h>
int main()
{
char names[10][15]; OUTPUT:
int n,i; How many strings:3
printf("\n How many strings:");
scanf("%d",&n); Enter 1 string:Rajkumar
printf("\n enter strings:");
char ch=getchar(); Enter 2 string:Sanjana
for(i=0;i<n;i++)
gets(names[i]); Enter 3 string:Pooja
printf("\n Given strings are:");
Given strings are:Rajkumar Sanjana Pooja
for(i=0;i<n;i++)
puts(names[i]);
}

Method 3 using getchar() and putchar()::


#include<stdio.h>
int main()
{ char names[10][15],ch;
int i,n,j,k;
printf("\n How many strings:");
scanf("%d",&n);
ch=getchar();
for(k=0;k<n;k++)
{
printf("\n Enter %d string:",k+1);
for(i=0;(ch=getchar())!='\n';i++)
names[k][i]=ch;
names[k][i]='\0';
}
printf("\n Given strings are:");
for(k=0;k<n;k++)
{
for(i=0;names[k][i]!='\0';i++)
putchar(names[k][i]);
putchar("\n");
}
}

Operations on 2D non-numeric arrays


/*A program to sort strings in alphabetical order*/
#include<stdio.h>
#include<string.h>
int main()
{ char names[10][15],temp[15];
int n,i,j;
printf("\n How many strings:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter %d string:",i+1);
scanf("%s",names[i]);
}

for(i=0;i<n;i++) OUTPUT:
{ How many strings:3
for(j=i+1;j<n;j++)
{ Enter 1 string:rajkumar

if(strcmp(names[i],names[j])>0) Enter 2 string:sanjana


{
strcpy(temp,names[i]); Enter 3 string:pooja
strcpy(names[i],names[j]);
strcpy(names[j],temp); Strings in alphabetical order:pooja rajkumar sanjana
}
}
}
printf("\n Strings in alphabetical order:");
for(i=0;i<n;i++)
printf("%s\t",names[i]);
}

/*A program to search for a string in multiple strings*/


#include<stdio.h>
#include<string.h>
int main()
{ char names[10][15],ele[15];
int n,i,pos;
printf(" How many strings:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter %d string:",i+1); OUTPUT:
scanf("%s",names[i]); How many strings:3
}
printf("\nEnter string to search:"); Enter 1 string:rajkumar
scanf("%s",ele);
for(i=0;i<n;i++) Enter 2 string:sanjana
{
if(strcmp(names[i],ele)==0) Enter 3 string:pooja
{
Enter string to search:sanjana
pos=i+1;
break;
String is found at 2 position
}
}
if(pos<=0)
printf("\n String is not found");
else
printf("\nString is found at %d position",pos);
}
Try them::

A program print frequencies of words in a line of text

A program to print words those begin with given alphabet

You might also like