SlideShare a Scribd company logo
Arrays
Course Code: CSC1102 &1103
Dept. of Computer Science
Faculty of Science and Technology
Lecturer No: 5 Week No: 3 (1X1.5 hrs),
4 (2X1.5 hrs)
Semester: Spring23-24
Lecturer: Name & email
Course Title: Introduction to Programming
Lecture 5: Outline
 Arrays
 The concept of array
 Defining arrays
 Initializing arrays
 Character arrays
 Variable length arrays
The concept of array
 Array: a set of ordered data items
 You can define a variable called x, which represents
not a single value, but an entire set of values.
 Each element of the set can then be referenced by
means of a number called an index number or
subscript.
 Mathematics: a subscripted variable, xi, refers to the
ith element x in a set
 Programming: the equivalent notation is x[i]
Declaring an array
 Declaring an array variable:
 Declaring the type of elements that will be contained in the array—such as int,
float, char, etc.
 Declaring the maximum number of elements that will be stored inside the
array.
 The compiler needs this information to determine how much memory space to
reserve for the array.)
 This must be a constant integer value
 The range for valid index values:
 First element is at index 0
 Last element is at index [size-1]
 It is the task of the programmer to make sure that array elements are referred
by indexes that are in the valid range ! The compiler cannot verify this, and it
comes to severe runtime errors !
Arrays - Example
int values[10];
Declares an array of 10 elements of type int
Using Symbolic Constants for array size:
#define N 10
…
int values[N];
Valid indexes:
values[0]=5;
values[9]=7;
Invalid indexes:
values[10]=3;
values[-1]=6;
In memory: elements of an array are stored
at consecutive locations
Arrays - Example
#include <iostream>
#define N 6
int main (void)
{
int values[N];
int index;
for ( index = 0; index < N; ++index ) {
cout<<“Enter value of element”<<index<<endl;
cin>>values[index];
}
for ( index = 0; index < N; ++index )
cout<< “values[“<<i<<“]=“<< values[index]<<endl;
return 0;
}
Using symbolic
constants for array
size makes program
more general
Typical loop for
processing all
elements of an array
#include <iostream>
using namespace std;
int main (void){
int NA, NB;
cout<<"Enter NA and NB"<<endl;
cin>>NA>>NB;
int b[NB],a[NA];
int index;
for ( index = 0; index < NB; index++ )
b[index]=10+index;
for ( index = 0; index < NA+2; ++index )
a[index]=index;
for ( index = 0; index < NA+2; ++index )
cout<<"a ["<<index<<"]= "<<a[index]<<endl;
for ( index = 0; index < NB; ++index )
cout<<"b ["<<index<<"] ="<< b[index]<<endl;
return 0;
}
What goes wrong if an index goes out of range ?
Exercise: Fibonacci numbers
// Program to generate the first 15 Fibonacci numbers
#include <iostream>
using namespace std;
int main (void)
{
int Fibonacci[15], i;
Fibonacci[0] = 0; // by definition
Fibonacci[1] = 1; // ditto
for ( i = 2; i < 15; ++i )
Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];
for ( i = 0; i < 15; ++i )
cout<< "Fibonacci["<<i<<"]="<<Fibonacci[i]<<endl;
return 0;
}
Exercise: Prime numbers
 An improved method for generating prime numbers involves the notion that a
number p is prime if it is not evenly divisible by any other prime number
 Another improvement: a number p is prime if there is no prime number smaller than
