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

Arrays & String Manipulation Concise

Chapter Four covers the fundamentals of arrays, string manipulation, and pointers in programming. It explains the definition, declaration, initialization, and processing of one-dimensional and multidimensional arrays, as well as string representation and manipulation techniques in C++. Additionally, it introduces pointers and their role in accessing memory locations.

Uploaded by

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

Arrays & String Manipulation Concise

Chapter Four covers the fundamentals of arrays, string manipulation, and pointers in programming. It explains the definition, declaration, initialization, and processing of one-dimensional and multidimensional arrays, as well as string representation and manipulation techniques in C++. Additionally, it introduces pointers and their role in accessing memory locations.

Uploaded by

kahsay
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Fundamentals of Programming I

Chapter Four
Arrays, String Manipulation and Pointers
4.1. What is an array

An array is a collection of data structure that stores elements/ items that have the same data
type
An array element is identified and accessed by its own unique index (or subscript).
The index must be an integer and indicates the position of the element in the array
In C++ the index of the first array element is 0 and the last element is N-1, where N is the
size of the array.

4.2. One Dimensional Array

4.2.1. Declaration of Arrays


General Syntax:
DataType arrayname[arraysize];
Examples:
int numbers[10]; // cause the compiler to allocate space for 10 consecutive int variables in
memory. That means, we can store 10 values of type int without having to declare 10 different
variables each one with a different identifier.
Example: char name[20]; //cause the compiler to allocate space for 20 consecutive char variables
in memory.
4.3.2 Initializing Arrays
int numbers[5]; //every element of numbers will be set initially to 0:
0 1 2 3 4
0 0 0 0 0

int numbers [5] = { 10, 20, 30, 40,50}; //array initialization


int numbers [10] = { 10, 20, 30, 40,50}; //array initialization
int numbers [10] = { 10, 20, 30}; //array initialization-fewer values than number of elements
int numbers [] = { 10, 20, 30, 40,50}; //possible initialization, the compiler will count the number of
initialization items.

0 1 2 3 4 indexes
10 20 30 40 50 Elements or Contents

4.3.3 Accessing and Processing Array Elements


The first element in an array in C++ always has index 0, and if the array has n elements
the last element will have the index n-1.
numbers[0] ; //To access the first element:
numbers[1] ; //To access the second element:
numbers[2] ; // To access the third element:
numbers[n-1] ; //To access the last element :
numbers[n] ; //using for loop-To access all the element :
n ;// using for loop //To find the index element:

To insert/read values into an array


Cout<<”Enter Array Elements”;
for(i=0;i<10);i++){
cin >> Array[i];
}
And the elements can be increased by 5, Array[i] = Array[i] + 5; or Array[i] += 5;
Array elements can form part of the condition for an if statement, or indeed, for any other
logical expression:
if (max<numbers[j]) {
max= numbers[j];
}
For loops are the usual means of accessing every element in an array. Here, the first NE
elements of the array annual_temp are given values from the input stream cin.
for (i = 0; i < MAX; i++){
cin >>numbers[i];
}
To find the sum & average numbers entered/stored in array numbers[5];
float numbers[5];
float sum = 0;
for (i = 0; i <5; i++){
sum += numbers[i];
av = sum / 5;
}
C++ Program that finds the sum & average of array elements
#include<iostream.h>
int main()
{
int numbers[] ={ 10,20,30,40,50}; //array declaration & initialization
int sum,average; //declaring variables that store sum and average of array
elements
sum = 0,average=0; //initializing sum & average to 0
for (int i = 0; i <5; i++){
sum += numbers[i];
average = sum / 5;
} //end of for loop
cout<<”The Sum of Array Elements=”<<sum;
cout<<”The Average of Array Elements=”<<average;
return 0;
} //end of main function

4.1.1. Displaying Arrays


int numbers[5]={10,20,30,40,50};
cout<<”\n List of Array Elements\n”;
for(i=0;i<5;i++){
cout<<numbers[i];
}

4.1.2. Copying Arrays


The assignment operator cannot be applied to array variables:
const int SIZE=10
int x [SIZE] ;
int y [SIZE] ;
x=y; // Error - Illegal
Only individual elements can be assigned to using the index operator, e.g., x[1] = y[2];.
To make all elements in 'x' the same as those in 'y' (equivalent to assignment), a loop has to
be used.
// Loop to do copying, one element at a time
for (int i = 0 ; i < SIZE; i++)
x[i] = y[i];
This code will copy the elements of array y into x, overwriting the original contents of x.

4.2. Multidimensional arrays


