0% found this document useful (0 votes)
5 views38 pages

Chapter 4_Array (1)

Chapter 4 covers arrays in programming, explaining their structure, declaration, initialization, and access methods. It details one-dimensional and multidimensional arrays, including how to copy and manipulate them. Additionally, the chapter discusses string handling and various string manipulation functions in C++.

Uploaded by

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

Chapter 4_Array (1)

Chapter 4 covers arrays in programming, explaining their structure, declaration, initialization, and access methods. It details one-dimensional and multidimensional arrays, including how to copy and manipulate them. Additionally, the chapter discusses string handling and various string manipulation functions in C++.

Uploaded by

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

Chapter – 4

Arrays
INTRODUCTION
 Array - a collection of a fixed number of components
where all of the components have the same data type
 Arrays in general are
– Structures of related data items

– Same name and type (int, char, double, float etc.)


 An individual element of an array is identified by its own
unique index (or subscript).
 The index must be an integer and indicates the position of
the element in the array
Cont…
ONE DIMENTIONAL ARRAYS

Declaration Of Arrays
When declaring arrays, specify
Data Type of array:-Any data type
Name of array
Number of elements(should be
constant number)

Syntax:
type arrayName[arraySize ];
Example:
int list[ 10 ];
float d[ 3284 ];
Accessing Array Elements

 An array element is accessed by writing the identifier of the array


followed by the index(subscript ) in square brackets.
 first element is at index 0, then the ith element is at index (i-1).

 A one-dimensional array is usually processed via a for loop.


 for giving inputs
 for accessing values and calculations
 for displaying
Initializing arrays

 Specify each element when array declared


int n[ 5 ] = { 1, 2, 3, 4, 5 };
Array size must be greater than or equal to the number of
elements in the initialization list.
If the size is greater, initializes rightmost elements to 0
But array index must always be greater than or equal to
the number of elements in the initialization unless error
will occur.
 To set every element to same value
int n[ 5 ] = { 0 };//or int n[ 5 ] = { };
 If array size omitted, initializes determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializes, therefore 5 element array
1 // Program :Initializing an array with a declaration.
2 //What is the output of the following program?
3 #include<iostream>
4 #include<iomanip>
5 using namespace std;
6 int main()
7 {
8 int n[ 10]={32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
9 cout <<"Element"<< setw( 13 ) << "Value" << endl;
10 for (int i=0; i<10; i++ )
11 cout <<setw(7)<< i <<setw(13)<<n[i]<< endl;
12 return 0;
13 }
Output:
Element Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
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 using the index operator,

e.g…, x[1] = y[2]


 Loop to do copying, one element at a time

for(int i = 0 ; i < SIZE; i++)

x[i] = y[i];
MULTIDIMENSIONAL ARRAYS
 C++ also allows an array to have more than one dimension.

 For example, a two-dimensional array consists of a certain number of rows


and columns:

const int NUMROWS = 3;

const int NUMCOLS = 7;

int Array[NUMROWS][NUMCOLS];
Initializing Multidimensional Arrays

 A two-dimensional array may be processed with a nested for loop:


 for giving inputs
 for accessing values and calculations
 for displaying

for (int Row = 0; Row < NUMROWS; Row++)

for (int Col = 0; Col < NUMCOLS; Col++)

Array[Row][Col] = 0;

}
Coloumn
What is the output of the following program?
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int row=2, column=3;
int array[row][column]={{1,2,3},{4,5,6}};
cout<<"The result is as shown below:"<<endl;
for(int row=0;row<2;row++)
{for(int column=0;column<3;column++)
cout<<array[row][column]<<" ";
cout<<endl;}
return 0;
}
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 and is not allowed. and must be written

int x[2][2] = { {1,2}, {3,4}};


Example : What is the output of the ff
program?
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int MyArray[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<<"MyArray["<<i<<"]["<<j<<"] ="<<setw(10)<<MyArray[i][j];
cout<<endl;
}
return 0;}
Example 1:Matrix addition

Write a c++ program that adds array P and Q?


char name[20];
N.B 1.we need not initialize all the available space (20)
2.the string will terminate by the null character ‘\0’
 Initialization
char my_string[]={‘H’,’e’,’l’,’k’,’o’,’\0’’};
or char my_string[]=”Hello”
once initialized we can not use the following:
my_string[]=”hello”;
my_string=”Hello”;
my_string[]={‘H’,’e’,’l’,’l’,’o’,’\0’’};
 but we can say
my_string [0]=’H’;
my_string[3]=’k’;
cout<< my_string[2];
cout<<my_string;
cin>> my_string;
Cont…
With cin space will not be read.
Hence use the following
cin.getline(char buffer[],int )

Address to store input Max length


Eg. // cin with strings
#include<iostream>

#include <string>

Using namespace std;

int main () {

char mystr[100];

cout << "What's your name? “<<endl;

cin.getline(mystr,100);

cout << "Hello " << mystr << ".\n";

cout << "What is your favorite team? “<<endl;

cin.getline(mystr,100);
String Manipulations:
Functions to manipulate strings:
Requires string header file in standard c++ and string.h in pre-standard c++.

i)strlen (char buffer[] ) =>retuns the length without the null character ‘\0’;
int main () {
char name[50] = "Abebe Kebede";
int len1, len2;
len1 = strlen(name); // 12
len2 = strlen("Hello World"); // 11
cout<<len1<<" "<<len2;
return 0; }
String concatenation
=>to concatenate or merge two strings

NB. 1.Tii)strcat(str1, str2) the first string str1 hold the concatenated
string

2.the size of the first string must be large enough to hold both
strings.

int main()

{char str1[13] = "Hello ";

char str2[] = "World!"

cout<<"Before: "<<str1<<endl;

cout<<"Before: "<<str2<<endl;

strcat(str1, str2);

cout<<"After: "<<str1<<endl;
String compare
iii)strcmp(str1,str2) => for lexical/alphabetica
comparison rule:
 0 if the two strings are equal
 negative if the first string comes before the
second in alphabetical order
 positive if the first string comes after the second in
alphabetical order
String copy
iv) strcpy(str1,str2): is used to copy one string to
another. This is because arrays can't be copied using
the assignment operator (=).
Example:
char str1[20];
char str2[] = "Second String";
strcpy(str1, str2);
cout<<"str1: "<<str1<<endl;
strcpy(str2, "Another String");
cout<<"str2: "<<str2<<endl;
String/Numeric
Conversion
i)atoi= string to int i)itoa int to string

ii)atof=string to float ii)ftoi float to string

iii)atoll=string to long iii)ltoa long to string


Cont…
Eg.
 int num = atoi("4123"); //num = 4123
 long lnum = atol ("12345678");
 float fnum = atof ("2.34");
 itoa (not standard): converts an integer to a string. It
accepts three arguments
argument1 - the integer to be converted
argument2 - the string to hold the converted result
argument3 - the base (8, 10, or 16)
char strnum[4];
itoa(102, strnum, 10);
`

• END OF CHAPTER 4

You might also like