Sunteți pe pagina 1din 19

BSIT-502, UNIT-2

Array, Strings, Structures, Union and Pointers


Arrays:
C++ provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of
data, but it is often more useful to think of an array as a collection of variables
of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and


number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. A specific
element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address


corresponds to the first element and the highest address to the last element.

Declaring Arrays:

To declare an array in C++, the programmer specifies the type of the elements
and the number of elements required by an array as follows:

type arrayName [ arraySize ];

This is called a single-dimension array. The arraySize must be an integer


constant greater than zero and type can be any valid C++ data type. For
example, to declare a 10-element array called balance of type double, use this
statement:

double balance[10];

Initializing Arrays:

You can initialize C++ array elements either one by one or using a single
statement as follows:

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ]. Following is
an example to assign a single element of the array:

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 1
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write:

double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

You will create exactly the same array as you did in the previous example.

balance[4] = 50.0;

The above statement assigns element number 5th in the array a value of 50.0.
Array with 4th index will be 5th, i.e., last element because all arrays have 0 as
the index of their first element which is also called base index. Following is the
pictorial representation of the same array we discussed above:

Accessing Array Elements:

An element is accessed by indexing the array name. This is done by placing the
index of the element within square brackets after the name of the array. For
example:

double salary = balance[9];

The above statement will take 10th element from the array and assign the value
to salary variable. Following is an example, which will use all the above-
mentioned three concepts viz. declaration, assignment and accessing arrays:

#include <iostream>
using namespace std;

#include <iomanip>
using std::setw;

int main ()
{
int n[ 10 ]; // n is an array of 10 integers

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 2
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
// initialize elements of array n to 0
for ( int i = 0; i < 10; i++ )
{
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;

// output each array element's value


for ( int j = 0; j < 10; j++ )
{
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}

return 0;
}

This program makes use of setw() function to format the output. When the
above code is compiled and executed, it produces the following result:

Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
Multidimensional Array

C++ allows multidimensional arrays. Here is the general form of a


multidimensional array declaration:

type name[size1][size2]...[sizeN];

For example, the following declaration creates a three dimensional 5. 10. 4


integer array:

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 3
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
int threedim[5][10][4];

Two-Dimensional Arrays:

The simplest form of the multidimensional array is the two-dimensional array.


A two-dimensional array is, in essence, a list of one-dimensional arrays. To
declare a two-dimensional integer array of size x,y, you would write something
as follows:

type arrayName [ x ][ y ];

Where type can be any valid C++ data type and arrayName will be a valid
C++ identifier.

A two-dimensional array can be think as a table, which will have x number of


rows and y number of columns. A 2-dimensional array a, which contains three
rows and four columns can be shown as below:

Thus, every element in array a is identified by an element name of the form


a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that
uniquely identify each element in a.

Initializing Two-Dimensional Arrays:

Multidimensional arrays may be initialized by specifying bracketed values for


each row. Following is an array with 3 rows and each row has 4 columns.

int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 4
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
The nested braces, which indicate the intended row, are optional. The following
initialization is equivalent to previous example:

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements:

An element in 2-dimensional array is accessed by using the subscripts, i.e., row


index and column index of the array. For example:

int val = a[2][3];


#include <iostream.h>

int main ()
{
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};

// output each array element's value


for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 2; j++ )
{
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}

return 0;
}

When the above code is compiled and executed, it produces the following
result:

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
Prof. Mandeep Kaur,
Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 5
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
a[4][0]: 4
a[4][1]: 8

Program1: C++ Program to store 5 numbers entered by user in an array


and display first and last number only.

#include <iostream.h>
int main()
{
int n[5];
cout<<"Enter 5 numbers: ";
/* Storing 5 number entered by user in an array using for loop. */
for (int i = 0; i < 5; ++i)
{
cin>>n[i];
}

cout<<"First number: "<<n[0]<<endl; // first element of an array is n[0]


cout<<"Last number: "<<n[4]; // last element of an array is
n[SIZE_OF_ARRAY - 1]
return 0;
}

Program 2: Transpose of a Matrix

#include <iostream>
int main()
{
int a[10][10], trans[10][10], r, c, i, j;
cout << "Enter rows and columns of matrix: ";
cin >> r >> c;

/* Storing element of matrix entered by user in array a[][]. */


cout << endl << "Enter elements of matrix: " << endl;
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
cout << "Enter elements a" << i+1 << j+1 << ": ";

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 6
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
cin >> a[i][j];
}
/* Displaying the matrix a[][] */
cout << endl << "Entered Matrix: " << endl;
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
cout << " " << a[i][j];
if(j==c-1)
cout << endl << endl;
}

/* Finding transpose of matrix a[][] and storing it in array trans[][]. */


for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
trans[j][i]=a[i][j];
}

/* Displaying the transpose,i.e, Displaying array trans[][]. */


cout << endl << "Transpose of Matrix: " << endl;
for(i=0; i<c; ++i)
for(j=0; j<r; ++j)
{
cout << " " << trans[i][j];
if(j==r-1)
cout << endl << endl;
}
return 0;
}

Output

Enter rows and column of matrix: 2