Multidimensional arrays are array of arrays. An array may have more than one dimension
(1D). 2D array have two subscripts, a three dimensional (3D) has three subscripts, N
dimensional (ND) have N subscripts).
Example: Matrix of 2x2 & 3x3 can be declared
int matrix[2][2]; // 2D array declaration
int matrix[3][3][3]; // 3D array declaration
Example: Matrix of 3x5
int matrix[3][5]; // declaration of 2D arrays

Example: int matrix[1][3];

4.2.1. Initializing Multidimensional Arrays


To initialize a multidimensional arrays , you must assign the list of values to array elements
in order, with last array subscript changing while the first subscript while the first subscript
holds steady.
Therefore, if the program has an array int theArray[5][3], the first three elements go int
theArray[0]; the next three into theArray[1]; and so forth.

The program initializes 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, the program could group the initializations with braces, as shown
below.
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 clarify how the numbers are distributed.

4.2.2. Omitting the Array Size


If a one-dimensional array is initialized, the size can be omitted as it can be found from the
number of initializing elements:
int x[] = { 1, 2, 3, 4} ;
This initialization creates an array of four elements.
Note however:
int x[][] = { {1,2}, {3,4} } ; // error is not allowed! and must be written
int x[2][2] = { {1,2}, {3,4} } ;
Example of multidimensional array
#include<iostream.h>
void main(){
int Array[5][2] = {{0,0},{1,2}, {2,4},{3,6}, {4,8}}
for ( int i=0; i<5; i++)
for (int j = 0; j<2;j++)
{
cout<<"Array["<<i<<"]["<<j<<'']: '';
cout<<Array[i][ j]<<endl;
}
}

4.3. Strings representation and manipulation


String in C++ is a sequence of character in which the last character is the null character ‘\
0’. The null character indicates the end of the string.
Any array of character can be converted into string type in C++ by appending this
special/null character ‘\0’at the end of the array sequence.
Hence if a string has n characters then it requires an n+1 element array (at least) to store it.
Thus the character `a' is stored in a single byte, whereas the single-character string "a" is
stored in two consecutive bytes holding the character `a' and the null character.

A string variable Str1 could be declared as follows:


char Str1[10];
The string variable Str1 could hold strings of length up to nine characters since space is
needed for the final null character. Strings can be initialized at the time of declaration just
as other variables are initialized.
For example: char str1 [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char str2[] = "Hello";
For example:
char Str1[] = "Hello!";
char Str2[18] = "C++ Programming";

Would store the above two strings as follows:


H e l l O ! \ Str1
0
C + + P r o g r a m m i n g \0 Str2

In the first case the array would be allocated space for seven characters that is sixth spaces
for the string Hello! & one for the null character. In the second case the string is set by the
declaration to be 18 characters long but only sixteen of these characters are set, i.e. the
fourteen characters of the string, one for space and the null character.

4.3.1. String Output

A string is output by sending it to an output stream, for example:


cout << "The string s1 is " << Str1 << endl; //would print The string Str1 is Hello!
The setw(width) I/O manipulator can be used before outputting a string, the string will then
be output right-justified in the field width.

4.3.2. String Input


When the input stream cin is used space characters, n space, tab, newline etc. are used
as separators and terminators.
To read a string with several words in it using cin we have to call cin.
To read in a name in the form of first name followed by a last name
char firstname[12], lastname[12];
cout << "Enter First name and Last name: ";
cin >> firstname
cin>>lastname;
cout << "The Name Entered was "
<< firstname << " "
<< lastname;
The cin>> considers a space to be a terminating character & read strings of a single word.
To read text containing blanks we use another function, cin::get().
#include<iostream.h>
void main()
{
const int max=80;
char str[max];
cout<<"\n Enter a string;";
cin.get(str,max); // max avoid buffer overflow
cout<<"\n You entered : "<<str;
}

Reading strings with multiple lines.


//reads multiple lines, terminates on '$' character
#include<iostream.h>
void main()
{
const int max=80;
char str[max];
cout<<"\n Enter a string:\n";
cin.get(str, max, '$'); //terminates with $
cout<<\n You entered:\n"<<str;
}
Type as many lines of input & enter the terminated character $ when you finish typing
& press Enter.

4.3.3. String constants


Initializing a string to a constant value when defining
#include<iostream.h>
void main(){
char str[] = "Welcome to C++ Programming Language";
cout<<str;
}
The best way to understand the true nature of strings is to deal with them character by
character
#include<iostream.h>
#include<string.h> //for strlen()
void main()
{
const int max=80;
char str1[]='' Hello World! Well Come To "
C++ Programming!";
char str2[max];
for(int i=0; i<strlen(str1);i++)
str2[i]=str1[1];
str2[i]='\0';
cout<<endl;
cout<<str2;
}
4.3.4. Copying string the easy way
A library function strcpy or strncpy is used to copy string without using for loop. Assign
strings by using the string copy function strcpy.
Syntax: strcpy(destination, source);
strcpy copies characters from the location specified by source to the location specified by
destination.
It stops copying characters after it copies the terminating null character.
Example:
#include <iostream.h>
#include <string.h>
void main(){
char asu[20] = "Computer Scince";
cout << me << endl;
strcpy(asu, "Information Science");
cout << asu << endl ;
return; // The return value is the value of the destination parameter.
}

There is also another function strncpy, is like strcpy, except that it copies only a specified
number of characters.
Syntax: strncpy(destination, source, int n); //It may not copy the terminating null
character.
Example
#include <iostream.h>
#include <string.h>
int main() {
char str1[] = "String test";
char str2[] = "Hello";
char one[10];
strncpy(one, str1, 9);
one[9] = '\0';
cout << one << endl;
strncpy(one, str2, 2);
cout << one << endl;
strcpy(one, str2);
cout << one << endl;
return 0;
}
Concatenating string
The strcat() or strncat are used for for concatenating strings.
The function strcat concatenates (appends) one string to the end of another string.
strcat(destination, source);
Example:
#include <iostream.h>
#include <string.h>
int main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strcat(str1, "def");
cout << str1 << endl;
char str2[] = "xyz";
strcat(str1, str2);
cout << str1 << endl;
str1[4] = '\0';
cout << str1 << endl;
return 0;
}

