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

Chapter 4 Array and String

Chapter 4 covers array and string manipulation in programming, explaining the concept of arrays as collections of data with the same type and name, and how they can simplify data management. It discusses single-dimensional and multidimensional arrays, providing examples of their usage in C++. The chapter also introduces strings, their representation in C++, and how to manipulate and access individual characters within strings.

Uploaded by

Ŷď Yøñî
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter 4 Array and String

Chapter 4 covers array and string manipulation in programming, explaining the concept of arrays as collections of data with the same type and name, and how they can simplify data management. It discusses single-dimensional and multidimensional arrays, providing examples of their usage in C++. The chapter also introduces strings, their representation in C++, and how to manipulate and access individual characters within strings.

Uploaded by

Ŷď Yøñî
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Chapter 4

Array and String Manipulation

What is an Array?
• An array is a collection of data storage locations, each
having the same data type and the same name.
• Each storage location in an array is called an array
element.
Why do you need arrays in your programs?
• Imagine that you're designing a program to keep track
of your business expenses. The program could declare
12 separate variables, one for each month's expense
total.
• This program have 12 separate folders for your receipts.
• Good programming practice, however, would utilize
an array with 12 elements, storing each month's
total in the corresponding array element.
• This approach is comparable to filing your receipts
in a single folder with 12 compartments.
Single-Dimensional Arrays
• A single-dimensional array has only a single
subscript.
• A subscript is a number in brackets that follows an
array's name. This number can identify the number
of individual elements in the array.
Example
float expenses[12];
• The array is named expenses, and it contains 12
elements.
• Each of the 12 elements is the exact equivalent of a
single float variable and all C++'s data types can be used
for arrays.
• C++ array elements are always numbered starting at 0,
so the 12 elements of expenses are numbered 0 through
11.
• When you declare an array, the compiler sets aside a
block of memory large enough to hold the entire array.
• Individual array elements are stored in sequential
memory locations.
Following figure shows the sequential memory locations of
an array A[10].
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]

