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

CP Chapter 5

The document discusses arrays and structures in C++. It defines an array as a group of consecutive memory locations with the same name and data type. Arrays allow storing multiple values under a single name. The document also defines a structure as a user-defined data type that groups together other variables. Structures allow grouping related data, like components of a date, under a single variable name. The document provides examples of declaring, initializing, and accessing elements of arrays and members of structures in C++ code.

Uploaded by

abelcreed1994
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)
36 views29 pages

CP Chapter 5

The document discusses arrays and structures in C++. It defines an array as a group of consecutive memory locations with the same name and data type. Arrays allow storing multiple values under a single name. The document also defines a structure as a user-defined data type that groups together other variables. Structures allow grouping related data, like components of a date, under a single variable name. The document provides examples of declaring, initializing, and accessing elements of arrays and members of structures in C++ code.

Uploaded by

abelcreed1994
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/ 29

Chapter 5

Array and Structure


Array
Quiz
1. What is an array?
2. syntax of creating an array
3. accessing an array element
4. what is 2D array?
5. setting a new value or initializing
WHAT IS ARRAY?
 An array is a group of consecutive memory locations with same name and data type.Simple

variable is a single memory location with unique name and a type.

 But an Array is collection of different adjacent memory locations.

 All these memory locations have one collective name and type.

 The memory locations in the array are known as elements of array.

 The total number of elements in the array is called length.

 The elements of array is accessed with reference to its position in array, that is call index or

subscript.
Properties of arrays
 Arrays in C++ are zero-bounded; that is the index of the first element in the array is 0 and the last

element is N-1, where N is the size of the array.

 Array can only hold values of one type

 All arrays consist of contiguous memory locations. The lowest address corresponds to the first element

and the highest address to the last element.

 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. Thus the elements

of an array are ordered by the index.


DECLARATION OF AN ARRAY
 Like a regular variable, an array must be declared before it is used.

 A typical declaration for an array in C++ is:

type name [elements];

 type is a valid type (like int, float...)

 name is a valid identifier (like grade, salary ….)

 elements field (which is always enclosed in square brackets []), specifies how many of these

elements the array has to contain.


ADVANTAGES OF ARRAY

 Arrays can store a large number of value with single name.

 Arrays are used to process many value easily and quickly.

 The values stored in an array can be sorted easily.

 The search process can be applied on arrays easily.


Example
#include <iostream>
using namespace std;
void arr2(){
//int arr[5]={12,23,34,45,56}; //using single line
int arr1[5]; Output
arr1[0]=90;
arr1[1]=50;
arr1[2]=20;
arr1[3]=40;
arr1[4]=10;
for(int i=0;i<5;i++){
cout<<"Array["<<i<<"]\t"<<arr1[i]<<endl;
// cout<<"Array1["<<i<<"]\t"<<arr[i]<<endl;
}
}
TYPES OF ARRAY

  Single dimensional array

  Two dimensional array

  Multi dimensional array


Two-dimensional array
 A collection of a fixed number of components arranged in rows and columns (that is, in two dimensions),

where in all components are of the same type.

 The syntax for declaring a two-dimensional array is:

dataType arrayName[ intExp1][ intExp2] ;

where in intExp1 and intExp2 are constant expressions yielding positive integer values.

 The two expressions, intExp1 and intExp2, specify the number of rows and the number of columns,

respectively, in the array.


Cont..

eg. double sales[ 10][ 5] ;

 Form eg. declares a two-dimensional array sales of 10 rows and 5 columns, in which every

component is of type double. As in the case of a one-dimensional array, the rows are

numbered 0. . . 9 and the columns are numbered 0. . . 4


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 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};


Cont..
 But 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.

 Each value should be separated by comma, regardless of whether inner braces are include.

 The entire initialization must set must appear within braces, and it must end with a semicolon.
Accessing array component
 To access the components of a two-dimensional array, you need a pair of indices:
 one for the row position and
 one for the column position.
 The syntax to access a component of a two-dimensional array is:
arrayName[ indexExp1][ indexExp2]
E.g: theArray [0][2] =3
Example1 Output
#include <iostream>
s[1][1]=55;
// write this code and practice
by ur self s[2][0]=333;

using namespace std; s[2][1]=88;

int main() //Access Two dimensional array

{ for(int i=0;i<3;i++){ // for rows

int s[3][2]; //two for(int j=0;j<2;j++){


dimensional array declaration
cout<<"Array "<<s[i][j]<<endl; }
// initializing two
dimensional array }