The function strncat is like strcat except that it copies only a specified number of characters.
strncat(destination, source, int n); // It may not copy the terminating null character.

Example:
#include <iostream.h>
#include <string.h>
int main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strncat(str1, "def", 2);
str1[5] = '\0';
cout << str1 << endl;
char str2[] = "xyz";
strcat(str1, str2);
cout << str1 << endl;
str1[4] = '\0';
cout << str1 << endl;
return 0;
}

4.3.5. Comparing strings


Strings can be compared using strcmp or strncmp functions
The function strcmp compares two strings.
strcmp(str1, str2); //Compares str1 with str2
Example:
#include <iostream.h>
#include <string.h>
int main()
{
cout << strcmp("abc", "def") << endl; //compares abc with def
cout << strcmp("abc", "ABC") << endl; //compares abc with ABC
return 0;
}
The function strncmp is like strcmp except that it compares only a specified number of
characters.
strncmp(str1, str2, int n);
strncmp does not compare characters after a terminating null character has been found in
one of the strings.
Example:
#include <iostream.h>
#include <string.h>
void main()
{
cout << strncmp("abc", "def", 2) << endl;
cout << strncmp("abc", "abcdef", 5) << endl;
}

Pointers
______________________________________________________________________________
A pointer is simply the address of a memory location and provides an indirect
way of accessing data in memory. A pointer variable is defined to ‘point to’
data of a specific type. For example:
int *ptr1; // pointer to an int
char *ptr2; // pointer to a char
The value of a pointer variable is the address to which it points. For example,
given the definitions
int num; //can be written as ptr1 = &num;
The symbol & is the address operator; it takes a variable as argument and
returns the memory address of that variable. The assignment ptr1 = &num; is
that the address of num is assigned to ptr1. Therefore, ptr1 points to num.

Diagrammatically,
Given that ptr1 points to num, the expression *ptr1 dereferences ptr1 to get
to what it points to, and is equivalent to num.
The symbol * is the dereference operator; it takes a pointer as argument and
returns the contents of the location to which it points.
Example 1: Write C++ Program that finds the square of a number
//Demonstration of Pointers
#include<iostream.h>
#include<math.h>
int main()
{
double num=25;
double *p1, *p2, *sq;
p1 = &num;
p2= &num;
sq=&num;

cout<<"\n Value of num: "<<*p1; // Content of num 25


cout<<"\n Value of num: "<<*p2; // Content of num 25
cout<<"\n Value of num: "<<*sq; // Content of num 25
cout<<"\n SQRT of num: "<<sqrt(*p1); // Square root of num 5
cout<<"\n SQRT of num: "<<sqrt(*p2); // Square root of num 5
cout<<"\n SQRT of num: "<<sqrt(*sq); // Square root of num 5
return 0;
}
Example 2: Write C++ Program that displays contents of array
#include<iostream.h>
#include<math.h>
int main()
{
int N[] = { 10,20,30,40,50,60};
int *ptr = N; // or int *ptr = &N[0];
cout<<"\n Displaying array contents using array\n ";
for(int i=0; i<6; i++)
{
cout<<N[i]<<" "; //using array
}
cout<<"\n Displaying array contents using pointer\n ";
for(int i=0; i<6; i++)
{
cout<<*(ptr+i)<<" "; //using pointer
}

cout<<"\n Displaying array contents using pointer\n ";

for( ptr= &N[0]; ptr<=&N[5]; ptr++)


{
cout<<*ptr<<" "; //using pointer
}
return 0;
}

