Lec 11 Arrays

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

LECTURE#13

1. Arrays
a. Array declaration
b. Array initialization
c. Access element of an array
2. Multi-dimensions arrays
d. Declaration & initialization
3. Passing array to a function
4. Array in a structure
5. Array as a class member
6. Arrays of objects
Arrays:
1. It is a group of variables of similar data types referred to by a single element.
2. Its elements are stored in a contiguous memory location.
3. The size of the array should be mentioned while declaring it.
4. Array elements are always counted from zero (0) onward.
5. Array elements can be accessed using the position of the element in the array.
6. The array can have one or more dimensions.
Contiguous memory locations:

 items stored at contiguous memory locations.


 elements can be accessed randomly using indices of an array.
Why do we need arrays? ??
The idea of an array is to represent many instances in one variable.
 Advantages:-
• Code Optimization: we can retrieve or sort the data efficiently.
• Random access: We can get any data located at an index position.

 Disadvantages:-
• Size Limit: We can store only the fixed size of elements in the array. It doesn’t grow its
size at runtime.
How to declare an array?

 dataType arrayName[arraySize]; e.g: float mark[5];


 declared an array, mark, of floating-point type and size is 5.
 It's important to note that the size and type of an array cannot be changed once it is
declared.
The items in an array are called elements (in contrast to
the items in a structure, which are called members).
Access Array Elements

The first element is mark[0], the second element is mark[1] and so on.

i. Arrays have 0 as the first index, not 1.


ii. In this example, mark[0] is the first element.
iii. If the size of an array is n, to access the last element, the n-1 index is used.
iv. In this example, mark[4].
v. Suppose the starting address of mark[0] is 2120d.
vi. Then, the address of the mark[1] will be 2124d.
vii. Similarly, the address of mark[2] will be 2128d and so on.
This is because the size of a float is 4 bytes.
How to initialize an array?
 It is possible to initialize an array during declaration. For example:
int mark[5] = {19, 10, 8, 17, 9};

 You can also initialize an array like this:


int mark[] = {19, 10, 8, 17, 9};

Here, we haven't specified the size. However, the compiler knows its size is 5 as we are initializing it
with 5 elements.

Here

 Change Value of Array elements


Example Program:
It then asks the user to enter four values, which it places in the
array. Finally, it displays all four values.
// gets four ages from user, displays them
#include <iostream>
using namespace std; Output:
int main() { Enter an age: 44
int age[4]; //array ‘age’ of 4 ints Enter an age: 16
for(int j=0; j<4; j++) //get 4 ages Enter an age: 23
{ Enter an age: 68
cout << “Enter an age: “; You entered 44
cin >> age[j]; //access array element You entered 16
} You entered 23
for(j=0; j<4; j++) //display 4 ages You entered 68
cout << “You entered “ << age[j] << endl;
return 0;
}
Example:
1. Program to take 5 values from the user and store them in an array

2. Another example of an array at work:


SALES, invites the user to enter a series of six values representing widget sales for each day
of the week (excluding Sunday), and then calculates the average of these values.
Use an array of type double so that monetary values can be entered.

3. Calculate Average of n numbers using arrays


Multidimensional arrays:

 an array of arrays that stores homogeneous data in tabular form.


 Data in multidimensional arrays are stored in row-major order.
 The general form of declaring N-dimensional arrays is:
data_type array_name[size1][size2]....[sizeN];

i. data_type: Type of data to be stored in the array.

ii. array_name: Name of the array

iii. size1, size2,… ,sizeN: Sizes of the dimension

Examples:
 Two dimensional array: int two_d[10][20];
 Three dimensional array: int three_d[10][20][30];