s[0][0]=23; return 0;

s[0][1]=34; }

s[1][0]=44;
Example2
#include <iostream>
using namespace std;
void arr2(){
int twod[3][2]={23,34,46,56,67,89};
int sum=0;
for(int i=0;i<3;i++){
for(int j=0;j<2;j++){
sum=sum+twod[i][j];
}
}
cout<<"Sum = "<<sum<<endl;
}
Structure
Structure
 Thus far we have worked with variable’s whose data types are very simple

 They are a numbers of either integer or floating-point format with a specific range.

 These types of variables, who only have a single value to their name, are known as basic

variables or primitives

 Everything in computers is built on numbers, but not necessarily singular types

 Sometimes it’s advantageous to group common variables into a single collection.

E.g. A date would require a day, month, and year


...
 From what we have discussed currently , you could create three separate variables for

each, like so: int day, month, year;

 This isn’t so bad, but what happens if you want to store two dates and not one?

 You’d have to create three more variables and give them unique names:

int day1, month1, year1;

int day2, month1, year2;

 This begins to become a hassle.


...
 Not only do you have to create many variables, but you have to keep giving them unique names

 C++ provides a way to collect similar variables into a single structure.

 The term structure in C++ means both a user-defined type which is a grouping of variables as

well as meaning a variable based on a user-defined structure type

 Structure Definition – the user defined type side

 Structure variable – the variable side


...
 A structure definition is a user-defined variable type which is a grouping of one or more variables

 The type itself has a name, just like ‘int’, ‘double’, or ‘char’

 But it is defined by the user and follows the normal rules of identifiers

 Defining a structure is giving the compiler a blue print for creating your type

 When you create a variable based on the structure definition, all of the member variables are created

automatically and grouped under the name you gave


...
 Syntax
struct structname
{
datatype1 variable1;
datatype2 variable2;
};

 Writing a structure definition begins with the word ‘struct’ followed by the type-to-be, and

ended with a structure block that is ultimately terminated with a semicolon.


 Structure Tag - The name of a structure definition ...
 Within the structure block you declare all the member variables you want associated with that

type

 Declare them as you would normal variables, but do not try to initialize them.

 The data members (synonym for member variables) of a structure won’t actually be created until a

variable based on the structure is created

 Example defining a student struct,


struct student {
int id;
char name[15];
struct date{
...
int day = 24, month = 10, year = 2001; Error, initialization not possible
};

 A structure definition has the same type of scoping as a variable.

 If you define a structure in a function, you will only be able to use it there.
#include <iostream>
using namespace std;
struct date{
int day, month, year;
};
int main(){
return 0;
}
 You cannot initialize member variables in the structure definition ...
 This is because that definition is only a map, or plan, of what a variable based on this type will be made of.

 You can, however, initialize the member variables of a structure variable. To initialize a structure variable’s

members, you follow the original declaration with the assignment operator (=).

 Next you define an initialization block which is a list of initializers separated by commas and enclosed in

curly braces and end with semi colon.

 E.g. date birthday = { 19, 8, 1979 };


student std1={"Abebe", "Scr/2222/22"};
 It is possible to use any expression that you normally would. ...
 But remember that the expression must result in a value
int myday = 19;
int mymonth = 5;
date birthday = { myday, mymonth + 3, 2001 - 22 };

 Although you can assign a value to a variable in the same way you initialize it, the same is not true with

structures

 While this works


int x;
x = 0;
But it doesn’t work
date birthday;
birthday = { 19, 8, 1979 };
...
 There’s not much you can do with the structure itself; much of your time with structure variables will be

spent using its members

 You can use a member variable in any place you’d use a normal variable,

 But you must specify it by the structure variable’s name as well as the member variable’s name using the

member operator

 To specify that you want a member of a specific structure variable, you use the structure member

operator which is the period

structure.member
int main() {
...
struct student{
student s1,s2;
int id;
cout<<"\n Enter Student Id";
Char name[22];
cin>>s1.id;
};
cout<<"\nEnter Name";
cin>>s1.name;
cout<<"\n Enter Student Id";
cin>>s2.id;
cout<<"\nEnter Name";
cin>>s2.name;
cout<<"\nStudents Information";
cout<<"\n Student id\t Student Name";
cout<<endl<<s1.id<<"\t"<<s1.name;
cout<<endl<<s2.id<<"\t"<<s2.name;
return 0;
}
Thank You!

You might also like