SlideShare a Scribd company logo
1 of 35
• Arrays and Strings in C++
Arrays
• So far we have used variables to store values in memory for later reuse. We
now explore a means to store multiple values together as one unit, the array.
• An array is a fixed number of elements of the same data type stored
sequentially in memory.
• Therefore, an integer array holds some number of integers, a character array
holds some number of characters, and so on.
• The size of the array is referred to as its dimension.
• To declare an array in C++, we write as follows:
type arrayName[dimension];
• To declare an integer array named arr of four elements, we write
int arr[4];
• The elements of an array can be accessed by using an index into
the array.
• Arrays in C++ are zero-indexed, so the first element has an index
of 0.
• So, to access the third element in arr, we write arr[2]; The value
returned can then be used just like any other integer.
Initializing an Arrays
• There are several ways to initialize the array. One way is to
declare the array and then initialize some or all of the elements:
int arr[4];
arr[0] = 6;
arr[1] = 0;
arr[2] = 9;
arr[3] = 6;
• Another way is to initialize some or all of the values at the time
of declaration:
int arr[4] = { 6, 0, 9, 6 };
• Sometimes it is more convenient to leave out the size of the array
and let the compiler determine the array's size for us, based on
how many elements we give it:
int arr[] = { 6, 0, 9, 6, 2, 0, 1, 1 };
• Here, the compiler will create an integer array of dimension 8.
The array can also be initialized with values that are not known beforehand:
#include <iostream>
using namespace std;
int main( )
{
int i, arr[4];
cout <<"Please enter 4 integers:" << endl;
for(i = 0; i < 4; i++){
cin >> arr[i];
}
cout << "Values in array are now:";
for(i = 0; i < 4; i++){
cout << " " << arr[i] << endl;
}
}
#include<iostream>
using namespace std;
int main( )
{
int i, avg, sum = 0 ;
int marks[10] ; /* array declaration */
for ( i = 0 ; i <= 9; i++ )
{
cout<<"n Enter marks " ;
cin>>marks[i] ; /* store data in array */
}
for ( i = 0 ; i <= 9 ; i++ ) {
sum = sum + marks[i] ; /* read data from an array*/ }
avg = sum / 10 ;
cout<< "n Average marks = "<<avg;
return 0; }
/*Write a program to get n numbers and find out sum and average of numbers*/
#include<iostream>
using namespace std;
int main( ) {
int a[100], i, n; //array of size n
float avg, sum=0;
cout<<“Enter total number of elements : ”;
cin>>n;
for(i=0; i<n; i++) {
cout<<“Enter the number<<“endl”;
cin>>a[i];
sum = sum + a[i];
}
avg=sum/n;
cout<<“Array elements are :”<<endl;
for(i=0; i<n; i++){
cout<< a[i])<<endl; }
cout<<“Sum = “<<sum <<“Average = “<<avg;
return 0;
}
//Program to find the largest element in an array
#include<iostream>
using namespace std;
int main() {
int a[50], size, i, big;
cout<<“nEnter size of the array : ”;
cin>>size;
cout<<“nEnter <<size<<“elements in to the array : ”;
for(i=0; i<size; i++) {
cin>>a[i]; }
big=a[0];
for(i=1; i<size; i++){
if(big<a[i])
big=a[i];}
cout<<“nThe biggest element is ”<<big;
return 0;}
• Note that when accessing an array the index given must be a
positive integer from 0 to n-1, where n is the dimension of the
array. The index itself may be directly provided, derived from a
variable, or computed from an expression:
arr[5];
arr[i];
arr[i+3];
• Arrays can also be passed as arguments to functions.
• When declaring the function, simply specify the array as a
parameter, without a dimension. The array can then be used as
normal within the function. For example:
#include <iostream>
using namespace std;
int sum(const int array[ ], const int length) {
long sum = 0;
for(int i = 0; i < length; sum += array[i++]);
return sum;
}
int main( ) {
int arr[ ] = {1, 2, 3, 4, 5, 6, 7};
cout << "Sum: " << sum(arr, 7) << endl;
return 0;
}
• C++ supports the creation of multidimensional arrays, through the
addition of more than one set of brackets.
• Thus, a two-dimensional array may be created as follows:
type arrayName[dimension1][dimension2];
• The array will have dimension1 x dimension2 elements of the same
type and can be thought of as an array of arrays.
• The first index indicates which of dimension1 sub-arrays to access,
and then the second index accesses one of dimension2 elements
within that sub-array.
• Initialization and access are similar to the one-dimensional case:
#include <iostream>
using namespace std;
int main() {
int twoDimArray[2][4];
twoDimArray[0][0] = 6;
twoDimArray[0][1] = 0;
twoDimArray[0][2] = 9;
twoDimArray[0][3] = 6;
twoDimArray[1][0] = 2;
twoDimArray[1][1] = 0;
twoDimArray[1][2] = 1;
twoDimArray[1][3] = 1;
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 4; j++)
{
cout << twoDimArray[i][j];
}
}
cout << endl;
return 0;
}
The array can also be initialized at declaration in the following ways:
int twoDimArray[2][4] = { 6, 0, 9, 6, 2, 0, 1, 1 };
int twoDimArray[2][4] = { { 6, 0, 9, 6 } , { 2, 0, 1, 1 } };
Examples #include<iostream>
using namespace std;
int main( )
{
/* An array with 5 rows and 2 column */
int a[5][2] = {{0,0},{1,2},{2,4},{3,6},{4,8}};
int i, j;
/* output each array element’s value */
for(i=0; i<5; i++){
for(j=0; j<2; j++){
cout<<a[i][j]<<endl”;
}
}
return 0;
}
#include<stdio.h>
using namespace std;
int main( )
{
int disp[3][5];
int i, j;
for(i=0; i<=2; i++)
{
for(j=0;j<=4;j++)
{
cout<<"Enter value for disp[3][5]: "<<endl;
cin>>disp[i][j]);
}
}
return 0;
}
/*Write a program to read 3*3 matrix and
find maximum number*/
#include<iostream>
using namespace std;
#include<conio.h>
int main()
{
int mat[3][3], i, j, max;
cout<<"Enter any 3*3 matrix: "<<endl;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
cin>>mat[i][j];
}
}
max = mat[0][0];
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
if(max<mat[i][j])
max = mat[i][j];
}
}
cout<<"nLargest Element = "<<max;
getch();
return 0;
}
Strings
• String literals such as “Hello, world!” are actually represented by
C++ as a sequence of characters in memory.
• In other words, a string is simply a character array and can be
manipulated as such.
• Consider the following program:
#include <iostream>
using namespace std;
int main()
{
char helloworld[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '0' };
cout << helloworld << endl;
return 0;
}
• This program prints Hello, world! Note that the character array
helloworld ends with a special character known as the null
character. This character is used to indicate the end of the string.
• Character arrays can also be initialized using string literals. In this
case, no null character is needed, as the compiler will
automatically insert one:
char helloworld[] = “Hello, world!”;
Reading words from user.
#include <iostream>
using namespace std;
int main()
{
char name[20];
cout<<"Enter your name: ";
cin>>name;
cout<<"Your name is “<<name;
return 0;
}
#include <iostream>
using namespace std;
int main( )
{
char name[30];
cout<<"Enter your full name: ";
gets(name); //Function to read string from user.
cout<<"Your Full Name is: ";
puts(name); //Function to display string.
system("pause");
return 0;
}
The individual characters in a string can be manipulated either
directly by the programmer or by using special functions provided by
the C/C++ libraries. These can be included in a program through the
use of the #include directive.
Of particular note are the following:
 cctype (ctype.h) : character handling
 cstdio (stdio.h) : input/output operations
 cstdlib (stdlib.h) : general utilities
 cstring (string.h) : string manipulation
Here is an example to illustrate the
cstring library:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char fragment1[] = "I'm a s";
char fragment2[] = "tring!";
char fragment3[20];
char finalString[20] = "";
strcpy(fragment3, fragment1);
strcat(finalString, fragment3);
strcat(finalString, fragment2);
cout << finalString;
return 0;
}
strlen()
Syntax:
temp_variable = strlen(string_name);
Function strlen() returns the value of type integer.
#include<iostream>
#include<string>
using namespace std;
int main()
{
char name[50];
int len;
cout<<"Enter your String not more than 50 ";
cout<<"character::";
gets(name);
len=strlen(name);
cout<<"The Length of String is "<<len<<endl;
return 0;
}
#include<iostream>
#include <string.h>
#include <conio.h>
using namespace std;
int main()
{
char name[30]= "hello whatssup";
cout<<"nString is "<<name;
cout<<"The length of string is "<<strlen(name);
getch();
return 0;
}
strcpy()
• Function strcpy() copies the content of one string to the
content of another string. It is defined under "string.h"
header file.
• It takes two arguments.
Syntax of strcpy()
strcpy(destination, source);
• Here, source and destination are both the name of the
string. This statement, copies the content of string
source to the content of string destination.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char a[10], b[10];
cout<<"Enter string: ";
gets(a);
strcpy(b, a); //Content of string a is copied to string b.
cout<<"Copied string: "<<endl;
puts(b);
return 0;
}
strcat()
In C++ programming, strcat() concatenates(joins) two strings.
It takes two arguments, i.e, two strings and resultant string is
stored in the first string specified in the argument.
Function strcat() is defined under "string.h" header file.
Syntax of strcat()
strcat(first_string, second_string);
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char name[10], name1[10];
//clrscr();
cout<<"Enter the First string t";
gets(name);
cout<<"Enter the Second string t";
gets(name1);
strcat(name,name1);
cout<<"The string after concatenations is "<<endl<<name;
return 0;
}
strrev ()
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
char name[10];
cout<<"Enter the String ";
gets(name);
strrev(name);
cout<<"The String after reverse isn "<<name;
getch();
return 0;
}
strcmp ()
#include <iostream>
#include <string.h>
#include<conio.h>
using namespace std;
int main()
{
char *str1 = "sample", *str2 = "sample";
if(strcmp(str1, str2)==0)
cout<<"strings are equal";
else
cout<<"strings are not equal";
getch();
return 0;
}

More Related Content

Similar to Array and string in C++_093547 analysis.pptx

I have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdfI have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdf
shreeaadithyaacellso
 
2DArrays.ppt
2DArrays.ppt2DArrays.ppt
2DArrays.ppt
Nooryaseen9
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
ch9_additional.ppt
ch9_additional.pptch9_additional.ppt
ch9_additional.ppt
LokeshK66
 

Similar to Array and string in C++_093547 analysis.pptx (20)

Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Arrays & Strings.pptx
Arrays & Strings.pptxArrays & Strings.pptx
Arrays & Strings.pptx
 
I have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdfI have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdf
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 
Array BPK 2
Array BPK 2Array BPK 2
Array BPK 2
 
SP-First-Lecture.ppt
SP-First-Lecture.pptSP-First-Lecture.ppt
SP-First-Lecture.ppt
 
Array assignment
Array assignmentArray assignment
Array assignment
 
2DArrays.ppt
2DArrays.ppt2DArrays.ppt
2DArrays.ppt
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Unit 2
Unit 2Unit 2
Unit 2
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
ch9_additional.ppt
ch9_additional.pptch9_additional.ppt
ch9_additional.ppt
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
 
Session 4
Session 4Session 4
Session 4
 
SlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdfSlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdf
 

Recently uploaded

Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
AldoGarca30
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
pritamlangde
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
HenryBriggs2
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
Kamal Acharya
 

Recently uploaded (20)

HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdf
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
 
👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...
👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...
👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
 
Signal Processing and Linear System Analysis
Signal Processing and Linear System AnalysisSignal Processing and Linear System Analysis
Signal Processing and Linear System Analysis
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptx
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth Reinforcement
 
Computer Graphics Introduction To Curves
Computer Graphics Introduction To CurvesComputer Graphics Introduction To Curves
Computer Graphics Introduction To Curves
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 

Array and string in C++_093547 analysis.pptx

  • 1. • Arrays and Strings in C++
  • 2. Arrays • So far we have used variables to store values in memory for later reuse. We now explore a means to store multiple values together as one unit, the array. • An array is a fixed number of elements of the same data type stored sequentially in memory. • Therefore, an integer array holds some number of integers, a character array holds some number of characters, and so on. • The size of the array is referred to as its dimension. • To declare an array in C++, we write as follows: type arrayName[dimension];
  • 3. • To declare an integer array named arr of four elements, we write int arr[4]; • The elements of an array can be accessed by using an index into the array. • Arrays in C++ are zero-indexed, so the first element has an index of 0. • So, to access the third element in arr, we write arr[2]; The value returned can then be used just like any other integer.
  • 4. Initializing an Arrays • There are several ways to initialize the array. One way is to declare the array and then initialize some or all of the elements: int arr[4]; arr[0] = 6; arr[1] = 0; arr[2] = 9; arr[3] = 6;
  • 5. • Another way is to initialize some or all of the values at the time of declaration: int arr[4] = { 6, 0, 9, 6 }; • Sometimes it is more convenient to leave out the size of the array and let the compiler determine the array's size for us, based on how many elements we give it: int arr[] = { 6, 0, 9, 6, 2, 0, 1, 1 }; • Here, the compiler will create an integer array of dimension 8.
  • 6. The array can also be initialized with values that are not known beforehand: #include <iostream> using namespace std; int main( ) { int i, arr[4]; cout <<"Please enter 4 integers:" << endl; for(i = 0; i < 4; i++){ cin >> arr[i]; } cout << "Values in array are now:"; for(i = 0; i < 4; i++){ cout << " " << arr[i] << endl; } }
  • 7. #include<iostream> using namespace std; int main( ) { int i, avg, sum = 0 ; int marks[10] ; /* array declaration */ for ( i = 0 ; i <= 9; i++ ) { cout<<"n Enter marks " ; cin>>marks[i] ; /* store data in array */ } for ( i = 0 ; i <= 9 ; i++ ) { sum = sum + marks[i] ; /* read data from an array*/ } avg = sum / 10 ; cout<< "n Average marks = "<<avg; return 0; }
  • 8. /*Write a program to get n numbers and find out sum and average of numbers*/ #include<iostream> using namespace std; int main( ) { int a[100], i, n; //array of size n float avg, sum=0; cout<<“Enter total number of elements : ”; cin>>n; for(i=0; i<n; i++) { cout<<“Enter the number<<“endl”; cin>>a[i]; sum = sum + a[i]; } avg=sum/n; cout<<“Array elements are :”<<endl; for(i=0; i<n; i++){ cout<< a[i])<<endl; } cout<<“Sum = “<<sum <<“Average = “<<avg; return 0; }
  • 9. //Program to find the largest element in an array #include<iostream> using namespace std; int main() { int a[50], size, i, big; cout<<“nEnter size of the array : ”; cin>>size; cout<<“nEnter <<size<<“elements in to the array : ”; for(i=0; i<size; i++) { cin>>a[i]; } big=a[0]; for(i=1; i<size; i++){ if(big<a[i]) big=a[i];} cout<<“nThe biggest element is ”<<big; return 0;}
  • 10. • Note that when accessing an array the index given must be a positive integer from 0 to n-1, where n is the dimension of the array. The index itself may be directly provided, derived from a variable, or computed from an expression: arr[5]; arr[i]; arr[i+3];
  • 11. • Arrays can also be passed as arguments to functions. • When declaring the function, simply specify the array as a parameter, without a dimension. The array can then be used as normal within the function. For example:
  • 12. #include <iostream> using namespace std; int sum(const int array[ ], const int length) { long sum = 0; for(int i = 0; i < length; sum += array[i++]); return sum; } int main( ) { int arr[ ] = {1, 2, 3, 4, 5, 6, 7}; cout << "Sum: " << sum(arr, 7) << endl; return 0; }
  • 13. • C++ supports the creation of multidimensional arrays, through the addition of more than one set of brackets. • Thus, a two-dimensional array may be created as follows: type arrayName[dimension1][dimension2]; • The array will have dimension1 x dimension2 elements of the same type and can be thought of as an array of arrays. • The first index indicates which of dimension1 sub-arrays to access, and then the second index accesses one of dimension2 elements within that sub-array. • Initialization and access are similar to the one-dimensional case:
  • 14. #include <iostream> using namespace std; int main() { int twoDimArray[2][4]; twoDimArray[0][0] = 6; twoDimArray[0][1] = 0; twoDimArray[0][2] = 9; twoDimArray[0][3] = 6; twoDimArray[1][0] = 2; twoDimArray[1][1] = 0; twoDimArray[1][2] = 1; twoDimArray[1][3] = 1; for(int i = 0; i < 2; i++) { for(int j = 0; j < 4; j++) { cout << twoDimArray[i][j]; } } cout << endl; return 0; }
  • 15. The array can also be initialized at declaration in the following ways: int twoDimArray[2][4] = { 6, 0, 9, 6, 2, 0, 1, 1 }; int twoDimArray[2][4] = { { 6, 0, 9, 6 } , { 2, 0, 1, 1 } };
  • 16. Examples #include<iostream> using namespace std; int main( ) { /* An array with 5 rows and 2 column */ int a[5][2] = {{0,0},{1,2},{2,4},{3,6},{4,8}}; int i, j; /* output each array element’s value */ for(i=0; i<5; i++){ for(j=0; j<2; j++){ cout<<a[i][j]<<endl”; } } return 0; }
  • 17. #include<stdio.h> using namespace std; int main( ) { int disp[3][5]; int i, j; for(i=0; i<=2; i++) { for(j=0;j<=4;j++) { cout<<"Enter value for disp[3][5]: "<<endl; cin>>disp[i][j]); } } return 0; }
  • 18. /*Write a program to read 3*3 matrix and find maximum number*/ #include<iostream> using namespace std; #include<conio.h> int main() { int mat[3][3], i, j, max; cout<<"Enter any 3*3 matrix: "<<endl; for(i=0; i<3; i++) { for(j=0; j<3; j++) { cin>>mat[i][j]; } } max = mat[0][0]; for(i=0; i<3; i++) { for(j=0; j<3; j++) { if(max<mat[i][j]) max = mat[i][j]; } } cout<<"nLargest Element = "<<max; getch(); return 0; }
  • 19. Strings • String literals such as “Hello, world!” are actually represented by C++ as a sequence of characters in memory. • In other words, a string is simply a character array and can be manipulated as such. • Consider the following program:
  • 20. #include <iostream> using namespace std; int main() { char helloworld[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '0' }; cout << helloworld << endl; return 0; }
  • 21. • This program prints Hello, world! Note that the character array helloworld ends with a special character known as the null character. This character is used to indicate the end of the string. • Character arrays can also be initialized using string literals. In this case, no null character is needed, as the compiler will automatically insert one: char helloworld[] = “Hello, world!”;
  • 23. #include <iostream> using namespace std; int main() { char name[20]; cout<<"Enter your name: "; cin>>name; cout<<"Your name is “<<name; return 0; }
  • 24. #include <iostream> using namespace std; int main( ) { char name[30]; cout<<"Enter your full name: "; gets(name); //Function to read string from user. cout<<"Your Full Name is: "; puts(name); //Function to display string. system("pause"); return 0; }
  • 25. The individual characters in a string can be manipulated either directly by the programmer or by using special functions provided by the C/C++ libraries. These can be included in a program through the use of the #include directive. Of particular note are the following:  cctype (ctype.h) : character handling  cstdio (stdio.h) : input/output operations  cstdlib (stdlib.h) : general utilities  cstring (string.h) : string manipulation
  • 26. Here is an example to illustrate the cstring library: #include <iostream> #include <string.h> using namespace std; int main() { char fragment1[] = "I'm a s"; char fragment2[] = "tring!"; char fragment3[20]; char finalString[20] = ""; strcpy(fragment3, fragment1); strcat(finalString, fragment3); strcat(finalString, fragment2); cout << finalString; return 0; }
  • 27. strlen() Syntax: temp_variable = strlen(string_name); Function strlen() returns the value of type integer.
  • 28. #include<iostream> #include<string> using namespace std; int main() { char name[50]; int len; cout<<"Enter your String not more than 50 "; cout<<"character::"; gets(name); len=strlen(name); cout<<"The Length of String is "<<len<<endl; return 0; }
  • 29. #include<iostream> #include <string.h> #include <conio.h> using namespace std; int main() { char name[30]= "hello whatssup"; cout<<"nString is "<<name; cout<<"The length of string is "<<strlen(name); getch(); return 0; }
  • 30. strcpy() • Function strcpy() copies the content of one string to the content of another string. It is defined under "string.h" header file. • It takes two arguments. Syntax of strcpy() strcpy(destination, source); • Here, source and destination are both the name of the string. This statement, copies the content of string source to the content of string destination.
  • 31. #include <iostream> #include <string.h> using namespace std; int main() { char a[10], b[10]; cout<<"Enter string: "; gets(a); strcpy(b, a); //Content of string a is copied to string b. cout<<"Copied string: "<<endl; puts(b); return 0; }
  • 32. strcat() In C++ programming, strcat() concatenates(joins) two strings. It takes two arguments, i.e, two strings and resultant string is stored in the first string specified in the argument. Function strcat() is defined under "string.h" header file. Syntax of strcat() strcat(first_string, second_string);
  • 33. #include<iostream> #include<string.h> using namespace std; int main() { char name[10], name1[10]; //clrscr(); cout<<"Enter the First string t"; gets(name); cout<<"Enter the Second string t"; gets(name1); strcat(name,name1); cout<<"The string after concatenations is "<<endl<<name; return 0; }
  • 34. strrev () #include<iostream> #include<conio.h> #include<string.h> using namespace std; int main() { char name[10]; cout<<"Enter the String "; gets(name); strrev(name); cout<<"The String after reverse isn "<<name; getch(); return 0; }
  • 35. strcmp () #include <iostream> #include <string.h> #include<conio.h> using namespace std; int main() { char *str1 = "sample", *str2 = "sample"; if(strcmp(str1, str2)==0) cout<<"strings are equal"; else cout<<"strings are not equal"; getch(); return 0; }