Dynamic Memory Allocation (DMA)


Two operators are used for allocating and deallocating memory blocks. The
new and delete operators. The new operator takes a type as argument and
allocated a memory block for an object of that type. It returns a pointer to the
allocated block. For example,
int *ptr = new int; // Allocate a block for storing a single integer
char *str = new char[10]; //Allocate a block large enough for storing an array
of 10 characters.
The delete operator is used for releasing memory blocks allocated by new. It
takes a pointer as argument and releases the memory block to which it points.
For example:
delete ptr; // delete an object
delete [] str; // delete an array of objects
Note that when the block to be deleted is an array, an additional [] should be
included to indicate.
It is harmless to apply delete to the 0 pointer.
Example of DMA
Write C++ program that performs addition of two numbers and outputs the
sum using DMA
//Demonstration of DMA
#include<iostream.h>
int main()
{
int *x = new int; // allocate memory for single int
int *y = new int; // " " "
int *sum = new int;
*x=5, *y=7;
*sum = *x+*y;
cout<<"\n Sum="<<*sum;
delete x;
delete y;
delete sum;
return 0;
}

Write C++ program that accepts array elements and displays them to console
using DMA
//Demonstration of DMA
//Demonstration of DMA
#include<iostream.h>
int main()
{
int *N = new int[20]; // Allocate memory for 20 ints dynamically
int *n = new int; // Allocate memory for single int dynamically
cout<<"\n Enter the number of Array elements: ";
cin>>*n;
cout<<"\n Inserting array contents using DMA\n ";
for(int i=0;i<*n;i++)
{
cout<<"\n Enter Element "<<i+1<<": ";
cin>>N[i];
}
cout<<"\n Displaying array contents using DMA\n ";
for(int i=0;i<*n;i++)
{
cout<<N[i]<<" ";
}
delete [] N;
delete n;
return 0;
}

Pointer Arithmetic
Pointer arithmetic means performing mathematical calculations using
pointers but not the same as integer arithmetic, because the outcome depends
on the size of the object pointed to. For example, an int is represented by 4
bytes. Now, given
char *str = "HELLO";
int nums[] = {10, 20, 30, 40};
int *ptr = &nums[0]; // pointer to first element
str++ advances str by one char (i.e., one byte) so that it points to the second
character of "HELLO", whereas ptr++ advances ptr by one int (i.e., four bytes)
so that it points to the second element of nums.
The elements of "HELLO" can be referred to as *str, *(str + 1), *(str + 2), etc.
Similarly, the elements of nums can be referred to as *ptr, *(ptr + 1), *(ptr + 2),
and *(ptr + 3).
Another form of pointer arithmetic allowed in C++ involves subtracting two
pointers of the same type. For example:
int *ptr1 = &nums[1];
int *ptr2 = &nums[3];
int n = ptr2 - ptr1; // n becomes 2
//Addition of two numbers using pointers
#include<iostream.h>
int main() {
int x,y,sum=0;
int *p1 = &x,*p2 = &y;
int *s = &sum;
cout<<”\n Enter Value of x: ”;
cin>>*p1;

cout<<”\n Enter Value of y: ”;


cin>>*p2;
*s = *p1+*p2;
cout<<”\n The Sum x+ y= ”<<*s;
return 0;
}
Function Pointers
It is possible to take the address of a function and store it in a function
pointer. The pointer can then be used to indirectly call the function.
//Demonstration of Passing Pointers by Value and Pass by Reference
#include<iostream.h>
void Swap1 (int x, int y) // pass-by-value (objects)
{
int temp = x;
x = y;
y = temp;
}
void Swap2 (int *x, int *y) // pass-by-value (pointers)
{
int temp = *x;
*x = *y;
*y = temp;
}
void Swap3 (int &x, int &y) // pass-by-reference (address)
{
int temp = x;
x = y;
y = temp;
}
int main (void) //void indicates the function take no argument
{
int i = 10, j = 20;
Swap1(i, j); cout << i << ", " << j << '\n';
Swap2(&i, &j); cout << i << ", " << j << '\n';
Swap3(i, j); cout << i << ", " << j << '\n';
}
//Output
10,20
20,10
10,20

You might also like