0% found this document useful (0 votes)
14 views

Arrays and Strings

The document provides an overview of arrays and strings in C programming, detailing their definitions, types (single-dimensional, two-dimensional, and multi-dimensional arrays), and basic operations such as reading, displaying, and manipulating data. It also covers string handling, including functions for string length, copying, concatenation, and reversal, along with examples of how to implement these functions. Additionally, it highlights the advantages and disadvantages of using arrays.

Uploaded by

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

Arrays and Strings

The document provides an overview of arrays and strings in C programming, detailing their definitions, types (single-dimensional, two-dimensional, and multi-dimensional arrays), and basic operations such as reading, displaying, and manipulating data. It also covers string handling, including functions for string length, copying, concatenation, and reversal, along with examples of how to implement these functions. Additionally, it highlights the advantages and disadvantages of using arrays.

Uploaded by

Hemanth Atla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 15

Ram’s C – Programming Arrays

& Strings
ARRAYS
An array is a contiguous blocks of memory that holds similar kind of values. In some other way,
an array is a sequence of homogeneous or similar kind of items. An array can be defined as a
group of similar kind of items referred by a common name. A specific element in the array is
located or identified by its index value. C supports different types of Arrays. They are:

o Single dimensional arrays


o Two-dimensional arrays
o Multi-dimensional arrays.

Single dimensional arrays:


An array with one subscript variable is known an single dimensional array. It is also known as
linear list or simply list. The general form follows:

Data type array name[ index];


Or
Data type array name[no.of items];
Ex:
int a[10]; // an array of 10 integers
char s[20]; // an array of 20 characters or simple a string.
float f[15]; // an array of 15 floating point values.
Symbolic representation:

Int a[6] = { 10, 15, 12, 18, 20, 25};

a Array name

10 15 12 18 20 25 Array values

0 1 2 3 4 5 Index positions
In memory, all the elements of above array are placed in continuous locations. Suppose the
starting is at 100th location then the remaining locations are 102, 104, 106, 108, 110. Here 100 is
the base address of array ‘a’. Index values always start from 0. Each element is referred as a[0],
a[1], a[2]…… Index values should not be negative values & the size of the array should not be a
value, which is less than 0.

Ex: #include<stdio.h>
#include<conio.h>
void main()
{
int a[6] ={11,12,14,45,43,56};
int I;
clrscr();
for(I=0;I<6;I++)
printf(“%d”,a[I]);
getch();
}

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 1


Ram’s C – Programming Arrays
& Strings
Two-dimensional arrays:
An array with two subscript variables is known as two-dimensional array. The first subscript
resembles number of rows & the second subscript resembles number of columns. It is also
called as double dimensional array. The general form follows:

Data type array name [ no.of rows][no.of columns];

Ex:
Int a[4][4];// an integer array with 4 rows & 4 columns
Char str[5][15]; //a char. Array with 5 rows & 15 columns (or) a set of 5 names
// with 15 characters in each name.

Symbolic representation follows:


Int a[3][4] = { 11, 55, 44, 33, 77, 99, 88, 67, 22, 25, 78, 87};

0 1 2 3
0 11 55 44 33
1 77 99 88 67
2 22 25 78 87

Here
a[0][0] = 11 , a[0][1] = 55, a[0][2] = 44, a[0][3] = 33
a[1][0] = 77, a[1][1] = 99 ………………………..
a[2][0] = 22, a[2][1] = 25 …………………………

Reading (entering) Data into an Array:


