Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Programming chapter 4

Chapter Four of 'Fundamentals of Programming' discusses arrays and strings in C++. It explains how arrays store multiple values of the same type, their definition, memory requirements, and how to access and manipulate their elements. Additionally, it covers string manipulation functions and the C++ string class for handling character sequences.

Uploaded by

atakilti
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Programming chapter 4

Chapter Four of 'Fundamentals of Programming' discusses arrays and strings in C++. It explains how arrays store multiple values of the same type, their definition, memory requirements, and how to access and manipulate their elements. Additionally, it covers string manipulation functions and the C++ string class for handling character sequences.

Uploaded by

atakilti
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 8

Fundamentals of Programming

January, 2013

Chapter Four Arrays and strings


Introduction
The variables you have worked with so far are designed to hold only one value at a time. An
array works like a variable that can store a group of values, all of the same type. The values are
stored together in consecutive memory locations. An array is a sequence of objects all of which
have the same type. The objects are called the elements of the array and are numbered
consecutively 0, 1, 2, 3, . . . . These numbers are called index values or subscripts of the array.
The term “subscript” is used because as a mathematical sequence, an array would be written with
subscripts: a0, al, a2, . . . . These numbers locate the element’s position within the array, thereby
giving direct access into the array.

Array Definition
Like other normal variables, the array variable must be defined before its use. The syntax for
defining an array is:
Data type ArrayName[array size];
In the definition, the array name must be a valid C++ variable name, followed by an integer
value enclosed in square braces. The integer value indicates the maximum number of elements
the array can hold. The following are some valid array definition statements:
int marks[100]; //integer array of size 100
float salary[25]; //floating-point array of size 25
char name[50]; //character array of size
double[10]; // double array of size 10
N.B. Arrays of any data type can be defined.

Here is a definition of an array of integers: int hours[6]; The name of this array is hours. The
number inside the brackets is the array’s size declarator. It indicates the number of elements, or
values, the array can hold. The hours array can store six elements, each one an integer. This is
depicted in Figure below.
hours array: Enough memory to hold six int values

Page | 1
Fundamentals of Programming
January, 2013

Chapter Four Arrays and strings


Element 0 Element 1 Element 2 Element 3 Element 4 Element 5

An array’s size declarator must be a constant integer expression with a value greater than zero. It
can be either a literal, as in the previous example, or a named constant, as shown here:

const int SIZE = 6;

int hours[SIZE];

Memory Requirements of Arrays


The size of an array can be calculated by multiplying the number of bytes needed to store an
individual element by the number of elements in the array.
Example Array Size Declarators
Array declaration Number of elements size of each element size of the array
char letter[26]; 26 1 byte 26 bytes
short ring[100]; 100 2 bytes 200 bytes
int mile[84]; 84 4 bytes 336 bytes
float temp[12]; 12 4 bytes 48 bytes
double distance[1000]; 1000 8 bytes 8,000 bytes

Accessing Array Elements


Once an array variable is defined, its elements can be accessed using an index. The syntax for
accessing array elements is:
ArrayName[index];
Even though an entire array has only one name, the elements may be accessed and used as
individual variables. This is possible because each element is assigned a number known as a
subscript. A subscript is used as an index to pinpoint a specific element within an array. To
access a particular element in the array, specify the array name followed by an integer constant
or variable (array index) enclosed within square braces. The array index indicates the element of
the array which has to be accessed. For example the expression
hours[4]

Page | 2
Fundamentals of Programming
January, 2013

Chapter Four Arrays and strings


accesses the fifth element of the array hours. Note that, in an array of N elements the first
element is indexed by 0, the second element is indexed by 1, and so forth and the last element is
indexed by N-1. The six elements in the hours array would have the subscripts 0 through 5. This
is shown in Figure below:
Subscripts (index values)
0 1 2 3 4 5

Note:
Subscript numbering in C++ always starts at zero. The subscript of the last element in an array is
one less than the total number of elements in the array. This means that in the array shown
above, the element hours[6] does not exist. The last element in the array is hours[5] .
Array initialization
Arrays may be initialized when they are defined as follows:
DataType array-name[size]={list of values separated by comma};
For instance the statement: int age[5]={19,21,16,1,50}; defines an array of integers of size 5. In
this case, the first element of the array age is initialized with19, second with 21 and so on. A
semicolon always follows the closing brace. The array size may be omitted when the array is
initialized during array definition as follows:
int age[]={19,21,16,1,50};
in such case the compiler assumes the array size to be equal to the number of elements enclosed
within the curly braces.

Processing Array Contents


Individual array elements are processed like any other type of variable. Processing array
elements is no different than processing other variables. For example, the following statement
multiplies hours[3] by the variable rate:
pay = hours[3] * rate;
And the following are examples of pre-increment and post-increment operations on array
elements:
Page | 3
Fundamentals of Programming
January, 2013

Chapter Four Arrays and strings