its square root, so that it is evenly divisible by it
primes
0 1 2
2 3 5 7 11
primeIndex
Is p the next
prime number
here ?
If you can find a
primes[i] < sqrt(p)
that divides evenly
p, than p is not
prime
Exercise: Prime numbers
#include <iostream>
using namespace std;
// Modified program to generate prime numbers
int main (void) {
int p, i, primes[50], primeIndex = 2; bool isPrime;
primes[0] = 2; primes[1] = 3;
for ( p = 5; p <= 50; p = p + 2 ) {
isPrime = true;
for ( i = 1; isPrime && p / primes[i] >= primes[i]; ++i )
if ( p % primes[i] == 0 )
isPrime = false;
if ( isPrime == true ) {
primes[primeIndex] = p;
++primeIndex;
}
}
for ( i = 0; i < primeIndex; ++i )
cout<<"Primes["<<i<<"]"<<primes[i]<<endl;
return 0;
}
Initializing arrays
 int counters[5] = { 0, 0, 0, 0, 0 };
 char letters[5] = { 'a', 'b', 'c', 'd', 'e' };
 float sample_data[500] = { 100.0, 300.0, 500.5 };
 The C++ language allows you to define an array without
specifying the number of elements. If this is done, the size of
the array is determined automatically based on the number of
initialization elements: int counters[] = { 0, 0, 0, 0, 0 };
Character arrays
#include <stdio.h>
int main (void)
{
char word[] = { 'H', 'e', 'l', 'l', 'o', '!' };
int i;
for ( i = 0; i < 6; ++i )
cout<<word[i]);
return 0;
}
a special case of character arrays: the character string type =>in a later chapter
Example: Base conversion using arrays
#include <iostream>
using namespace std;
int main (void)
{
const char baseDigits[16] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
int convertedNumber[64];
long int numberToConvert;
int nextDigit, base, index = 0;
// get the number and the base
cout<<"Number to be converted? "<<endl;
cin>>numberToConvert;
cout<<"Base? "<<endl;
cin>>base;
Example continued
// convert to the indicated base
do {
convertedNumber[index] = numberToConvert % base;
++index;
numberToConvert = numberToConvert / base;
}
while ( numberToConvert != 0 );
// display the results in reverse order
cout<<"Converted number = ";
for (--index; index >= 0; --index )
{
nextDigit = convertedNumber[index];
cout<<baseDigits[nextDigit];
}
return 0;
}
 Dynamic memory allocation in C++ means allocating memory
manually by programmer when needed.
 How is it different from memory allocated to normal variables?
Previously used variables like “int a”, “char str[10]”, etc.,
memory is automatically allocated and deallocated. For
dynamically allocated memory it is programmers responsibility
to deallocate memory when no longer needed. If programmer
doesn’t deallocate memory, it causes memory leak (memory is
not deallocated until program terminates).
 How is memory allocated/deallocated in C++?
C++ has two operators new and delete that perform the task of
allocating and freeing the memory. The allocation is done at
runtime.
new and delete operators in C++ for dynamic
memory
Example:Variable length arrays
#include <iostream>
using namespace std;
int main() {
int n;
int i;
cout<<"How many elements do you have? "<<endl;
cin>>n;
int *a = new int[n];
for(i = 0; i < n; i++)
cin>>a[i];
for(i = 0; i < n; i++)
cout<< a[i];
delete a;
return 0;
}
Pointer is used so that we know where
the memory is allocated.
new operator is responsible for allocating
the memory
It indicates, memory is allocated for this
type of datatype, here it is int
If we want to allocate memory for multiple data’s we
can create array by providing any positive integer
number or a variable having similar type value
Now when we are
done using our
allocated memory
which is where a
pointer is pointing
,we must
deallocate it using
delete operator.

More Related Content

PPTX
Lecture-5_Arrays.pptx FOR EDUCATIONAL PURPOSE
PPT
2 arrays
PPTX
Chapter-Five.pptx
PDF
05_Arrays C plus Programming language22.pdf
PPT
Lecture#8 introduction to array with examples c++
PPTX
Lecture 7
PPTX
Arrays matrix 2020 ab
PPTX
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
Lecture-5_Arrays.pptx FOR EDUCATIONAL PURPOSE
2 arrays
Chapter-Five.pptx
05_Arrays C plus Programming language22.pdf
Lecture#8 introduction to array with examples c++
Lecture 7
Arrays matrix 2020 ab
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx

Similar to Lecture 5Arrays on c++ for Beginner.pptx (20)

PPTX
C_Arrays(3)bzxhgvxgxg.xhjvxugvxuxuxuxvxugvx.pptx
PPT
02 c++ Array Pointer
PDF
Arrays and library functions
PPTX
Lecture 9
PDF
array 2 (1)_merged.pdf
PDF
C++ Course - Lesson 2
PPTX
Data structure.pptx
PPT
Lecture#5-Arrays-oral patholohu hfFoP.ppt
PDF
PPTX
Array,string structures. Best presentation pptx
PPT
PPTX
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
PPTX
Arrays_in_c++.pptx
PDF
Arrays and library functions
PDF
Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis S...
PPT
show the arrays ppt for first year students
PPT
C array and Initialisation and declaration
PPTX
CSCI 238 Chapter 08 Arrays Textbook Slides
PPTX
Array 1D.................................pptx
PDF
Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis S...
C_Arrays(3)bzxhgvxgxg.xhjvxugvxuxuxuxvxugvx.pptx
02 c++ Array Pointer
Arrays and library functions
Lecture 9
array 2 (1)_merged.pdf
C++ Course - Lesson 2
Data structure.pptx
Lecture#5-Arrays-oral patholohu hfFoP.ppt
Array,string structures. Best presentation pptx
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
Arrays_in_c++.pptx
Arrays and library functions
Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis S...
show the arrays ppt for first year students
C array and Initialisation and declaration
CSCI 238 Chapter 08 Arrays Textbook Slides
Array 1D.................................pptx
Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis S...
Ad

Recently uploaded (20)

PPT
Gsisgdkddkvdgjsjdvdbdbdbdghjkhgcvvkkfcxxfg
PPTX
OnePlus 13R – ⚡ All-Rounder King Performance: Snapdragon 8 Gen 3 – same as iQ...
PPTX
The Stock at arrangement the stock and product.pptx
PPTX
Discovering the LMA Course by Tim Han.pptx
PPTX
cse couse aefrfrqewrbqwrgbqgvq2w3vqbvq23rbgw3rnw345
PPTX
PMP (Project Management Professional) course prepares individuals
PPTX
Cerebral_Palsy_Detailed_Presentation.pptx
PPTX
1751884730-Visual Basic -Unitj CS B.pptx
PPTX
Sports and Dance -lesson 3 powerpoint presentation
PPTX
chapter 3_bem.pptxKLJLKJLKJLKJKJKLJKJKJKHJH
PPTX
Condensed_Food_Science_Lecture1_Precised.pptx
PPT
BCH3201 (Enzymes and biocatalysis)-JEB (1).ppt
PDF
Prostaglandin E2.pdf orthoodontics op kharbanda
PPTX
microtomy kkk. presenting to cryst in gl
PPTX
normal_menstrual_cycle_,,physiology.PPTX
PDF
Biography of Mohammad Anamul Haque Nayan
DOC
field study for teachers graduating samplr
PDF
Daisia Frank: Strategy-Driven Real Estate with Heart.pdf
PDF
Blue-Modern-Elegant-Presentation (1).pdf
PPTX
1-4 Chaptedjkfhkshdkfjhalksjdhfkjshdljkfhrs.pptx
Gsisgdkddkvdgjsjdvdbdbdbdghjkhgcvvkkfcxxfg
OnePlus 13R – ⚡ All-Rounder King Performance: Snapdragon 8 Gen 3 – same as iQ...
The Stock at arrangement the stock and product.pptx
Discovering the LMA Course by Tim Han.pptx
cse couse aefrfrqewrbqwrgbqgvq2w3vqbvq23rbgw3rnw345
PMP (Project Management Professional) course prepares individuals
Cerebral_Palsy_Detailed_Presentation.pptx
1751884730-Visual Basic -Unitj CS B.pptx
Sports and Dance -lesson 3 powerpoint presentation
chapter 3_bem.pptxKLJLKJLKJLKJKJKLJKJKJKHJH
Condensed_Food_Science_Lecture1_Precised.pptx
BCH3201 (Enzymes and biocatalysis)-JEB (1).ppt
Prostaglandin E2.pdf orthoodontics op kharbanda
microtomy kkk. presenting to cryst in gl
normal_menstrual_cycle_,,physiology.PPTX
Biography of Mohammad Anamul Haque Nayan
field study for teachers graduating samplr
Daisia Frank: Strategy-Driven Real Estate with Heart.pdf
Blue-Modern-Elegant-Presentation (1).pdf
1-4 Chaptedjkfhkshdkfjhalksjdhfkjshdljkfhrs.pptx
Ad

