SlideShare a Scribd company logo
Arrays
One Dimensional arrays
Contents
 Arrays
Types of Arrays
 One-Dimensional Array
 Declaring One-Dimensional Array
 Initializing One-Dimensional Array
 Accessing elements of One-Dimensional Array
 Inputting elements of One-Dimensional Array
 Displaying elements of One-Dimensional Array
 Example programs
Need for array
Imagine you have to write a program to find the sum of marks of
15 students in a class.
For this we would have to declare 15 variables of the same type.
Further to enforce uniformity, we could take the names of the
variables as marks1, marks2, marks3….etc.
The program would look like this:
Need for array
#include<iostream.h>
void main()
{ int marks1, marks2, marks3, marks4, marks5, marks6, sum;
cout<<“n enter the marks of 6 students”;
cin>>marks1>>marks2>>marks3>>marks4>>marks5>>marks6;
sum= marks1+marks2+marks3+marks4+marks5+marks6;
cout<<“average marks are “<<sum/6;
}
In the above program, we have declared 6 variables to store marks of each of the 6 students and one
variable to accumulate the sum of marks. To declare and maintain such a large number of similar
variables makes the program bulky and inefficient. To avoid such a situation, we can use arrays.
What is an array?
An array is a series of elements (variables) of the same type which
can be referenced collectively by a common name.
These elements are placed in consecutive memory locations .
They can be individually referenced by adding an index or
subscript to the unique name.
In the above scenario, to store marks of the 6 students, we could
declare an array:
int marks[6];
Declaration of marks array and memory
representation
int marks[6]; Memory Representation
array name subscript or index value
array element
Name of the array
Number of elements
Data type of
the array
marks[5]
marks[3]
marks[2]
marks[1]
marks[0]
marks[4]
Types of arrays
There are basically two types of
arrays depending on the dimension
One dimensional arrays are used to
store lists of data items like marks of
20 students, age of 15 people in a
family etc.
Two dimensional arrays are used to
store list of lists, for example to store
the marks of 20 students in 6 subjects
Types of
Arrays
One
Dimensional
Two
Dimensional
Declaring a one-dimensional array
Syntax :
type name[integer constant/literal];
• type is the data type of the array. It can be int, float or char or
user defined(discussed in later chapters)
• name is any valid c++ identifier
• the number of elements in the array has to be an integer
constant or literal.
• The size of the array in bytes= data type size X no of elements
The elements of an array are the individual variables which can be
referenced by a subscript value
One dimensional array declarations
int runs[6];
Size of array=2X6=12 bytes
(size of int X no of elements)
Data type of
each element
Name of
the array
const int x=8;
int scores[x];
Here x is a named
constant with value 8.
Thus number of
elements in the above
array=8
float salary[20];
Size of array=4X20=80 bytes
(size of floatX no of elements)
Data type of
each element
No of elementsNo of elements
No of
elements
One dimensional arrays examples
One dimensional arrays are simple lists. They may be lists of
numbers, marks or characters depending on the data type of the
array. Examples:
 int age[20]; //represents the age of 20 people
 float salary[15];// represents the salary of 15 employees
 char alphabets[24];// represents the alphabets
Memory representation of an array
Consider the following array declaration:
int a[4]; memory representation
 Data type =integer
 Name=a
 Number of elements=4
 Size = 4 X 2=8 bytes array elements
Here a is an array having 4 elements , each of type int. Each of the element can
be referred individually using name of the array and subscript value eg, a[0],
a[1] etc.
a[0] a[2] a[3]a[1]
Note: the array subscript always starts from 0. The numbering of subscript of an
array with n elements varies from 0 to n-1. Thus an array of 4 elements will be
having subscripts from 0 to 3
Initializing an array
To initialize a one dimensional array we need to specify data values enclosed in
curly braces. These data values are called initializers.
Data-type name[size]={initialvalue1,initialvalue2, initialvalue3,initialvalue4…..};
The data type of the initializers should match with the data type of the array
and number of initializers should match with the size of the array.
If the number of initializers are more than the size of the array, an error is
generated.
Initializing an array
• Example :
int marks[6]={15, 24, 20, 18, 22, 25};
15 24 20 18 22 25
More examples of array initializations
• int age[4]={25, 34, 60, 22};
0 1 2 3
• float salary[8]={45.5, 34,5, 45.0, 87.0,56.5, 78.0, 90.0, 54.5, 67.0};
0 1 2 3 4 5 6 7
25 34 60 22
45.5 34.5 45.0 87.0 56.5 78.0 54.5 67.0
Accessing array elements
In one dimensional array, every element has one index number
 The index number always starts from 0.
For an array of n elements the index varies from 0 to n-1
Thus the index of the element is always one less than the element
number. For example the index value of the 6th element will be 5 and
the index of 1st item is 0.
 We can access any element using the array name along with the
element index value inside the square brackets.
We can display, input or perform any other action with the elements just
like simple c++ variables
Accessing array elements
The elements of an array can be accessed individually as well as
collectively.
To access individual array elements the syntax is :
name[subscript]
• Example :
For the array marks :
cout<< marks[1]; // displays 24
cout<<marks[4]; // displays 22
15
24
20
18
22
25
marks[0]
marks[1]
marks[2]
marks[3]
marks[4]
marks[5]
Accessing array elements individually
Consider an array : int num[4];
Let us assign some values to the
elements individually:
• Example :
num[0]=9;
num[2]=6;
9
6
0
1
2
3
Let us now do some more calculations
with elements of the same array :
• Example :
num[0]=num[0]+2 ;
(num[0]=9, num[0]+2=11)
num[3]=num[2]+num[0];
(num[2]=6, num[0]=11)
11
6
17
Some more examples of accessing array
elements
Example Statement Meaning
age[3]=22; Assign the value 22 to the 2nd element of the array age
runs[4]=20*2; Assign the product of 20 and 2 to the 5th element of the array
runs
cin>>list[5] ; Input the 6th element of the array list
scores[7]=scores[4]+90; Add 90 to the 5th element of array score and assign the result to
the 8th element of the array
cout<<age[8 ]; Display the content of the 9th element of array age.
average=(scores[0]+scores[1])/2; find the average of score 1 and 2 and assign it to the variable
average.
age[i-2]= s+t; Assign the sum of s and t to the element of array whose index is
given by the expression i-2
Accessing array elements collectively
To assign values collectively we use a loop
Let us assign some values to the elements of the same array
collectively:
• Example : num[0]:= i=0, i*2=0
for(int i=0;i<4; i++) num[1]:= i=1, i*2=2
num[i]=i*2; num[2]:= i=2, i*2=4
num[3]:= i=3, i*2=6
Thus using a loop we can access all the elements of the array one
by one(or sequentially). The value of the index varies from 0 to 3
thus assigning the values to the elements accordingly.
0
2
4
6
Input into an array
To input values into an array we can use the for loop. Each element is accessed
individually.
int nums[4];
for(int i=0; i<4; i++)
cin>>nums[i];
The value of i will vary from 0 to 3, thus in the first pass, value of i=0.
cin>>nums[i]= cin>>nums[0]
In the second pass, value of i=1, thus
cin>>nums[i]= cin>>nums[1] and so on.
Displaying contents of an array
To diplay values of an array we can use the for loop again to access each
element individually.
for( i=0; i<4; i++)
cout<<nums[i];
The value of i will vary from 0 to 3, thus in the first pass, value of i=0.
cout<<nums[i]= cout<<nums[0]
In the second pass, value of i=1, thus
cout<<nums[i]= cout<<nums[1]
and so on.
Program to input values into an array and
display array contents
#include<iostream.h>
void main()
{
int nums[4];
cout<<“Enter the list of numbers :”;
for(int i=0; i<4; i++)
cin>>nums[i];
cout<<“n The numbers you entered are :”;
for (i=0;i<4;i++)
cout<<nums[i]<<“n”;
}
Enter the list of numbers :
2
5
6
8
The numbers you entered are :
2
5
6
8
Output
Program to input the marks of 6 students and
find the average score
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float marks[6], sum=0;
for(int i=0; i<6; i++) //loop for reading marks
{
cout<< “Enter marks of student “<< i+1<<”:”;
cin>> marks[i];
}
for(int j=0; j<6; j++) //loop for accumulating sum of marks
{
sum=sum+marks[j];
}
cout<<endl<<”Marks you have entered are :”<<endl;
for(j=0; j<6; j++) //loop for displaying the marks
{
cout<< “Marks of student “<< j+1<<”:”;
cout<< a[j]<<endl;
}
cout<<”nTotal marks : “<<sum;
cout<<“nAverage marks :”<<sum/6;
getch();
}
Enter marks of student 1: 24
Enter marks of student 2: 25
Enter marks of student 3: 22
Enter marks of student 4: 20
Enter marks of student 5: 25
Enter marks of student 6: 22
Marks you have enetered are :
Marks of student 1:24
Marks of student 2:25
Marks of student 3:22
Marks of student 4:20
Marks of student 5:25
Marks of student 6:22
Total marks :138
Average marks :23
Output
Entering unknown number of elements
The memory is allocated to an array at compile time. So this makes
it compulsory to declare an array size at the time of declaration.
But at times we do not need to input or fill each and every array
element. For example, in a school we have to define an array
marks to store data of 50 students because maximum number of
students in any class in the school is 50. But there will be classes
having lesser number of students.
Entering unknown number of elements…contd
For this we need to partially
fill the array depending on
the number of students eg 25
or 40 etc. So we take a
variable say n and run the
loop from 0 to n-1.
int marks[50], n;
cout<<“nenter number of students:
“;
cin>>n;
for(int i=0;i<n;i++)
cin>>marks[i];
Here marks[50] is the array and n is
the number of students whose marks
are to be entered. So the loop will run
from 0 to n-1 and input marks of n
students.
Explanation
Example
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float marks[50], sum=0,n;
cout<<“Enter number of students in class:”;
cin>>n;
for(int i=0; i<n; i++) //loop for reading marks
{
cout<< “Enter marks of student “<< i+1<<”:”;
cin>> marks[i];
}
for(int j=0; j<n; j++) //loop for accumulating sum of marks
{
sum=sum+marks[j];
}
cout<<”nTotal marks : “<<sum;
cout<<“nAverage marks :”<<sum/n;
getch();
}
Program to input the marks of n students and
find the average score
Enter number of students in class
4
Enter marks of student 1: 90
Enter marks of student 2: 80
Enter marks of student 3: 75
Enter marks of student 4: 85
Total marks : 330
Average marks :82.5
Output
Program to read temperatures for unknown
number of days and find average temperature
#include<iostream.h>
void main()
{
float temp[20]; int n=0;char ch=‘y’;
do
{cout<<“nEnter temperature for day ”<<n+1<<“:”;
cin>>temp[n];
cout<<“nEnter more (y/n)? ”;
cin>>ch;
n++;
}while(ch!=‘n’ || ch!=‘n’);
for(int i=0; i<n;i++)
sum+=temp[i];
cout<<“nAverage temp is :”<<sum/n;
}
Enter temperature for day 1: 25.5
Enter more(y/n)? Y
Enter temperature for day 2: 26.5
Enter more(y/n)? Y
Enter temperature for day 3: 27.0
Enter more(y/n)? Y
Enter temperature for day 4: 24.5
Enter more(y/n)? Y
Enter temperature for day 5: 25.0
Enter more(y/n)? N
Average temp is : 25.7
Output
Array out of bounds
Consider the array marks declared in the above program to store
the marks of 6 students. Although we have input marks of 6
students using the loop. But what if a user enters more than 6
marks. Lets say marks of 20 students?
We would expect an error. But this does NOT happen. The data
thus entered will be placed in locations outside the array , maybe
in other programs’ memory.
This happens because, in c++ there is no way to check if the
number of elements entered into an array exceeds the size or
number of elements declared in the array.
This may cause some unexpected program behavior and may
cause errors.
Program to find maximum number in an array
#include<iostream.h>
void main()
{
int nums[20];
cout<<Ënter the number of list items:”;
cin>>n;
cout<<“Enter the list of numbers :”;
for(int i=0; i<n; i++)
cin>>nums[i];
int max=nums[0];
for (i=0;i<n;i++)
if(nums[i]>max)
max=nums[i];
cout<<“n The largest number is :”<<max;
}
Enter the number of list items:
6
Enter the list of numbers :
22
11
56
62
80
44
The largest number is : 80
Output

More Related Content

What's hot

Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
Dr.Subha Krishna
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
Janpreet Singh
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Fatima Kate Tanay
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Union
nikshaikh786
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
Appili Vamsi Krishna
 
strings in c language and its importance
strings in c language and its importancestrings in c language and its importance
strings in c language and its importance
sirmanohar
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
Munazza-Mah-Jabeen
 
Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
Jasleen Kaur (Chandigarh University)
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
Tareq Hasan
 
Array in c
Array in cArray in c
Array in c
Ravi Gelani
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
Shubham Sharma
 
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
LATHA LAKSHMI
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
imtiazalijoono
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
Hareem Naz
 

What's hot (20)

Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Arrays
ArraysArrays
Arrays
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Union
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
strings in c language and its importance
strings in c language and its importancestrings in c language and its importance
strings in c language and its importance
 
Array assignment
Array assignmentArray assignment
Array assignment
 
Strings
StringsStrings
Strings
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
 
Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Array in c
Array in cArray in c
Array in c
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
Arrays
ArraysArrays
Arrays
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
 

Similar to Arrays

Chapter 13.pptx
Chapter 13.pptxChapter 13.pptx
Chapter 13.pptx
AnisZahirahAzman
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
MrMaster11
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
HarmanShergill5
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
Thesis Scientist Private Limited
 
Arrays In C
Arrays In CArrays In C
Arrays In C
yndaravind
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
Hemantha Kulathilake
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
ajajkhan16
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
أحمد محمد
 
Arrays
ArraysArrays
Arrays
ArraysArrays
Chap 6 c++
Chap 6 c++Chap 6 c++
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
HNDE Labuduwa Galle
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
Swarup Boro
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
Chap 6 c++
Chap 6 c++Chap 6 c++

Similar to Arrays (20)

Chapter 13.pptx
Chapter 13.pptxChapter 13.pptx
Chapter 13.pptx
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
Arrays In C
Arrays In CArrays In C
Arrays In C
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
 
Array
ArrayArray
Array
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
2 arrays
2   arrays2   arrays
2 arrays
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 

More from Neeru Mittal

Machine Learning
Machine LearningMachine Learning
Machine Learning
Neeru Mittal
 
Introduction to AI and its domains.pptx
Introduction to AI and its domains.pptxIntroduction to AI and its domains.pptx
Introduction to AI and its domains.pptx
Neeru Mittal
 
Brain Storming techniques in Python
Brain Storming techniques in PythonBrain Storming techniques in Python
Brain Storming techniques in Python
Neeru Mittal
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python Pandas
Neeru Mittal
 
Python Tips and Tricks
Python Tips and TricksPython Tips and Tricks
Python Tips and Tricks
Neeru Mittal
 
Python and CSV Connectivity
Python and CSV ConnectivityPython and CSV Connectivity
Python and CSV Connectivity
Neeru Mittal
 
Working of while loop
Working of while loopWorking of while loop
Working of while loop
Neeru Mittal
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
Neeru Mittal
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
Neeru Mittal
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
Neeru Mittal
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
Neeru Mittal
 
Nested loops
Nested loopsNested loops
Nested loops
Neeru Mittal
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
Neeru Mittal
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
Neeru Mittal
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
Neeru Mittal
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
Neeru Mittal
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
Neeru Mittal
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
Neeru Mittal
 

More from Neeru Mittal (18)

Machine Learning
Machine LearningMachine Learning
Machine Learning
 
Introduction to AI and its domains.pptx
Introduction to AI and its domains.pptxIntroduction to AI and its domains.pptx
Introduction to AI and its domains.pptx
 
Brain Storming techniques in Python
Brain Storming techniques in PythonBrain Storming techniques in Python
Brain Storming techniques in Python
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python Pandas
 
Python Tips and Tricks
Python Tips and TricksPython Tips and Tricks
Python Tips and Tricks
 
Python and CSV Connectivity
Python and CSV ConnectivityPython and CSV Connectivity
Python and CSV Connectivity
 
Working of while loop
Working of while loopWorking of while loop
Working of while loop
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Nested loops
Nested loopsNested loops
Nested loops
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 

Recently uploaded

Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 

Recently uploaded (20)

Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 

Arrays

  • 2. Contents  Arrays Types of Arrays  One-Dimensional Array  Declaring One-Dimensional Array  Initializing One-Dimensional Array  Accessing elements of One-Dimensional Array  Inputting elements of One-Dimensional Array  Displaying elements of One-Dimensional Array  Example programs
  • 3. Need for array Imagine you have to write a program to find the sum of marks of 15 students in a class. For this we would have to declare 15 variables of the same type. Further to enforce uniformity, we could take the names of the variables as marks1, marks2, marks3….etc. The program would look like this:
  • 4. Need for array #include<iostream.h> void main() { int marks1, marks2, marks3, marks4, marks5, marks6, sum; cout<<“n enter the marks of 6 students”; cin>>marks1>>marks2>>marks3>>marks4>>marks5>>marks6; sum= marks1+marks2+marks3+marks4+marks5+marks6; cout<<“average marks are “<<sum/6; } In the above program, we have declared 6 variables to store marks of each of the 6 students and one variable to accumulate the sum of marks. To declare and maintain such a large number of similar variables makes the program bulky and inefficient. To avoid such a situation, we can use arrays.
  • 5. What is an array? An array is a series of elements (variables) of the same type which can be referenced collectively by a common name. These elements are placed in consecutive memory locations . They can be individually referenced by adding an index or subscript to the unique name. In the above scenario, to store marks of the 6 students, we could declare an array: int marks[6];
  • 6. Declaration of marks array and memory representation int marks[6]; Memory Representation array name subscript or index value array element Name of the array Number of elements Data type of the array marks[5] marks[3] marks[2] marks[1] marks[0] marks[4]
  • 7. Types of arrays There are basically two types of arrays depending on the dimension One dimensional arrays are used to store lists of data items like marks of 20 students, age of 15 people in a family etc. Two dimensional arrays are used to store list of lists, for example to store the marks of 20 students in 6 subjects Types of Arrays One Dimensional Two Dimensional
  • 8. Declaring a one-dimensional array Syntax : type name[integer constant/literal]; • type is the data type of the array. It can be int, float or char or user defined(discussed in later chapters) • name is any valid c++ identifier • the number of elements in the array has to be an integer constant or literal. • The size of the array in bytes= data type size X no of elements The elements of an array are the individual variables which can be referenced by a subscript value
  • 9. One dimensional array declarations int runs[6]; Size of array=2X6=12 bytes (size of int X no of elements) Data type of each element Name of the array const int x=8; int scores[x]; Here x is a named constant with value 8. Thus number of elements in the above array=8 float salary[20]; Size of array=4X20=80 bytes (size of floatX no of elements) Data type of each element No of elementsNo of elements No of elements
  • 10. One dimensional arrays examples One dimensional arrays are simple lists. They may be lists of numbers, marks or characters depending on the data type of the array. Examples:  int age[20]; //represents the age of 20 people  float salary[15];// represents the salary of 15 employees  char alphabets[24];// represents the alphabets
  • 11. Memory representation of an array Consider the following array declaration: int a[4]; memory representation  Data type =integer  Name=a  Number of elements=4  Size = 4 X 2=8 bytes array elements Here a is an array having 4 elements , each of type int. Each of the element can be referred individually using name of the array and subscript value eg, a[0], a[1] etc. a[0] a[2] a[3]a[1] Note: the array subscript always starts from 0. The numbering of subscript of an array with n elements varies from 0 to n-1. Thus an array of 4 elements will be having subscripts from 0 to 3
  • 12. Initializing an array To initialize a one dimensional array we need to specify data values enclosed in curly braces. These data values are called initializers. Data-type name[size]={initialvalue1,initialvalue2, initialvalue3,initialvalue4…..}; The data type of the initializers should match with the data type of the array and number of initializers should match with the size of the array. If the number of initializers are more than the size of the array, an error is generated.
  • 13. Initializing an array • Example : int marks[6]={15, 24, 20, 18, 22, 25}; 15 24 20 18 22 25
  • 14. More examples of array initializations • int age[4]={25, 34, 60, 22}; 0 1 2 3 • float salary[8]={45.5, 34,5, 45.0, 87.0,56.5, 78.0, 90.0, 54.5, 67.0}; 0 1 2 3 4 5 6 7 25 34 60 22 45.5 34.5 45.0 87.0 56.5 78.0 54.5 67.0
  • 15. Accessing array elements In one dimensional array, every element has one index number  The index number always starts from 0. For an array of n elements the index varies from 0 to n-1 Thus the index of the element is always one less than the element number. For example the index value of the 6th element will be 5 and the index of 1st item is 0.  We can access any element using the array name along with the element index value inside the square brackets. We can display, input or perform any other action with the elements just like simple c++ variables
  • 16. Accessing array elements The elements of an array can be accessed individually as well as collectively. To access individual array elements the syntax is : name[subscript] • Example : For the array marks : cout<< marks[1]; // displays 24 cout<<marks[4]; // displays 22 15 24 20 18 22 25 marks[0] marks[1] marks[2] marks[3] marks[4] marks[5]
  • 17. Accessing array elements individually Consider an array : int num[4]; Let us assign some values to the elements individually: • Example : num[0]=9; num[2]=6; 9 6 0 1 2 3 Let us now do some more calculations with elements of the same array : • Example : num[0]=num[0]+2 ; (num[0]=9, num[0]+2=11) num[3]=num[2]+num[0]; (num[2]=6, num[0]=11) 11 6 17
  • 18. Some more examples of accessing array elements Example Statement Meaning age[3]=22; Assign the value 22 to the 2nd element of the array age runs[4]=20*2; Assign the product of 20 and 2 to the 5th element of the array runs cin>>list[5] ; Input the 6th element of the array list scores[7]=scores[4]+90; Add 90 to the 5th element of array score and assign the result to the 8th element of the array cout<<age[8 ]; Display the content of the 9th element of array age. average=(scores[0]+scores[1])/2; find the average of score 1 and 2 and assign it to the variable average. age[i-2]= s+t; Assign the sum of s and t to the element of array whose index is given by the expression i-2
  • 19. Accessing array elements collectively To assign values collectively we use a loop Let us assign some values to the elements of the same array collectively: • Example : num[0]:= i=0, i*2=0 for(int i=0;i<4; i++) num[1]:= i=1, i*2=2 num[i]=i*2; num[2]:= i=2, i*2=4 num[3]:= i=3, i*2=6 Thus using a loop we can access all the elements of the array one by one(or sequentially). The value of the index varies from 0 to 3 thus assigning the values to the elements accordingly. 0 2 4 6
  • 20. Input into an array To input values into an array we can use the for loop. Each element is accessed individually. int nums[4]; for(int i=0; i<4; i++) cin>>nums[i]; The value of i will vary from 0 to 3, thus in the first pass, value of i=0. cin>>nums[i]= cin>>nums[0] In the second pass, value of i=1, thus cin>>nums[i]= cin>>nums[1] and so on.
  • 21. Displaying contents of an array To diplay values of an array we can use the for loop again to access each element individually. for( i=0; i<4; i++) cout<<nums[i]; The value of i will vary from 0 to 3, thus in the first pass, value of i=0. cout<<nums[i]= cout<<nums[0] In the second pass, value of i=1, thus cout<<nums[i]= cout<<nums[1] and so on.
  • 22. Program to input values into an array and display array contents #include<iostream.h> void main() { int nums[4]; cout<<“Enter the list of numbers :”; for(int i=0; i<4; i++) cin>>nums[i]; cout<<“n The numbers you entered are :”; for (i=0;i<4;i++) cout<<nums[i]<<“n”; } Enter the list of numbers : 2 5 6 8 The numbers you entered are : 2 5 6 8 Output
  • 23. Program to input the marks of 6 students and find the average score #include<iostream.h> #include<conio.h> void main() { clrscr(); float marks[6], sum=0; for(int i=0; i<6; i++) //loop for reading marks { cout<< “Enter marks of student “<< i+1<<”:”; cin>> marks[i]; } for(int j=0; j<6; j++) //loop for accumulating sum of marks { sum=sum+marks[j]; } cout<<endl<<”Marks you have entered are :”<<endl; for(j=0; j<6; j++) //loop for displaying the marks { cout<< “Marks of student “<< j+1<<”:”; cout<< a[j]<<endl; } cout<<”nTotal marks : “<<sum; cout<<“nAverage marks :”<<sum/6; getch(); } Enter marks of student 1: 24 Enter marks of student 2: 25 Enter marks of student 3: 22 Enter marks of student 4: 20 Enter marks of student 5: 25 Enter marks of student 6: 22 Marks you have enetered are : Marks of student 1:24 Marks of student 2:25 Marks of student 3:22 Marks of student 4:20 Marks of student 5:25 Marks of student 6:22 Total marks :138 Average marks :23 Output
  • 24. Entering unknown number of elements The memory is allocated to an array at compile time. So this makes it compulsory to declare an array size at the time of declaration. But at times we do not need to input or fill each and every array element. For example, in a school we have to define an array marks to store data of 50 students because maximum number of students in any class in the school is 50. But there will be classes having lesser number of students.
  • 25. Entering unknown number of elements…contd For this we need to partially fill the array depending on the number of students eg 25 or 40 etc. So we take a variable say n and run the loop from 0 to n-1. int marks[50], n; cout<<“nenter number of students: “; cin>>n; for(int i=0;i<n;i++) cin>>marks[i]; Here marks[50] is the array and n is the number of students whose marks are to be entered. So the loop will run from 0 to n-1 and input marks of n students. Explanation Example
  • 26. #include<iostream.h> #include<conio.h> void main() { clrscr(); float marks[50], sum=0,n; cout<<“Enter number of students in class:”; cin>>n; for(int i=0; i<n; i++) //loop for reading marks { cout<< “Enter marks of student “<< i+1<<”:”; cin>> marks[i]; } for(int j=0; j<n; j++) //loop for accumulating sum of marks { sum=sum+marks[j]; } cout<<”nTotal marks : “<<sum; cout<<“nAverage marks :”<<sum/n; getch(); } Program to input the marks of n students and find the average score Enter number of students in class 4 Enter marks of student 1: 90 Enter marks of student 2: 80 Enter marks of student 3: 75 Enter marks of student 4: 85 Total marks : 330 Average marks :82.5 Output
  • 27. Program to read temperatures for unknown number of days and find average temperature #include<iostream.h> void main() { float temp[20]; int n=0;char ch=‘y’; do {cout<<“nEnter temperature for day ”<<n+1<<“:”; cin>>temp[n]; cout<<“nEnter more (y/n)? ”; cin>>ch; n++; }while(ch!=‘n’ || ch!=‘n’); for(int i=0; i<n;i++) sum+=temp[i]; cout<<“nAverage temp is :”<<sum/n; } Enter temperature for day 1: 25.5 Enter more(y/n)? Y Enter temperature for day 2: 26.5 Enter more(y/n)? Y Enter temperature for day 3: 27.0 Enter more(y/n)? Y Enter temperature for day 4: 24.5 Enter more(y/n)? Y Enter temperature for day 5: 25.0 Enter more(y/n)? N Average temp is : 25.7 Output
  • 28. Array out of bounds Consider the array marks declared in the above program to store the marks of 6 students. Although we have input marks of 6 students using the loop. But what if a user enters more than 6 marks. Lets say marks of 20 students? We would expect an error. But this does NOT happen. The data thus entered will be placed in locations outside the array , maybe in other programs’ memory. This happens because, in c++ there is no way to check if the number of elements entered into an array exceeds the size or number of elements declared in the array. This may cause some unexpected program behavior and may cause errors.
  • 29. Program to find maximum number in an array #include<iostream.h> void main() { int nums[20]; cout<<Ënter the number of list items:”; cin>>n; cout<<“Enter the list of numbers :”; for(int i=0; i<n; i++) cin>>nums[i]; int max=nums[0]; for (i=0;i<n;i++) if(nums[i]>max) max=nums[i]; cout<<“n The largest number is :”<<max; } Enter the number of list items: 6 Enter the list of numbers : 22 11 56 62 80 44 The largest number is : 80 Output