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

Array and String in C++

Arrays and strings in the Advance C Programming
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
36 views38 pages

Array and String in C++

Arrays and strings in the Advance C Programming
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 38

• 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];
• Suppose a class has 250 students, and we need to store the grades of all
of them. Instead of creating 250 separate variables, we can simply
create an array:
double grade[250];
• 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 numbers[5];
cout << "Enter 5 numbers: " << endl;
// store input from user to array
for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
}
cout << "The numbers are: ";
// print array elements
for (int n = 0; n < 5; ++n) {
cout << numbers[n] << " ";
}
return 0; }
#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; }
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int val_array[3], int_val=1, counter;
cout<<"Please enter three numbers that you want to multiply"<<endl;
for(counter=0; counter<3; counter++)
{
cin>>val_array[counter];
int_val = int_val*val_array[counter];
}
cout<<"The product of these three numbers is = "<<int_val;
getch();
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];}
• 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> twoDimArray[1][3] = 1;
using namespace std; for(int i = 0; i < 2; i++)
int main() { {
int twoDimArray[2][4]; for(int j = 0; j < 4; j++)
twoDimArray[0][0] = 6; {
twoDimArray[0][1] = 0; cout << twoDimArray[i][j];
twoDimArray[0][2] = 9; }
twoDimArray[0][3] = 6; }
twoDimArray[1][0] = 2; cout << endl;
twoDimArray[1][1] = 0; return 0;
twoDimArray[1][2] = 1; }
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 <iostream> }
using namespace std; cout << "The numbers are: " << endl;
int main() // Printing array elements

{ for (int i = 0; i < 2; ++i)


int numbers[2][3]; {
cout << "Enter 6 numbers: " << endl; for (int j = 0; j < 3; ++j)
// Storing user input in the array {
for (int i = 0; i < 2; ++i) cout << "numbers[" << i << "][" << j;
{ cout<< "] = " << numbers[i][j] << endl;
for (int j = 0; j < 3; ++j) }
{ }
cin >> numbers[i][j]; return 0;
} }
#include<stdio.h> cout<<"The elements of the array
using namespace std; are"<<endl;
int main( ) for(i=0; i<=2; i++)
{ {
int disp[3][5]; for(j=0;j<=4;j++)
int i, j; {
for(i=0; i<=2; i++) cout<<disp[i][j]<<endl;
{ }
for(j=0;j<=4;j++) }
{
cout<<"Enter value for disp[3][5]: return 0;
"<<endl; }
cin>>disp[i][j];
}
}
/*Write a program to read 3*3 matrix }
and find maximum number*/ max = mat[0][0];
#include<iostream> for(i=0; i<3; i++)
using namespace std; {
#include<conio.h> for(j=0; j<3; j++)
int main() {
{ if(max<mat[i][j])
int mat[3][3], i, j, max; max = mat[i][j];
cout<<"Enter any 3*3 matrix: }
"<<endl; }
for(i=0; i<3; i++) cout<<"\nLargest Element =
{ "<<max;
for(j=0; j<3; j++) getch();
{ return 0;
cin>>mat[i][j]; }
}
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 char fragment3[20];
cstring library: char finalString[20] = "";
#include <iostream> strcpy(fragment3, fragment1);
#include <string.h> strcat(finalString, fragment3);
using namespace std; strcat(finalString, fragment2);
int main() cout << finalString;
{ return 0;
char fragment1[] = "I'm a s";
}
char fragment2[] = "tring!";
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 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 is\n "<<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;
}

You might also like