Here is the section of code that places data into an array:
void main ()
{
int num[10],i;
clrscr();
printf(“\n Enter List of Numbers:”);
for (i = 0; i <= 9; i++)
{
scanf (“%d", &num[i]);
}
}
Output:
Enter list of Numbers: 1 2 3 4 5 6 7 8 9 10

The for loop causes the process of asking for and receiving a list of 10 numbers from the
user. The first time through the loop, i has a value 0, so the scanf() function will cause the
value typed to be stored in the array element num[0], the first element of the array. This
process will be repeated until i become 9. This is last time through the loop, which is a
good thing, because there is no array element like num[10].

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 2


Ram’s C – Programming Arrays
& Strings
Displaying Data from an Array:
In many situations, it is needed to read the data back out of the array and uses it to
further calculation during the program.
for ( i = 0 ; i <= 9; i++ )
printf(“%d ", num[i] ) ;
Advantages of Arrays:
1. Arrays are able to hold fixed no.of elements & identical values.
2. Accessing of array elements is easy.
3. Arrays hold any number of items.
4. Pointer can be applied on arrays.
5. More flexible.

Disadvantages of arrays:
1. As the array size is fixed, we cannot grew or shrink the size. Hence it may lead to
wastage of memory.
2. Insertions & deletions are difficult to perform.
3. Unable to hold different values.

Muti-dimensional arrays:

The other way of representing arrays is multi-dimensional arrays. In this category, there may be
any number of subscripts in the array. The general form follows:

Data type array name [ size1][size2][size3]…………


Ex:
Int a[3][5][5];

In the above array, a maximum of 3*5*5 = 75 elements can be placed.

STRINGS
 A string is a collection of character data.

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 3


Ram’s C – Programming Arrays
& Strings
 In other words, a set of characters followed by a null is known to be a string i.e., at
the end of every string, there exists a null terminating character (‘\0’).
 It represents end of string. Strings are able to hold names & sentences.

Ex: char str[8]= “hanuman”;

Note:
A string with size 8 is able to hold at most 7 characters. The 8th character will be ‘\0’.
In order to perform input/output operations on strings, C provides different functions.
They are called as unformatted I/O.

Ex: Reading and Displaying String.


#include<stdio.h>
#include<conio.h>
void main()
{
char str[10];
clrscr();
puts(“Enter any string:”); // unformatted Output function
gets(str); // unformatted Input function.
puts(str);
getch();
}
String handling functions
A string in C is simply an array of characters. The following are the basic string handling
functions. All the string-handling functions are prototyped in: #include <string.h>
Function Meaning
strlen Determine the length of a string
strncat Append n characters from string2 to stringl
strcmp Compare string1 and string2 to determine Alphabetic order
Strrev Reverses the given string
strcpy Copy string2 to stringl
strerror Get error message corresponding to specified error number.
stpcpy Copy one string into another
strncmp Compare first n characters of two strings.
strncpy Copy first n characters of string2 to stringl

strlen() Function :
This function counts the number of characters present in a string.
Syntax:
int strlen(char *str );
The strlen() function calculates the length, in bytes, of str. This calculation
does not include the null terminating character. strlen() function returns
integer value.

Ex: main()
{
char s[20];

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 4


Ram’s C – Programming Arrays
& Strings
int i,charcount=0;
clrscr();
printf("\n Enter any string : ");
gets(s);
charcount = strlen(s);
printf("\n No. of characters in the given string : %d",charcount);
getch();
}

String Length without Using String Handling Functions:


main()
{
char s[20];
int i,charcount=0;
clrscr();
printf("\n Enter any string : ");
gets(s);
for(i=0;s[i]!='\0';i++)
charcount++;
printf("\n No. of characters in the given string : %d",charcount);
getch();
}

strcpy() Function :
This function copies the contents of one sting into another. The base address of the
source and target strings should be supplied to this function.
Syntax:
char *strcpy (char *str1, char *str2);
The strcpy function copies characters from str2 to str1 and including the
terminating null character. The str2 should be a variable and str1 can
either be a string constant or a variable.
The strcpy function returns a string str2.
Ex:
main()
{
char a[20],b[20];
int i;
clrscr();
printf("\n Enter any string : ");
gets(a);
strcpy(b,a);
printf("\n Copied string is : ");
puts(b);
getch();
}
String Copy Without Using String Handling Functions:
main()
{

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 5


Ram’s C – Programming Arrays
& Strings
char a[20],b[20];
int i;
clrscr();
printf("\n Enter any string : ");
gets(a);
for(i=0;a[i]!='\0';i++)
{
b[i]=a[i];
}
b[i] = '\0';
printf("\n Copied string is : ");
puts(b);
getch();
}

strrev() Function :
This function reverses the string.
Ex:
main()
{
char a[20],b[20];
int i,stringlength=0;
clrscr();
printf("\n Enter any string : ");
gets(a);
strrev(a);
printf("\n Reversed string is : ");
puts(a);
}
String Reverse without using String Handling Functions:
#include <stdio.h>
#include <conio.h>
#include <string.h>

main()
{
char a[20],b[20];
int i,stringlength=0;

clrscr();
printf("\n Enter any string : ");
gets(a);
for(i=0;a[i]!='\0';i++)
{
stringlength++;
}
for(i=0;i<stringlength;i++)
{
b[i]=a[stringlength-(i+1)];

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 6


Ram’s C – Programming Arrays
& Strings
}

printf("\n Reversed string is : ");


puts(b);
getch();
}

strcat() Function :
This function concatenates the source string into target string. It is necessary to place ‘\
0’ into the target string, to make its end.

Syntax: char *strcat(char *str1, const char *str2);

 The strcat() function concatenates or appends str2 to str1. All characters from
str2 are copied including the terminating null character.
 The str1 should be a variable and str2 can either be a string constant or a
variable. The strcat() function returns the string str1.

Ex:
main()
{
char a[20],b[20],c[40];
int i,j;
clrscr();
printf("\n Enter 1st string:");
gets(a);
printf("\n Enter 2nd string :");
gets(b);
strcpy(c,a);
strcat(c,b);
printf("\n concatenated string is ");
puts(c);
}
String Concatenation without using String Handling Functions:
#include <stdio.h>
#include <conio.h>
main()
{
char a[20],b[20],c[40]; int i,j;
clrscr();
printf("\n Enter 1st string:"); gets(a);
printf("\n Enter 2nd string :"); gets(b);
for(i=0;a[i]!='\0';i++)
{
c[i]=a[i];
}
for(j=0;b[j]!='\0';j++)
{
c[i+j]=b[j];

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 7


Ram’s C – Programming Arrays
& Strings
}
c[i+j]='\0';
printf("\n concatenated string is "); puts(c);
getch();
}

Program to check whether a given string is palindrome or not.


main()
{
char a[20],b[20];
int i,l=0,flag=0;
clrscr();
printf("\n enter any string : ");
gets(a);
l = strlen(a);
for(i=0;i<l;i++)
{
b[i]=a[l-(i+1)];
}
for(i=0;i<l;i++)
{
if(b[i]!=a[i])
flag=1;
}
if(flag==1)
printf("\n %s is not a palindrome.",a);
else
printf("\n %s is a palindrome.",a);

getch();
}
Program to find count of words in a string.
main()
{
char s[200];
int i,wordcount=0,wordflag = 0,slen;
clrscr();
printf("\n enter any string:");
gets(s);
slen = strlen(s);
for(i=0;i<=slen;i++)
{
if ((s[i] >= 65 && s[i] <= 91) || (s[i] >= 97 && s[i] <= 122) || (s[i] >= 48 &&
s[i] <= 57))
{
wordflag = 1;
continue;
}
if (wordflag == 1)

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 8


Ram’s C – Programming Arrays
& Strings
{
if (s[i]==' ' || s[i] == '\0' || s[i] == '.' || s[i] == ',')
{
wordcount++;
wordflag=0;
}
}
}
printf("\n Number of words in a given string=%d",wordcount);
getch();
}
Program to count number of vowels in a given string
main()
{
char s[20];
int i,l=0;
clrscr();
printf("\n enter any strying:");
gets(s);
for(i=0;s[i]!='\0';i++)
{
if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u' || s[i]=='A' ||
s[i]=='E' || s[i]=='I' || s[i]=='O' || s[i]=='U' )
l++;
}
printf("\n No. of vowels in a given string are : %d",l);
getch();
}
program to compare the characters in a given string and arrange them in
ascending order.
main()
{
char a[100],temp;
int i,j,l=0;
clrscr();
printf("\n Enter a string :");
gets(a);
l=strlen(a);
for(i=0;i<l-1;i++)
{
for(j=i+1;j<l;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 9


Ram’s C – Programming Arrays
& Strings
}
a[l] = '\0';
printf("\n Arranged string in ascending order is :%s",a);
getch();
}

Write a program to print in the following format.


C
C O
C O M
C O M P
C O M P U
C O M P U T
C O M P U T E
C O M P U T U R

#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
char s[10];
int i,j;
clrscr();
printf("\n Enter a string : ");
gets(s);
for(i=0;s[i] != '\0';i++)
{
for(j=0;j<=i;j++)
{
printf("\t%c",s[j]);
}
printf("\n");
}
getch();
}

Write a program to print the following format.


R
E R
T E R
S T E R
A S T E R
M A S T E R

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

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 10


Ram’s C – Programming Arrays
& Strings
#include <string.h>
main()
{
char s[10];
int i,j,sp;
clrscr();
printf("\n Enter a string : ");
gets(s);
sp = strlen(s)-1;
for(i=strlen(s)-1;i>=0;i--)
{
for(j=0;j<=sp;j++) printf("\t");
for(j=i;j<=strlen(s);j++)
{
printf("\t%c",s[j]);
}
printf("\n");
sp--;
}
getch();
}

Character I/O in C.

FUNCTION PURPOSE
getchar() To accept a single character from the keyboard; it returns the same
character
gets() To accept a string from the keyboard
getch() To accept a single character from the keyboard; it returns the ASCII
value of the character. It doesn’t echo the character on the screen
getche() To accept a single character from the keyboard; it returns the ASCII
value of the character. It echoes the character on the screen
Putchar() To prints a given character on the screen
Puts To print a given string on the screen
Isalpha() To check whether the given character is alphabet or not
Isdigit() To check whether the given character is digit or not
Isalnum() To check whether the given character is alphanumeric or not
Isspace() To check whether the given character is a space or not
Islower() To check whether the given character is alphabet and is in lower case
or not
Isupper() To check whether the given character is alphabet and is in upper case
or not

isalpha():
The isalpha( ) function returns nonzero if ch is an alphabet; otherwise zero is returns

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 11


Ram’s C – Programming Arrays
& Strings
int isalpha(char ch);

Ex: void main()


{
char ch;
clrscr();
printf(“\n Enter Any Character:”);
scanf(“%c”,&ch);
if(isalpha(ch))
printf(“\n Given Character is Alpahbet”);
else
printf(“\n Given Character is not a Alphabet”);
getch();
}

isalnum():
The isalnum( ) function returns nonzero if its argument is either a letter of the alphabet
or a digit. If the character is not alphanumeric, zero is returned
int isalnum(char ch);

Ex: void main()


{
char ch;
clrscr();
printf(“\n Enter Any Character:”);
scanf(“%c”,&ch);
if(isalnum(ch))
printf(“\n Given Character is Alphanumeric”);
else
printf(“\n Given Character is not a Alphanumeric”);
getch();
}
iscntrl():
The iscntrl( ) function returns nonzero if ch is a control character (new line, back space,
form feed, carriage return, vertical tab) ; otherwise it returns zero.
void main()
{
char ch;
clrscr();
printf(“\n Enter Any Character:”);
scanf(“%c”,&ch);
if(iscntrl(ch))
printf(“\n Given Character is control character”);
else
printf(“\n Given Character is not a control character”);
getch();
}

ispunct():

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 12


Ram’s C – Programming Arrays
& Strings
The ispunct( ) function returns nonzero if ch is a punctuation character; otherwise zero
is returned. The term ''punctuation," as defined by this function, includes all printing
characters that are neither alphanumeric nor a space. The punctuation characters are: "
# % & ' ( ) ; < = >> ? [ \ ] * + , - . / : ^ _ { | } ~.
int ispunct(int c);

Ex: void main()


{
char ch;
clrscr();
printf(“\n Enter Any Character:”);
scanf(“%c”,&ch);
if(ispunct(ch))
printf(“\n Given Character is punctuation character”);
else
printf(“\n Given Character is not a punctuation character”);
getch();
}

isspace():
The function returns nonzero if c is space otherwise this will return zero which will be
equivalent to false
int isspace(char ch);
Ex: void main()
{
char ch;
clrscr();
printf(“\n Enter Any Character:”);
scanf(“%c”,&ch);
if(isspace(ch))
printf(“\n Given Character is space”);
else
printf(“\n Given Character is not a space”);
getch();
}
isdigit():
The isdigit( ) function returns nonzero if ch is a digit, that is, 0 through 9. Otherwise
zero is returned.
int isdigit(int ch);
Ex: void main()
{
char ch;
clrscr();
printf(“\n Enter Any Character:”);
scanf(“%c”,&ch);
if(isdigit(ch))
printf(“\n Given Character is digit”);
else

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 13


Ram’s C – Programming Arrays
& Strings
printf(“\n Given Character is not a digit”);
getch();
}

isxdigit():
The isxdigit( ) function returns nonzero if ch is a hexadecimal digit; otherwise zero is
returned. A hexadecimal digit will be in one of these ranges: A–F, a–f, or 0–9.
int isxdigit(char ch);
Ex:
void main()
{
char ch;
clrscr();
printf(“\n Enter Any Character:”);
scanf(“%c”,&ch);
if(isdigit(ch))
printf(“\n Given Character is Hexa Decimal Digit”);
else
printf(“\n Given Character is not a Hexa Decimal digit”);
getch();
}

islower():
The islower() function returns nonzero if ch is a lowercase letter; otherwise zero is
returned.
int islower(char ch);
Ex:
void main()
{
char ch;
clrscr();
printf(“\n Enter Any Character:”);
scanf(“%c”,&ch);
if(islower(ch))
printf(“\n Given Character is in lower case”);
else
printf(“\n Given Character is not in a lower case ”);
getch();
}

isupper();
The isupper( ) function returns nonzero if ch is an uppercase letter; otherwise zero is
returned.
int isupper(char ch);

Ex:

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 14


Ram’s C – Programming Arrays
& Strings
void main()
{
char ch;
clrscr();
printf(“\n Enter Any Character:”);
scanf(“%c”,&ch);
if(isupper(ch))
printf(“\n Given Character is in Upper case”);
else
printf(“\n Given Character is not in a Upper case ”);
getch();
}

tolower():
The tolower( ) function returns the lowercase equivalent of ch, if ch is a upper case
character; otherwise ch is returned unchanged.
int tolower(char ch);
Ex:
#include <stdio.h>
void main()
{
clrscr();
printf( "Lower case of R is %c\n",
tolower('R'));
printf( "Lower case of 4 is %c\n",
tolower('4'));
printf( "Lower case of a is %c\n",
tolower('a'));
getch();
}

toupper():
The toupper( ) function returns the uppercase equivalent of ch, if ch is a lower
case letter; otherwise ch is returned unchanged..
int toupper(int c);

#include <stdio.h>
void main()
{
clrscr();
printf( "Upper case of m is %c\n", tolower('m'));
printf( "Upper case of 6 is %c\n", tolower('6'));
printf( "Upper case of u is %c\n", tolower('u'));
getch();

G. Ramanjaiah.,AMIETE,M.Sc(CS), M.Tech, (Ph.D) Assoc. Prof, Dept. Of CSE, RVIT, Guntur. 15

You might also like