int score[5] = {7, 8, 9, 10, 11};
++score[2]; // Pre-increment operation on the value in score[2]
score[4]++; // Post-increment operation on the value in score[4]
Note: When using increment and decrement operators, be careful not to confuse the subscript
with the array element. The following example illustrates the difference.
amount[count]--; // This decrements the value stored in amount[count].
amount[count--]; // This decrements the variable count, but does nothing to the value stored in
amount[count].
Strings
A string (also called a character string) is a sequence of contiguous characters in memory
terminated by the NULL character ( ‘\ 0’ ) .Strings are used in programming language for storing
and manipulating text such as words, names and sentences. It is represented as an array of
characters and end of string is marked by the null character(‘\0’). String constants are enclosed in
double quotes. For instance, “Hello World” is a string.
Array of characters represented a string is defined as follows:
char array-name[size];
For instance, the statement char name[50]; defines an array and reserves 50 bytes memory for
storing a set of characters. The length of this string cannot exceed 49 since one storage location
is reserved for storing the end of the string marker. The following program defines an array and
uses it to store characters.
#include<iostream.h>
int main()
{
char name[50];
cout<< “enter your name<49-max>”;
cin>>name;
cout<< “your name is:”<<name;
return 0;
}
String Manipulation

Page | 4
Fundamentals of Programming
January, 2013

Chapter Four Arrays and strings


C++ has several built-in functions such as strlen(), strcat(),strcpy(), etc. for string manipulation.
To use these functions, the header file string.h must be included in the program using the
statement: #include<string.h>
String length
The string function strlen() returns the length of a given string. A string constant or an array of
characters can be passed as an argument. The length of the string excludes the end of string
character (NULL).
Example
#include<iostream.h>
Program Output
#include<string.h>
int main()
{ Enter Your Name: Selam
char s1[25]; strlen(s1): 5
cout<< “Enter your name:”;
cin>>s1;
cout<< “strlen(s1):”<<strlen(s1)<<endl;
return 0;
}
String copy
The string function strcpy() copies the content of one string to another. It takes two arguments,
the first argument is the destination string array and the second argument is the source string
array. The source is copied into the destination string.
Example
#include<iostream.h>
#include<string.h>
int main() Program Output
{
char s1[25],s2[25];
cout<< “Enter a string:”; Enter a string: Garbage
cin>>s1; strcpy(s2,s1): Garbage
strcpy(s2,s1);
cout<< “strcpy(s2,s1):”<<s2;
return 0;
}
String Concatenation
Page | 5
Fundamentals of Programming
January, 2013

Chapter Four Arrays and strings


The string function strcat() concatenates two strings resulting in a single string. It takes two
arguments, which are the destination and source strings. The destination and source strings are
concatenated and the resulting string is stored in the destination (first) string.
Example
#include<iostream.h>
Program Output
#include<string.h>
int main()
{ Enter string s1: C
char s1[40],s2[25]; Enter string s2: ++
cout<< “Enter string s1:”; strcat(s1,s2): C++
cin>>s1;
cout<< “Enter string s2:”;
cin>>s2;
strcat(s1,s2);
cout<< “strcat(s1,s2):”<<s1;
return 0;}
String Comparison
The string function strcmp() compares two strings character by character. It accepts two strings
as parameters and returns an integer whose value is :
<0 if the first string is less than the second
==0 if both are identical
>0 if the first string is greater than the second
Whenever two corresponding characters in the string differ, the string which has the character
with the higher ASCII value is greater. For example consider the string hello and Hello. The first
character itself differs. The ASCII code for h is 104, while the ASCII code for H is 72. Since the
ASCII code of h is greater, the string hello is greater than the string Hello. Once a different
character is found, there is no need to compare remaining characters in the string.
Example
#include<iostream.h>
#include<string.h>
int main()
{
Program Output
char s1[25],s2[25];
cout<< “Enter string s1:”;
cin>>s1; Enter string s1: Computer
cout<< “Enter string s2:”; Enter string s2: Computing
strcmp(s1,s2): Computer is less than Computing
Page | 6
Fundamentals of Programming
January, 2013

Chapter Four Arrays and strings


cin>>s2;
strcat(s1,s2);
int status=strcmp(s1,s2);
cout<< “strcmp(s1,s2):”;
if(status==0)
cout<<s1<< “is equal to ”<<s2;
else if(status>0)
cout<<s1<< “is greater than ”<<s2;
else
cout<<s1<< “is less than ”<<s2;
return 0;
}

String to Upper/Lower Case


The functions strlwr() and strupr() convert a string to lower case and upper case respectively.
Example
#include<iostream.h>
#include<string.h>
int main() Program Output
{
char s1[25],temp[25];
cout<< “Enter a string :”; Enter a string: Maths
cin>>s1; strupr(temp): MAHS
strcpy(temp,s1); strlwr(temp): maths
cout<< “strupr(temp):”<< strupr(temp)<<endl;
cout<< “strlwr(temp):”<< strlwr(temp)<<endl;
return 0;
}
More about the C++ string class

string address; Defines an empty string object named address.


string name("William Smith"); Defines a string object named name, initialized with
“William Smith.”
string person1(person2); Defines a string object named person1, which is a copy of
person2. Person2 may be either a string object or character
array.
string set1(set2, 5); Defines a string object named set1, which is initialized to
the first five characters in the character array set2.

Page | 7
Fundamentals of Programming
January, 2013

Chapter Four Arrays and strings


string firstName(fullName, 0, 7); Defines a string object named firstName, initialized with a
substring of the string fullName. The substring is seven
characters long, beginning at position 0.
Examples
#include<iostream.h> Program Output
#include<string.h>
int main(){
string str1, str2, str3; ABC
str1 = "ABC"; DEF
str2 = "DEF"; ABCDEF
str3 = str1 + str2; ABCDEFGHI
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
str3 += "GHI";
cout << str3 << endl;
return 0; }

Page | 8

You might also like