3

Enter elements of matrix:


Enter elements a11: 1
Enter elements a12: 2

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 7
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
Enter elements a13: 9
Enter elements a21: 0
Enter elements a22: 4
Enter elements a23: 7

Entered Matrix:
1 2 9
0 4 7
Transpose of Matrix:
1 0
2 4
9 7

Program 3: Multiply two matrices


#include <iostream>
int main()
{
int a[10][10], b[10][10], mult[10][10], r1, c1, r2, c2, i, j, k;
cout << "Enter rows and columns for first matrix: ";
cin >> r1 >> c1;
cout << "Enter rows and columns for second matrix: ";
cin >> r2 >> c2;

/* If colum of first matrix in not equal to row of second matrix, asking user to
enter the size of matrix again. */
while (c1!=r2)
{
cout << "Error! column of first matrix not equal to row of second.";
cout << "Enter rows and columns for first matrix: ";
cin >> r1 >> c1;
cout << "Enter rows and columns for second matrix: ";
cin >> r2 >> c2;
}

/* Storing elements of first matrix. */


cout << endl << "Enter elements of matrix 1:" << endl;
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
Prof. Mandeep Kaur,
Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 8
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
{
cout << "Enter element a" << i+1 << j+1 << " : ";
cin >> a[i][j];
}

/* Storing elements of second matrix. */


cout << endl << "Enter elements of matrix 2:" << endl;
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
cout << "Enter element b" << i+1 << j+1 << " : ";
cin >> b[i][j];
}

/* Initializing elements of matrix mult to 0.*/


for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
mult[i][j]=0;
}

/* Multiplying matrix a and b and storing in array mult. */


for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
mult[i][j]+=a[i][k]*b[k][j];
}

/* Displaying the multiplication of two matrix. */


cout << endl << "Output Matrix: " << endl;
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
cout << " " << mult[i][j];
if(j==c2-1)
cout << endl;
}
return 0;
Prof. Mandeep Kaur,
Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 9
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
}

Output

Enter rows and column for first matrix: 3


2
Enter rows and column for second matrix: 3
2
Error! column of first matrix not equal to row of second.

Enter rows and column for first matrix: 2


3
Enter rows and column for second matrix: 3
2

Enter elements of matrix 1:


Enter elements a11: 3
Enter elements a12: -2
Enter elements a13: 5
Enter elements a21: 3
Enter elements a22: 0
Enter elements a23: 4

Enter elements of matrix 2:


Enter elements b11: 2
Enter elements b12: 3
Enter elements b21: -9
Enter elements b22: 0
Enter elements b31: 0
Enter elements b32: 4

Output Matrix:
24 29
6 25

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 10
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
Strings in C++:

It is an array of type char.


Syntax for declaration:
char string name [number of characters+1];
The number of elements that can be stored in a string is always n-1, if the size
of the array specified is n. This is because 1 byte is reserved for the NULL
character '\0' i.e. backslash zero. A string is always terminated with the NULL
character.
Example: char str[80];
In the above example, str can be used to store a string with 79 characters
Initializing a string
A string can be initialized to a constant value when it is declared.
char str[ ] = "Good";
Or
char str[]={'G','o','o','d','\0'};
Here. 'G' will be stored in str[0], 'o' in str[1] and so on.
When the value is assigned to the complete string at once, the computer
automatically inserts the NULL character at the end of the string. But, if it is
done character by character, then we have to insert it at the end of the string.

Reading strings with/without embedded blanks


To read a string without blanks cin can be used:
cin>>str;
To read a string with blanks cin.getline() or gets() can be used.
cin.getline(str,80);
-Or-
gets(str);
Printing strings
cout and puts() can be used to print a string.
cout<<str:
or
puts(str);
For gets( ) and puts(), the header file <cstdio.h> (formally stdio.h) has to be
included. puts() can be used to display only strings. It takes a line feed after
printing the string.

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 11
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 12
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers

C++ supports a wide range of functions that manipulate null-terminated strings:

S.N. Function & Purpose


1 strcpy(s1, s2); Copies string s2 into string s1.
2 strcat(s1, s2); Concatenates string s2 onto the end of string s1.
3 strlen(s1); Returns the length of string s1.
strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if
4
s1<s2; greater than 0 if s1>s2.
strchr(s1, ch); Returns a pointer to the first occurrence of
5
character ch in string s1.
strstr(s1, s2); Returns a pointer to the first occurrence of string s2
6
in string s1.

Program: Counting the number of characters in a string and printing it


backwards
#include<iostream.h>
int main( )
{
Prof. Mandeep Kaur,
Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 13
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
char str[80];
cout<<"Enter a string:";
cin.getline(str,80);
for(int i=0; str[i]!='\0';i++); //Loop to find length
cout<<"The length of the string is : "<<i<<endl ;
for(int i=i-1;i>=0;i--) //Loop to display the string backwards
cout<<str[i];
return 0;
}

Program: Function to count the number of words in a string


void count(char S[])
{
int words=0;
for(int i=0;S[i]!='\0';i++)
{
if (S[i]==' ')
words++; //Checking for spaces
}
cout<<"The number of words="<<words+1<<endl;
}

Function to find the length of a string


int length(char S[ ])
{
for(int i=0;S[i]!='\0';i++);
return i;
}

Function to copy the contents of string S2 to S1


void copy(char S1[ ], char S2[ ])
{
for(int i=0;S2[i]!='\0';i++)
S1[i]=S2[i];
S1[i]='\0';
}

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 14
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
Function to concatenate the contents of string S2 to S1
void concat(char S1[ ], char S2[ ])
{
for(int l=0;S1[l]!='\0';l++);
for(int i=0;S2[i]!='\0';i++)
S1[l++]=S2[i];
S1[l]='\0';
}

Function to compare strings STR1 to STR2.


The function returns a value>0 if //STR1> STR2, a value<0 if STR1<STR2, and
value 0 if STR1=STR2
int compare(char STR1[ ],char STR2[])
{
for(int i=0;STR1[i]==STR2[i] && STR1[i]!='\0'&&STR2[i]!='\0'; I++);
return STR1[I]-STR2[I];
}

To reverse the contents of string S and store it in string Rev


void Reverse(char S[], char Rev[])
{
for(int C1=0; S[C1]!='\0'; C1++);
C1--;
for(int C2=0;C1>=0;C2++,C1--)
Rev[C2]=S[C1];
Rev[C2]='\0';
}

Function to check whether a string S is a palindrome or not


int Palin(char S[])
{
for(int L=0;S[L]!='\0';L++); //To find length
for(int C=0;(C<L/2) && (S[C]==S[L-C-1]);C++);
return (C==L/2)?1:0; //Returns 1 if Palindrome else 0
}

Function to change the case of string S to uppercase


void Upper(char S[])
{
Prof. Mandeep Kaur,
Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 15
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
for(int i=0;S[i]!='\0';i++)
S[i] = (S[i]>='a' && S[i]<='z')?(S[i]-32):S[i];
}

Function to change the case of string S to lower case


void Lower(char S[])
{
for(int i=0;S[i]!='\0';i++)
S[i] = (S[i]>='A' && S[i]<='Z')?(S[i]+32):S[i];
}

C++ Structures:

Structure is the collection of variables of different types under a single name for
better visualisation of problem. Arrays is also collection of data but arrays can
hold data of only one type whereas structure can hold data of one or more types.

How to define a structure in C++ programming?


The struct keyword defines a structure type followed by an identifier(name of
the structure). Then inside the curly braces, you can declare one or more
members (declare variables inside curly braces) of that structure.

For example:
struct person
{
char name[50];
int age;
float salary;
};
Here a structure person is defined which has three members: name, age and
salary.

When a structure is created, no memory is allocated. The structure definition is


only the blueprint for the creating of variables. You can imagine it as a data
type. When you define an integer as below:
int x;

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 16
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
The int specifies that, variable x can hold integer element only. Similarly,
structure definition only specifies that, what property a structure variable holds
when it is defined.
How to access members of a structure?
The members of structure variable are accessed using dot operator. Suppose,
you want to access age of structure variable bill and assign it 50 to it. You can
perform this task by using following code below:
bill.age = 50;

C++ Program to assign data to members of a structure


variable and display it.
#include <iostream.h>
struct person
{
char name[50];
int age;
float salary;
};
int main()
{
person p1;
cout << "Enter Full name: ";
cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
cout << "\n Displaying Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;
return 0;
}

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 17
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
C++ Program to Store Information (name, roll and
marks) of a Student Using Structure
#include <iostream.h>
#include <cstring.h>
struct student
{
char name[50];
int roll;
float marks;
};
int main()
{
struct student s;
cout << "Enter information of students: " << endl;
cout << "Enter name: ";
cin >> s.name;
cout << "Enter roll number: ";
cin >> s.roll;
cout << "Enter marks: ";
cin >> s.marks;
cout << endl << "Displaying Information" << endl;
cout << endl << "Name: " << s.name;
cout << endl << "Roll: " << s.roll;
cout << endl << "Marks: " << s.marks;
return 0;
}

Unions in c++:
Unions in C++ is a user defined data type that uses the same memory as other
objects from a list of objects. At an instance it contains only a single object.
#include <iostream.h>
union Emp
{
int num;
double sal;
};

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 18
BSIT-502, UNIT-2
Array, Strings, Structures, Union and Pointers
int main()
{
Emp value;
value.num = 2;
cout << "Employee Number::" << value.num
<< "\nSalary is:: " << value.sal << endl;
value.sal = 2000.0;
cout << "Employee Number::" << value.num
<< "\nSalary is:: " << value.sal << endl;
return 0;
}

The difference between structure and union is,


1. The amount of memory required to store a structure variable is the sum of
the size of all the members. On the other hand, in case of unions, the
amount of memory required is always equal to that required by its largest
member.
2. In case of structure, each member have their own memory space but In
union, one block is used by all the member of the union.

Prof. Mandeep Kaur,


Dept. of Elect & IT, S.D. College, Ambala Cantt
Mob: 09729871160
Email: mandeepmalhotra28@gmail.com Page 19

S-ar putea să vă placă și