• A[0]
• A[1]
• A[2]
• A[3]
• A[4]
• A[5]
• A[6]
• A[7]
• A[8]
For example
• The following statement stores the value 25 in
the first array element (remember, the first
array element is A[0] not A[1]):
• A[0] = 25;
• When you use arrays, keep the element
numbering scheme in mind: In an array of n
elements, the allowable subscripts range from
0 to n-1.
The following programs demonstrates the use
of an array.
Example 1: Demonstration of a simple array.
#include<iostream.h>
main()
{
int a[3];
a[0] = 12;
a[1] = 7;
a[2] = 65;
cout<<” The array elements are\n”;
cout<<a[0]<<endl;
cout<<a[1]<<endl;
cout<<a[2];
• When you run the above program, it makes
an array of size 3.
• The first array location is initialized with value
12, second with 7 and third with 65. Then the
program displays all the values in different
lines.
The following programs demonstrate the use of
arrays.
• Example 2: An integer array of size 5 that accepts values from user and
displays them on the screen.
#include<iostream.h>
main()
{
int i, a[5];
for(i = 0; i < 5; i++)
{
cout<< “Please enter the element of array: “;
cin>>a[i];
}
cout<<”\n The array elements are\n”;
for(i = 0; i < 5; i++)
{
cout<<a[i]<<endl;
}
Example 3: A float array of size 5 that accepts values from user and
displays their sum and average.
#include<iostream.h>
main()
{
int i;
float a[5], sum = 0, avg;
for(i = 0; i < 5; i++)
{
cout<< “Please enter value “<<(i+1)<<”: “;
cin>>a[i];
sum = sum + a[i];
}
cout<<”Sum = ”<<sum;
avg = sum/5;
cout<<”\nAverage = ”<<avg;
Multidimensional Arrays
• It is possible to have arrays of more than
one dimension. Each dimension is
represented as a subscript in the array.
• Therefore, a two-dimensional array has
two subscripts; a three dimensional array
has three subscripts; and so on.
• Arrays can have any number of
dimensions, although it is likely that most
of the arrays you make will be of one or
two dimensions.
• A good example of a two-dimensional array is a chess
board.
• One dimension represents the eight rows; the other
dimension represents the eight columns.
Suppose that you have a class named SQUARE.
The declaration of an array named Board that
represents it would be
• SQUARE Board[8][8];
• You could also represent the same data with a one-
dimensional, 64-square array. For example,
• SQUARE Board[64];
• This doesn't correspond as closely to the real-world
object as the two-dimension.
• When the game begins, the king is located in the
fourth position in the first row. Counting from zero
array, that position corresponds to Board[0][3];
Initializing Multidimensional Arrays
• You can initialize multidimensional arrays. You
assign the list of values to array elements in order,
with the last array subscript changing while each of
the former holds steady.
• Therefore, if you have an array
• int theArray[5][3]
• The first three elements go into theArray[0]; the
next three into theArray[1]; and so forth.
• You initialize this array by writing
• int theArray[5][3] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }
• For the sake of clarity, you could group the initializations with
braces. For example,
• int theArray[5][3] =
{ {1,2,3},
{4,5,6},
{7,8,9},
{10,11,12},
{13,14,15} };
• The compiler ignores the inner braces, which
make it easier to understand how the numbers
STRING
• Natural languages are based upon words and
punctuation, connected to form sentences
and paragraphs.
• In computer science languages, these are
usually referred to as strings.
• Computer programming languages all need to
represent natural language in some form or
another, either to interact with users, record
data to a file, send data to a printing device,
etc.
Strings as raw data
• Here's a familiar example of a program which
contains a string.
• In this program, that string is used to send the user
a message.

#include<iostream.h>
main()
{
cout<<”hello, world”;
}
C++ Strings
Here is a new example containing another kind of
string, a C++ String.

#include<iostream.h>
main()
{
char hello[30];
hello[30] = “hello, world”;
cout<<hello;
}
• There are some new elements to this
program;
Here is the instruction which makes the C++
string.
• char hello[] = "Hello, World";
• Behind the scenes, the program makes a C++
array variable called hello. This variable owns
an area in memory, to which the data, "Hello,
World" is copied into.
Strings as input
• A programmer might want to ask the user to input a
string, such as their name, the name of a file, details
about a book, etc.
C++ strings are well equipped for this task.
#include<iostream.h>
main()
{
char your_name[30];
cout<<”hello, what is your name? “;
cin>>your_name;
cout<<” pleased to meet you, “<<your_name;
• Again, the program makes a C++ string, but initially
leaves it empty. After sending the user a message,
the program calls upon cin to help out.
• cin >> your_name;
• The program should wait for the user to type their
name and press enter, then output a message
directed at them, "Pleased to meet you".
• There's a hidden problem, however. If the user
enters their full name, cin only recognizes the first
part of their name, the rest is left alone.
For Example
• Hello, What is your name? Tesfaye Abera
• Pleased to meet you, Tesfaye
• What happens here is a direct result of one of the
shortcomings of the >> symbol, which is used for
reading data from the user.
• The program only reads from the user up until the
first 'white space' character.
• A white space character is usually a space, a tab, a
carriage return, or a new line.
• The solution is to force the program to read
everything up until the point when the user hit
'return' or 'enter'.
• C++ has the perfect tool for the job, called getline
which, as its name suggests, retrieves an entire line
of text.
#include<iostream.h>
main()
{
char your_name[30];
cout<<”hello, what is your name? “;
cin.getline(your_name,30);
cout<<” pleased to meet you, “<<your_name;
}
Strings as character sequences
• Thus far, strings have been treated as complete
entities, although, in reality, strings are actually
sequences of characters.
• Many problems involving strings are interested with
specific characters, and the positions where those
characters occur in a string.
• C++ provides complete un-hindered access to
characters in a string through the subscript
operator.
• The subscript operator is a pair of square brackets,
which takes an integer, representing a character's
position in a string.
#include<iostream.h>
main()
{
char myname[]=”abdulqadir”;
cout<<”the first character of ”<<myname<<”is
“<<myname[0];
}
• The first character in a string is always position zero.
• Since the first character in a string is position zero,
logic dictates that the last character in a string must
be at a position 'one less' than the string's length.
• For "abdulqadir", which is 11 characters long, its last
character will appear at position 10.
#include<iostream.h>
main()
{
char myname[]=”abdulqadir”;
cout<<”the last character of ”<<myname<<”is
“<<myname[9];
}
How long is a string and what is last word?
#include<iostream.h>
#include<string.h>
main()
{
char a[20]= “tesfaye abera”;
int l;
l=strlen(a);
cout<<”length of the string is “<<l;
l=l-1;
cout<<”last word of the string is “<<endl<<a[l];
}
Changing characters within a string
• Since string objects are modifiable, The subscript operator
provides direct access to the memory area where a particular
character is stored.
• As a consequence of this, any character within a string object
can be modified in much the same way as a normal variable.
#include<iostream.h>
#include<string.h>
main()
{
char a[20]= “tesfaye abera”;
a[0]=’*’;
cout<<a;
}

You might also like