Enter sales for district 1, month 1: 3964.23 cout << “\n\n”;
Enter sales for district 1, month 2: 4135.87
Example Program:
Enter sales for district 1, month 3: 4397.98
cout << “
cout << “
Months\n;
1 2 3”;
Enter
// displays sales chart using 2-d sales
array for district 2, month 1: 867.75 for(d=0; d<DISTRICTS; d++)
#include <iostream> Enter sales for district 2, month 2: 923.59
{
two-dimensional array to store sales figures for several districts and several months:
#include <iomanip> //for Enter sales foretc.
setprecision, district 2, month 3: 1037.01cout <<”\nDistrict “ << d+1;
using namespace std; Enter sales for district 3, month 1: 12.77 for(m=0; m<MONTHS; m++) //display array values
Enter sales for
const int DISTRICTS = 4; //array dimensions district 3, month 2: 378.32 cout << setiosflags(ios::fixed) //not exponential
const int MONTHS = 3; Enter sales for district 3, month 3: 798.22 << setiosflags(ios::showpoint) //always use point
int main() Enter sales for district 4, month 1: 2983.53 << setprecision(2) //digits to right
{ Enter sales for district 4, month 2: 3983.73 << setw(10) //field width
int d, m; Enter sales for district 4, month 3: 9494.98 << sales[d][m]; //get number from array
double sales[DISTRICTS][MONTHS]; //two-dimensional array }//definition
Month //end for(d)
cout << endl; 1. 2 cout
3 << endl;
for(d=0; d<DISTRICTS; District
d++) //get
1 array values 4135.87 4397.98
3964.23 return 0; } //end main
for(m=0; m<MONTHS; m++) District 2 867.75 923.59 1037.01
{ District 3 12.77 378.32 798.22
cout << “Enter sales for District
district “4<< d+1;
2983.53 3983.72 9494.98
cout << “, month “ << m+1 << “: “;
cin >> sales[d][m];
}
Function Call with Array
Passing Array to a function: Arguments
Arrays can be used as arguments to functions.

Function Declaration with Array Arguments

Function Definition
with Array
Arguments
Arrays as Class Member Data:
Arrays of objects:
// Driver code
int main()Example of array of object:
{
////This
C++ is an array
program of objects having
to implement // Defining the function outside
////maximum limit
the above of 30 Employees
approach // the class
Employee emp[30];
#include<iostream> void Employee::getdata()
int n, i;
using namespace std; {
cout << "Enter Number of Employees - ";
cout << "Enter Id : ";
cin >> n;
class Employee cin >> id;
{ cout << "Enter Name : ";
// Accessing
int id; the function
cin >> name;
for(i = 0;
char i < n; i++)
name[30]; }
emp[i].getdata();
public:
// Defining the function outside
cout//<<Declaration
"Employee Data - " << endl;
of function // the class
void getdata(); void Employee::putdata()
// Accessing the function
{
for(i
// =Declaration
0; i < n; i++)
of function cout << id << " ";
emp[i].putdata();
void putdata(); cout << name << " ";
} }; cout << endl;
}
// Function to get item details
Example of array of object:
void item::getitem()
{
int main() #include<iostream> cout << "Item Name = ";
{ using namespace std; cin >> name;
item t[size];
class item cout << "Price = ";
for(int i ={ 0; i < size; i++) cin >> price;
{ char name[30]; }
cout << "Item : " <<
int price;
(i public:
+ 1) << "\n"; // Function to print item
t[i].getitem();
void getitem(); // details
} void printitem(); void item ::printitem()
}; {
for(int i = 0; i < size; i++) cout << "Name : " << name <<
{ "\n";
cout << "Item Details : " << cout << "Price : " << price <<
(i + 1) << "\n"; "\n";
t[i].printitem(); }
}
} const int size = 3;
Advantages of Array of Objects:

1. The array of objects represent storing multiple objects in a single name.


2. In an array of objects, the data can be accessed randomly by using the index number.
3. Reduce the time and memory by storing the data in a single variable.
Strings:

 Strings are used for storing text/characters.


 For example, "Hello World" is a string of characters.
 In C programming, a string is a sequence of characters terminated with
a null character \0. For example:
char c[] = "c string";

null character \0 at the end by default.


 How to declare a string?
 char s[5];

String Declaration in C

 How to initialize strings?


char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0’};
char c[5] = {'a', 'b', 'c', 'd', '\0’};

 Assigning Values to Strings


char c[100];
c = "C++ programming"; // Error! array type is not assignable.
Read String from the user…
#include <iostream>
using namespace std;
int main()
 can use the cin function to read a string.
{
char str[100];
 The cin function reads the sequence of characters until it encounters whitespace (space,
cout << "Enter a string: ";
newline, tab, etc.). cin.get(str, 100);
#include <iostream> Output:" << str << endl;
cout << "You entered:
using namespace std; return 0; Enter a string: C++
int main() } You entered: C++
{ Enter another string: Programming is fun.
char str[100]; You entered: Programming
cout << "Enter a string: ";
cin >> str;
cout << "You entered: " << str << endl; Enter a string: Programming is fun.
cout << "\nEnter another string: "; You entered: Programming is fun.
cin >> str;
cout << "You entered: "<<str<<endl;
return 0;
}
Buffer Overflow:
Reading Multiple Lines:

Now type as many lines of input as you want.


Remember, you must still press Enter after typing the ‘$’ character.
Arrays of Strings:
Passing String to a Function: Str=char array
Str1=object array
 Strings are passed to a function in a similar way arrays passed in a function.
display()=overloaded function

#include <iostream> void display(char s[])


using namespace std; {
void display(char *); cout << "Entered char array is: " << s << endl;
void display(string); }
int main() void display(string s)
{ {
string str1; cout << "Entered string is: " << s << endl;
char str[100]; }
cout << "Enter a string: ";
getline(cin, str1);
cout << "Enter another string: "; Enter a string: Programming is fun.
cin.get(str, 100, '\n’); Enter another string: Really?
display(str1); Entered string is: Programming is fun.
display(str); Entered char array is: Really?
return 0;
}
#include <iostream>
#include <cstring> //for strcpy()
Strings as Class Members:
using namespace std;
int main()
class part
{
{
part part1, part2;
private:
part1.setpart("handle bolt", 4473, 217.55); //set parts
char partname[30]; //name of widget part
part2.setpart("start leverr", 9924, 419.25);
int partnumber; //ID number of widget part
cout << "\n First part:"; part1.showpart(); //show parts
double cost; //cost of part
cout << "\nSecond part:"; part2.showpart();
public:
cout << endl;
void setpart(char pname[], int pn, double c)
return 0;
{
}
strcpy(partname, pname);
partnumber = pn;
cost = c;
}
Output:
void showpart()
First part:
{
cout<<"\n Name="<<partname;
Name=handle bolt,number=4473,cost=$217.55
cout<<",number="<<partnumber;
cout << ",cost=$”<< cost;
Second part:
}
};
Name=start leverr,number=9924,cost=$419.25
THANK YOU for your patience…

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy