SlideShare a Scribd company logo
1 of 19
EC-102 Computer System &
Programming
Lecture #8
Instructor: Jahan Zeb
Department of Computer Engineering (DCE)
College of E&ME
Introduction
 Arrays
– Structures of related data items
– Static entity (same size throughout program)
Arrays
 Array
– Consecutive group of memory locations
– Same name and type (int, char, etc.)
 To refer to an element
– Specify array name and position number (index)
– Format: arrayname[ position number ]
– First element at position 0
 N-element array c
c[ 0 ], c[ 1 ] … c[ n - 1 ]
– Nth element as position N-1
Arrays
 Array elements like other variables
– Assignment, printing for an integer array c
c[ 0 ] = 3;
cout << c[ 0 ];
 Can perform operations inside subscript
c[ 5 – 2 ] same as c[3]
Arrays
c[6]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
Name of array (Note that
all elements of this array
have the same name, c)
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
Position number of the
element within array c
Declaring Arrays
 When declaring arrays, specify
– Name
– Type of array
• Any data type
– Number of elements
– type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats
 Declaring multiple arrays of same type
– Use comma separated list, like regular variables
int b[ 100 ], x[ 27 ];
Examples Using Arrays
 Initializing arrays
– For loop
• Set each element
– Initializer list
• Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
• If not enough initializers, rightmost elements 0
– To set every element to same value
int n[ 5 ] = { 0 };
– If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array
1
2 // Initializing an array.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setw;
11
12 int main()
13 {
14 int n[ 10 ]; // n is an array of 10 integers
15
16 // initialize elements of array n to 0
17 for ( int i = 0; i < 10; i++ )
18 n[ i ] = 0; // set element at location i to 0
19
20 cout << "Element" << setw( 13 ) << "Value" << endl;
21
22 // output contents of array n in tabular format
23 for ( int j = 0; j < 10; j++ )
24 cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;
25
Declare a 10-element array of
integers.
Initialize array to 0 using a
for loop. Note that the array
has elements n[0] to n[9].
26 return 0; // indicates successful termination
27
28 } // end main
Element Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
1
2 // Initializing an array with a declaration.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setw;
11
12 int main()
13 {
14 // use initializer list to initialize array n
15 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
16
17 cout << "Element" << setw( 13 ) << "Value" << endl;
18
19 // output contents of array n in tabular format
20 for ( int i = 0; i < 10; i++ )
21 cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;
22
23 return 0; // indicates successful termination
24
25 } // end main
Note the use of the initializer
list.
Element Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
Examples Using Arrays
 Array size
– Can be specified with constant variable (const)
• const int size = 20;
– Constants cannot be changed
– Constants must be initialized when declared
– Also called named constants or read-only variables
1
2 // Initialize array s to the even integers from 2 to 20.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setw;
11
12 int main()
13 {
14 // constant variable can be used to specify array size
15 const int arraySize = 10;
16
17 int s[ arraySize ]; // array s has 10 elements
18
19 for ( int i = 0; i < arraySize; i++ ) // set the values
20 s[ i ] = 2 + 2 * i;
21
22 cout << "Element" << setw( 13 ) << "Value" << endl;
23
Note use of const keyword.
Only const variables can
specify array sizes.
The program becomes more
scalable when we set the array
size using a const variable.
We can change arraySize,
and all the loops will still
work (otherwise, we’d have to
update every loop in the
program).
24 // output contents of array s in tabular format
25 for ( int j = 0; j < arraySize; j++ )
26 cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl;
27
28 return 0; // indicates successful termination
29
30 } // end main
Element Value
0 2
1 4
2 6
3 8
4 10
5 12
6 14
7 16
8 18
9 20
1
2 // Using a properly initialized constant variable.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 const int x = 7; // initialized constant variable
11
12 cout << "The value of constant variable x is: "
13 << x << endl;
14
15 return 0; // indicates successful termination
16
17 } // end main
The value of constant variable x is: 7
Proper initialization of
const variable.
1
2 // A const object must be initialized.
3
4 int main()
5 {
6 const int x; // Error: x must be initialized
7
8 x = 7; // Error: cannot modify a const variable
9
10 return 0; // indicates successful termination
11
12 } // end main
d:cpphtp4_examplesch04Fig04_07.cpp(6) : error C2734: 'x' :
const object must be initialized
Uninitialized const results
in a syntax error. Attempting
to modify the const is
another error.
1
2 // Compute the sum of the elements of the array.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 const int arraySize = 10;
11
12 int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
13
14 int total = 0;
15
16 // sum contents of array a
17 for ( int i = 0; i < arraySize; i++ )
18 total += a[ i ];
19
20 cout << "Total of array element values is " << total << endl;
21
22 return 0; // indicates successful termination
23
24 } // end main
Total of array element values is 55
1
2 // Histogram printing program.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setw;
11
12 int main()
13 {
14 const int arraySize = 10;
15 int n[ arraySize ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
16
17 cout << "Element" << setw( 13 ) << "Value"
18 << setw( 17 ) << "Histogram" << endl;
19
20 // for each element of array n, output a bar in histogram
21 for ( int i = 0; i < arraySize; i++ ) {
22 cout << setw( 7 ) << i << setw( 13 )
23 << n[ i ] << setw( 9 );
24
25 for ( int j = 0; j < n[ i ]; j++ ) // print one bar
26 cout << '*';
Prints asterisks corresponding
to size of array element,
n[i].
27
28 cout << endl; // start next line of output
29
30 } // end outer for structure
31
32 return 0; // indicates successful termination
33
34 } // end main
Element Value Histogram
0 19 *******************
1 3 ***
2 15 ***************
3 7 *******
4 11 ***********
5 9 *********
6 13 *************
7 5 *****
8 17 *****************
9 1 *

More Related Content

What's hot

Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3Ali Aminian
 
C++ Function
C++ FunctionC++ Function
C++ FunctionHajar
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)Ritika Sharma
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Dharma Kshetri
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operatorSAFFI Ud Din Ahmad
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - ReferenceMohammed Sikander
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings imtiazalijoono
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2Amit Kapoor
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...ssuserd6b1fd
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...ssuserd6b1fd
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 

What's hot (20)

Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Pointers
PointersPointers
Pointers
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
 
functions of C++
functions of C++functions of C++
functions of C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 
C++ lecture 03
C++   lecture 03C++   lecture 03
C++ lecture 03
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
 
Function & Recursion in C
Function & Recursion in CFunction & Recursion in C
Function & Recursion in C
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
C++ references
C++ referencesC++ references
C++ references
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 

Viewers also liked

Hosting Dergi - 9.SAYI
Hosting Dergi - 9.SAYIHosting Dergi - 9.SAYI
Hosting Dergi - 9.SAYIHosting Dergi
 
Ejercicio 2 programación algoritmos Valentino Spina.
Ejercicio 2 programación  algoritmos Valentino Spina.Ejercicio 2 programación  algoritmos Valentino Spina.
Ejercicio 2 programación algoritmos Valentino Spina.Valentino Spina
 
Olena teliga pr.-konf.
Olena teliga pr.-konf.Olena teliga pr.-konf.
Olena teliga pr.-konf.TOBM Ternopil
 
Colgate-Palmolive Company: The Precision Toothbrush
Colgate-Palmolive Company: The Precision ToothbrushColgate-Palmolive Company: The Precision Toothbrush
Colgate-Palmolive Company: The Precision ToothbrushPriyadarsini Somasundaram
 
[UNIP2015] Testando a Performance de Aplicações Web com JMeter
[UNIP2015] Testando a Performance de Aplicações Web com JMeter[UNIP2015] Testando a Performance de Aplicações Web com JMeter
[UNIP2015] Testando a Performance de Aplicações Web com JMeterJúlio de Lima
 
DevQA - Da zona de conforto ao comprometimento com a qualidade
DevQA  - Da zona de conforto ao comprometimento com a qualidadeDevQA  - Da zona de conforto ao comprometimento com a qualidade
DevQA - Da zona de conforto ao comprometimento com a qualidadeKamilla Queiroz Xavier
 
Dem ham bang odontosil final - hn 042016
Dem ham bang odontosil   final - hn 042016Dem ham bang odontosil   final - hn 042016
Dem ham bang odontosil final - hn 042016DentechUMP
 
Ch01 introduction
Ch01 introductionCh01 introduction
Ch01 introductionGRajendra
 
[TICNOVA2015] Palestra sobre Automação de Testes
[TICNOVA2015] Palestra sobre Automação de Testes[TICNOVA2015] Palestra sobre Automação de Testes
[TICNOVA2015] Palestra sobre Automação de TestesJúlio de Lima
 
Tru phuc hinh ca nhan trong cong nghe CAD/CAM - Ly thuyet va thuc te (P.1)
Tru phuc hinh ca nhan trong cong nghe CAD/CAM - Ly thuyet va thuc te (P.1)Tru phuc hinh ca nhan trong cong nghe CAD/CAM - Ly thuyet va thuc te (P.1)
Tru phuc hinh ca nhan trong cong nghe CAD/CAM - Ly thuyet va thuc te (P.1)DentechUMP
 
Colgate Precision - Harvard Business Case Analysis
Colgate Precision - Harvard Business Case AnalysisColgate Precision - Harvard Business Case Analysis
Colgate Precision - Harvard Business Case AnalysisUsha Vijay
 
Mri d stream brochure_final_16 nov 12
Mri d stream brochure_final_16 nov 12Mri d stream brochure_final_16 nov 12
Mri d stream brochure_final_16 nov 12Jhon Arriaga Cordova
 
Principal Component Analysis and Clustering
Principal Component Analysis and ClusteringPrincipal Component Analysis and Clustering
Principal Component Analysis and ClusteringUsha Vijay
 

Viewers also liked (20)

Hosting Dergi - 9.SAYI
Hosting Dergi - 9.SAYIHosting Dergi - 9.SAYI
Hosting Dergi - 9.SAYI
 
Ejercicio 2 programación algoritmos Valentino Spina.
Ejercicio 2 programación  algoritmos Valentino Spina.Ejercicio 2 programación  algoritmos Valentino Spina.
Ejercicio 2 programación algoritmos Valentino Spina.
 
Mi auto biografía
Mi auto biografíaMi auto biografía
Mi auto biografía
 
Reglamento interno itei 2014
Reglamento interno itei 2014Reglamento interno itei 2014
Reglamento interno itei 2014
 
Olena teliga pr.-konf.
Olena teliga pr.-konf.Olena teliga pr.-konf.
Olena teliga pr.-konf.
 
Panorama sobre Teste de Software
Panorama sobre Teste de SoftwarePanorama sobre Teste de Software
Panorama sobre Teste de Software
 
Colgate-Palmolive Company: The Precision Toothbrush
Colgate-Palmolive Company: The Precision ToothbrushColgate-Palmolive Company: The Precision Toothbrush
Colgate-Palmolive Company: The Precision Toothbrush
 
ting-cert-BI
ting-cert-BIting-cert-BI
ting-cert-BI
 
2° informe s. gabriel 2014
2° informe s. gabriel 20142° informe s. gabriel 2014
2° informe s. gabriel 2014
 
[UNIP2015] Testando a Performance de Aplicações Web com JMeter
[UNIP2015] Testando a Performance de Aplicações Web com JMeter[UNIP2015] Testando a Performance de Aplicações Web com JMeter
[UNIP2015] Testando a Performance de Aplicações Web com JMeter
 
DevQA - Da zona de conforto ao comprometimento com a qualidade
DevQA  - Da zona de conforto ao comprometimento com a qualidadeDevQA  - Da zona de conforto ao comprometimento com a qualidade
DevQA - Da zona de conforto ao comprometimento com a qualidade
 
Dem ham bang odontosil final - hn 042016
Dem ham bang odontosil   final - hn 042016Dem ham bang odontosil   final - hn 042016
Dem ham bang odontosil final - hn 042016
 
Ch01 introduction
Ch01 introductionCh01 introduction
Ch01 introduction
 
[TICNOVA2015] Palestra sobre Automação de Testes
[TICNOVA2015] Palestra sobre Automação de Testes[TICNOVA2015] Palestra sobre Automação de Testes
[TICNOVA2015] Palestra sobre Automação de Testes
 
Tru phuc hinh ca nhan trong cong nghe CAD/CAM - Ly thuyet va thuc te (P.1)
Tru phuc hinh ca nhan trong cong nghe CAD/CAM - Ly thuyet va thuc te (P.1)Tru phuc hinh ca nhan trong cong nghe CAD/CAM - Ly thuyet va thuc te (P.1)
Tru phuc hinh ca nhan trong cong nghe CAD/CAM - Ly thuyet va thuc te (P.1)
 
Colgate Precision - Harvard Business Case Analysis
Colgate Precision - Harvard Business Case AnalysisColgate Precision - Harvard Business Case Analysis
Colgate Precision - Harvard Business Case Analysis
 
Scrum for CodeLabs
Scrum for CodeLabsScrum for CodeLabs
Scrum for CodeLabs
 
Mri d stream brochure_final_16 nov 12
Mri d stream brochure_final_16 nov 12Mri d stream brochure_final_16 nov 12
Mri d stream brochure_final_16 nov 12
 
Principal Component Analysis and Clustering
Principal Component Analysis and ClusteringPrincipal Component Analysis and Clustering
Principal Component Analysis and Clustering
 
Fluidmechanics
Fluidmechanics Fluidmechanics
Fluidmechanics
 

Similar to Lecture#8 introduction to array with examples c++

Synapse india dotnet development overloading operater part 3
Synapse india dotnet development overloading operater part 3Synapse india dotnet development overloading operater part 3
Synapse india dotnet development overloading operater part 3Synapseindiappsdevelopment
 
Introduction to cpp (c++)
Introduction to cpp (c++)Introduction to cpp (c++)
Introduction to cpp (c++)Arun Umrao
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfyamew16788
 
lecture7.ppt
lecture7.pptlecture7.ppt
lecture7.pptEdFeranil
 
Csphtp1 07
Csphtp1 07Csphtp1 07
Csphtp1 07HUST
 
I have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdfI have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdfshreeaadithyaacellso
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxarjurakibulhasanrrr7
 
array 2 (1)_merged.pdf
array  2 (1)_merged.pdfarray  2 (1)_merged.pdf
array 2 (1)_merged.pdfPradiptaPaul7
 
Array,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN CArray,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN Cnaveed jamali
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2Mouna Guru
 
using C++ to Write a program to demonstrate an array of 10 elements an.docx
using C++ to Write a program to demonstrate an array of 10 elements an.docxusing C++ to Write a program to demonstrate an array of 10 elements an.docx
using C++ to Write a program to demonstrate an array of 10 elements an.docxslyndon
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-libraryHariz Mustafa
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptxMrMaster11
 

Similar to Lecture#8 introduction to array with examples c++ (20)

Arrays
ArraysArrays
Arrays
 
Synapse india dotnet development overloading operater part 3
Synapse india dotnet development overloading operater part 3Synapse india dotnet development overloading operater part 3
Synapse india dotnet development overloading operater part 3
 
Introduction to cpp (c++)
Introduction to cpp (c++)Introduction to cpp (c++)
Introduction to cpp (c++)
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
 
lecture7.ppt
lecture7.pptlecture7.ppt
lecture7.ppt
 
Csphtp1 07
Csphtp1 07Csphtp1 07
Csphtp1 07
 
Array in Java
Array in JavaArray in Java
Array in Java
 
I have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdfI have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdf
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptx
 
array 2 (1)_merged.pdf
array  2 (1)_merged.pdfarray  2 (1)_merged.pdf
array 2 (1)_merged.pdf
 
Array,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN CArray,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN C
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
using C++ to Write a program to demonstrate an array of 10 elements an.docx
using C++ to Write a program to demonstrate an array of 10 elements an.docxusing C++ to Write a program to demonstrate an array of 10 elements an.docx
using C++ to Write a program to demonstrate an array of 10 elements an.docx
 
C++ practical
C++ practicalC++ practical
C++ practical
 
Chapter 6 arrays part-1
Chapter 6   arrays part-1Chapter 6   arrays part-1
Chapter 6 arrays part-1
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 

More from NUST Stuff

Drag force on a sphere in yield stress fluid
Drag force on a sphere in yield stress fluidDrag force on a sphere in yield stress fluid
Drag force on a sphere in yield stress fluidNUST Stuff
 
Nums entry test 2017 paper
Nums entry test 2017 paperNums entry test 2017 paper
Nums entry test 2017 paperNUST Stuff
 
Nums entry-test-new-syllabus-mbbsc-bds
Nums entry-test-new-syllabus-mbbsc-bdsNums entry-test-new-syllabus-mbbsc-bds
Nums entry-test-new-syllabus-mbbsc-bdsNUST Stuff
 
MCAT Full length paper 8-student_copy_
MCAT Full length paper  8-student_copy_MCAT Full length paper  8-student_copy_
MCAT Full length paper 8-student_copy_NUST Stuff
 
MCAT Full length paper 7-student_copy_
MCAT Full length paper 7-student_copy_MCAT Full length paper 7-student_copy_
MCAT Full length paper 7-student_copy_NUST Stuff
 
MCAT Full length paper 6-student_copy_
MCAT Full length paper  6-student_copy_MCAT Full length paper  6-student_copy_
MCAT Full length paper 6-student_copy_NUST Stuff
 
MCAT Full length paper 5-student_copy_
MCAT Full length paper 5-student_copy_MCAT Full length paper 5-student_copy_
MCAT Full length paper 5-student_copy_NUST Stuff
 
Mcat (original paper 2014)
Mcat (original paper 2014)Mcat (original paper 2014)
Mcat (original paper 2014)NUST Stuff
 
MCAT Full length paper 4-student_copy
MCAT Full length paper  4-student_copyMCAT Full length paper  4-student_copy
MCAT Full length paper 4-student_copyNUST Stuff
 
mcat (original paper 2013)
mcat (original paper 2013)mcat (original paper 2013)
mcat (original paper 2013)NUST Stuff
 
mcat (original paper 2012)
mcat (original paper 2012)mcat (original paper 2012)
mcat (original paper 2012)NUST Stuff
 
MCAT Full length paper 3 final
MCAT Full length paper 3 finalMCAT Full length paper 3 final
MCAT Full length paper 3 finalNUST Stuff
 
MCAT (original paper 2011)
MCAT (original paper 2011)MCAT (original paper 2011)
MCAT (original paper 2011)NUST Stuff
 
mcat (original paper 2010)
 mcat (original paper 2010) mcat (original paper 2010)
mcat (original paper 2010)NUST Stuff
 
MCAT Full length paper 1 (student copy)
MCAT Full length paper 1 (student copy)MCAT Full length paper 1 (student copy)
MCAT Full length paper 1 (student copy)NUST Stuff
 

More from NUST Stuff (20)

Me211 1
Me211 1Me211 1
Me211 1
 
Lab LCA 1 7
Lab LCA 1 7Lab LCA 1 7
Lab LCA 1 7
 
Me211 2
Me211 2Me211 2
Me211 2
 
Me211 4
Me211 4Me211 4
Me211 4
 
Me211 3
Me211 3Me211 3
Me211 3
 
Drag force on a sphere in yield stress fluid
Drag force on a sphere in yield stress fluidDrag force on a sphere in yield stress fluid
Drag force on a sphere in yield stress fluid
 
Nums entry test 2017 paper
Nums entry test 2017 paperNums entry test 2017 paper
Nums entry test 2017 paper
 
Nums entry-test-new-syllabus-mbbsc-bds
Nums entry-test-new-syllabus-mbbsc-bdsNums entry-test-new-syllabus-mbbsc-bds
Nums entry-test-new-syllabus-mbbsc-bds
 
MCAT Full length paper 8-student_copy_
MCAT Full length paper  8-student_copy_MCAT Full length paper  8-student_copy_
MCAT Full length paper 8-student_copy_
 
MCAT Full length paper 7-student_copy_
MCAT Full length paper 7-student_copy_MCAT Full length paper 7-student_copy_
MCAT Full length paper 7-student_copy_
 
MCAT Full length paper 6-student_copy_
MCAT Full length paper  6-student_copy_MCAT Full length paper  6-student_copy_
MCAT Full length paper 6-student_copy_
 
MCAT Full length paper 5-student_copy_
MCAT Full length paper 5-student_copy_MCAT Full length paper 5-student_copy_
MCAT Full length paper 5-student_copy_
 
Mcat (original paper 2014)
Mcat (original paper 2014)Mcat (original paper 2014)
Mcat (original paper 2014)
 
MCAT Full length paper 4-student_copy
MCAT Full length paper  4-student_copyMCAT Full length paper  4-student_copy
MCAT Full length paper 4-student_copy
 
mcat (original paper 2013)
mcat (original paper 2013)mcat (original paper 2013)
mcat (original paper 2013)
 
mcat (original paper 2012)
mcat (original paper 2012)mcat (original paper 2012)
mcat (original paper 2012)
 
MCAT Full length paper 3 final
MCAT Full length paper 3 finalMCAT Full length paper 3 final
MCAT Full length paper 3 final
 
MCAT (original paper 2011)
MCAT (original paper 2011)MCAT (original paper 2011)
MCAT (original paper 2011)
 
mcat (original paper 2010)
 mcat (original paper 2010) mcat (original paper 2010)
mcat (original paper 2010)
 
MCAT Full length paper 1 (student copy)
MCAT Full length paper 1 (student copy)MCAT Full length paper 1 (student copy)
MCAT Full length paper 1 (student copy)
 

Recently uploaded

Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 

Recently uploaded (20)

Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 

Lecture#8 introduction to array with examples c++

  • 1. EC-102 Computer System & Programming Lecture #8 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME
  • 2. Introduction  Arrays – Structures of related data items – Static entity (same size throughout program)
  • 3. Arrays  Array – Consecutive group of memory locations – Same name and type (int, char, etc.)  To refer to an element – Specify array name and position number (index) – Format: arrayname[ position number ] – First element at position 0  N-element array c c[ 0 ], c[ 1 ] … c[ n - 1 ] – Nth element as position N-1
  • 4. Arrays  Array elements like other variables – Assignment, printing for an integer array c c[ 0 ] = 3; cout << c[ 0 ];  Can perform operations inside subscript c[ 5 – 2 ] same as c[3]
  • 5. Arrays c[6] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 Name of array (Note that all elements of this array have the same name, c) c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4] Position number of the element within array c
  • 6. Declaring Arrays  When declaring arrays, specify – Name – Type of array • Any data type – Number of elements – type arrayName[ arraySize ]; int c[ 10 ]; // array of 10 integers float d[ 3284 ]; // array of 3284 floats  Declaring multiple arrays of same type – Use comma separated list, like regular variables int b[ 100 ], x[ 27 ];
  • 7. Examples Using Arrays  Initializing arrays – For loop • Set each element – Initializer list • Specify each element when array declared int n[ 5 ] = { 1, 2, 3, 4, 5 }; • If not enough initializers, rightmost elements 0 – To set every element to same value int n[ 5 ] = { 0 }; – If array size omitted, initializers determine size int n[] = { 1, 2, 3, 4, 5 }; • 5 initializers, therefore 5 element array
  • 8. 1 2 // Initializing an array. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setw; 11 12 int main() 13 { 14 int n[ 10 ]; // n is an array of 10 integers 15 16 // initialize elements of array n to 0 17 for ( int i = 0; i < 10; i++ ) 18 n[ i ] = 0; // set element at location i to 0 19 20 cout << "Element" << setw( 13 ) << "Value" << endl; 21 22 // output contents of array n in tabular format 23 for ( int j = 0; j < 10; j++ ) 24 cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl; 25 Declare a 10-element array of integers. Initialize array to 0 using a for loop. Note that the array has elements n[0] to n[9].
  • 9. 26 return 0; // indicates successful termination 27 28 } // end main Element Value 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0
  • 10. 1 2 // Initializing an array with a declaration. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setw; 11 12 int main() 13 { 14 // use initializer list to initialize array n 15 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; 16 17 cout << "Element" << setw( 13 ) << "Value" << endl; 18 19 // output contents of array n in tabular format 20 for ( int i = 0; i < 10; i++ ) 21 cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl; 22 23 return 0; // indicates successful termination 24 25 } // end main Note the use of the initializer list.
  • 11. Element Value 0 32 1 27 2 64 3 18 4 95 5 14 6 90 7 70 8 60 9 37
  • 12. Examples Using Arrays  Array size – Can be specified with constant variable (const) • const int size = 20; – Constants cannot be changed – Constants must be initialized when declared – Also called named constants or read-only variables
  • 13. 1 2 // Initialize array s to the even integers from 2 to 20. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setw; 11 12 int main() 13 { 14 // constant variable can be used to specify array size 15 const int arraySize = 10; 16 17 int s[ arraySize ]; // array s has 10 elements 18 19 for ( int i = 0; i < arraySize; i++ ) // set the values 20 s[ i ] = 2 + 2 * i; 21 22 cout << "Element" << setw( 13 ) << "Value" << endl; 23 Note use of const keyword. Only const variables can specify array sizes. The program becomes more scalable when we set the array size using a const variable. We can change arraySize, and all the loops will still work (otherwise, we’d have to update every loop in the program).
  • 14. 24 // output contents of array s in tabular format 25 for ( int j = 0; j < arraySize; j++ ) 26 cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl; 27 28 return 0; // indicates successful termination 29 30 } // end main Element Value 0 2 1 4 2 6 3 8 4 10 5 12 6 14 7 16 8 18 9 20
  • 15. 1 2 // Using a properly initialized constant variable. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 const int x = 7; // initialized constant variable 11 12 cout << "The value of constant variable x is: " 13 << x << endl; 14 15 return 0; // indicates successful termination 16 17 } // end main The value of constant variable x is: 7 Proper initialization of const variable.
  • 16. 1 2 // A const object must be initialized. 3 4 int main() 5 { 6 const int x; // Error: x must be initialized 7 8 x = 7; // Error: cannot modify a const variable 9 10 return 0; // indicates successful termination 11 12 } // end main d:cpphtp4_examplesch04Fig04_07.cpp(6) : error C2734: 'x' : const object must be initialized Uninitialized const results in a syntax error. Attempting to modify the const is another error.
  • 17. 1 2 // Compute the sum of the elements of the array. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 const int arraySize = 10; 11 12 int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 13 14 int total = 0; 15 16 // sum contents of array a 17 for ( int i = 0; i < arraySize; i++ ) 18 total += a[ i ]; 19 20 cout << "Total of array element values is " << total << endl; 21 22 return 0; // indicates successful termination 23 24 } // end main Total of array element values is 55
  • 18. 1 2 // Histogram printing program. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setw; 11 12 int main() 13 { 14 const int arraySize = 10; 15 int n[ arraySize ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 16 17 cout << "Element" << setw( 13 ) << "Value" 18 << setw( 17 ) << "Histogram" << endl; 19 20 // for each element of array n, output a bar in histogram 21 for ( int i = 0; i < arraySize; i++ ) { 22 cout << setw( 7 ) << i << setw( 13 ) 23 << n[ i ] << setw( 9 ); 24 25 for ( int j = 0; j < n[ i ]; j++ ) // print one bar 26 cout << '*'; Prints asterisks corresponding to size of array element, n[i].
  • 19. 27 28 cout << endl; // start next line of output 29 30 } // end outer for structure 31 32 return 0; // indicates successful termination 33 34 } // end main Element Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 *