Lecture 5Arrays on c++ for Beginner.pptx

  • 1. Arrays Course Code: CSC1102 &1103 Dept. of Computer Science Faculty of Science and Technology Lecturer No: 5 Week No: 3 (1X1.5 hrs), 4 (2X1.5 hrs) Semester: Spring23-24 Lecturer: Name & email Course Title: Introduction to Programming
  • 2. Lecture 5: Outline  Arrays  The concept of array  Defining arrays  Initializing arrays  Character arrays  Variable length arrays
  • 3. The concept of array  Array: a set of ordered data items  You can define a variable called x, which represents not a single value, but an entire set of values.  Each element of the set can then be referenced by means of a number called an index number or subscript.  Mathematics: a subscripted variable, xi, refers to the ith element x in a set  Programming: the equivalent notation is x[i]
  • 4. Declaring an array  Declaring an array variable:  Declaring the type of elements that will be contained in the array—such as int, float, char, etc.  Declaring the maximum number of elements that will be stored inside the array.  The compiler needs this information to determine how much memory space to reserve for the array.)  This must be a constant integer value  The range for valid index values:  First element is at index 0  Last element is at index [size-1]  It is the task of the programmer to make sure that array elements are referred by indexes that are in the valid range ! The compiler cannot verify this, and it comes to severe runtime errors !
  • 5. Arrays - Example int values[10]; Declares an array of 10 elements of type int Using Symbolic Constants for array size: #define N 10 … int values[N]; Valid indexes: values[0]=5; values[9]=7; Invalid indexes: values[10]=3; values[-1]=6; In memory: elements of an array are stored at consecutive locations
  • 6. Arrays - Example #include <iostream> #define N 6 int main (void) { int values[N]; int index; for ( index = 0; index < N; ++index ) { cout<<“Enter value of element”<<index<<endl; cin>>values[index]; } for ( index = 0; index < N; ++index ) cout<< “values[“<<i<<“]=“<< values[index]<<endl; return 0; } Using symbolic constants for array size makes program more general Typical loop for processing all elements of an array
  • 7. #include <iostream> using namespace std; int main (void){ int NA, NB; cout<<"Enter NA and NB"<<endl; cin>>NA>>NB; int b[NB],a[NA]; int index; for ( index = 0; index < NB; index++ ) b[index]=10+index; for ( index = 0; index < NA+2; ++index ) a[index]=index; for ( index = 0; index < NA+2; ++index ) cout<<"a ["<<index<<"]= "<<a[index]<<endl; for ( index = 0; index < NB; ++index ) cout<<"b ["<<index<<"] ="<< b[index]<<endl; return 0; } What goes wrong if an index goes out of range ?
  • 8. Exercise: Fibonacci numbers // Program to generate the first 15 Fibonacci numbers #include <iostream> using namespace std; int main (void) { int Fibonacci[15], i; Fibonacci[0] = 0; // by definition Fibonacci[1] = 1; // ditto for ( i = 2; i < 15; ++i ) Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1]; for ( i = 0; i < 15; ++i ) cout<< "Fibonacci["<<i<<"]="<<Fibonacci[i]<<endl; return 0; }
  • 9. Exercise: Prime numbers  An improved method for generating prime numbers involves the notion that a number p is prime if it is not evenly divisible by any other prime number  Another improvement: a number p is prime if there is no prime number smaller than its square root, so that it is evenly divisible by it primes 0 1 2 2 3 5 7 11 primeIndex Is p the next prime number here ? If you can find a primes[i] < sqrt(p) that divides evenly p, than p is not prime
  • 10. Exercise: Prime numbers #include <iostream> using namespace std; // Modified program to generate prime numbers int main (void) { int p, i, primes[50], primeIndex = 2; bool isPrime; primes[0] = 2; primes[1] = 3; for ( p = 5; p <= 50; p = p + 2 ) { isPrime = true; for ( i = 1; isPrime && p / primes[i] >= primes[i]; ++i ) if ( p % primes[i] == 0 ) isPrime = false; if ( isPrime == true ) { primes[primeIndex] = p; ++primeIndex; } } for ( i = 0; i < primeIndex; ++i ) cout<<"Primes["<<i<<"]"<<primes[i]<<endl; return 0; }
  • 11. Initializing arrays  int counters[5] = { 0, 0, 0, 0, 0 };  char letters[5] = { 'a', 'b', 'c', 'd', 'e' };  float sample_data[500] = { 100.0, 300.0, 500.5 };  The C++ language allows you to define an array without specifying the number of elements. If this is done, the size of the array is determined automatically based on the number of initialization elements: int counters[] = { 0, 0, 0, 0, 0 };
  • 12. Character arrays #include <stdio.h> int main (void) { char word[] = { 'H', 'e', 'l', 'l', 'o', '!' }; int i; for ( i = 0; i < 6; ++i ) cout<<word[i]); return 0; } a special case of character arrays: the character string type =>in a later chapter
  • 13. Example: Base conversion using arrays #include <iostream> using namespace std; int main (void) { const char baseDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; int convertedNumber[64]; long int numberToConvert; int nextDigit, base, index = 0; // get the number and the base cout<<"Number to be converted? "<<endl; cin>>numberToConvert; cout<<"Base? "<<endl; cin>>base;
  • 14. Example continued // convert to the indicated base do { convertedNumber[index] = numberToConvert % base; ++index; numberToConvert = numberToConvert / base; } while ( numberToConvert != 0 ); // display the results in reverse order cout<<"Converted number = "; for (--index; index >= 0; --index ) { nextDigit = convertedNumber[index]; cout<<baseDigits[nextDigit]; } return 0; }
  • 15.  Dynamic memory allocation in C++ means allocating memory manually by programmer when needed.  How is it different from memory allocated to normal variables? Previously used variables like “int a”, “char str[10]”, etc., memory is automatically allocated and deallocated. For dynamically allocated memory it is programmers responsibility to deallocate memory when no longer needed. If programmer doesn’t deallocate memory, it causes memory leak (memory is not deallocated until program terminates).  How is memory allocated/deallocated in C++? C++ has two operators new and delete that perform the task of allocating and freeing the memory. The allocation is done at runtime. new and delete operators in C++ for dynamic memory
  • 16. Example:Variable length arrays #include <iostream> using namespace std; int main() { int n; int i; cout<<"How many elements do you have? "<<endl; cin>>n; int *a = new int[n]; for(i = 0; i < n; i++) cin>>a[i]; for(i = 0; i < n; i++) cout<< a[i]; delete a; return 0; } Pointer is used so that we know where the memory is allocated. new operator is responsible for allocating the memory It indicates, memory is allocated for this type of datatype, here it is int If we want to allocate memory for multiple data’s we can create array by providing any positive integer number or a variable having similar type value Now when we are done using our allocated memory which is where a pointer is pointing ,we must deallocate it using delete operator.

Editor's Notes

  • #11: A simplified example will be better