SlideShare a Scribd company logo
Lecture 8
                   Arrays



TCP1231 Computer Programming I   1
Objectives

   • To Learn about arrays
   • Explore how to declare and manipulate data
     into arrays
   • Understand the meaning of “array index out of
     bounds”
   • Become familiar with the restrictions on array
     processing




   TCP1231 Computer Programming I       2
Introduction to Arrays
• Given this scenario …
  – Write a program that reads five numbers, and
    performs some manipulations on these
    numbers, such as find their sum, and print the
    numbers in reverse order
  – We could use five individual variables of type
    int, but five variables are hard to keep track of
  – We could make program more readable by
    giving the variables related names such as
    item1, item2, item3, and so forth, but this
    solution becomes absurd if the number of items
    is very large

   TCP1231 Computer Programming I          3
Program: Read five numbers, find their sum, and print
the numbers in reverse order
#include <iostream>
using namespace std;

int main()
{
  int item0, item1, item2, item3, item4;
  int sum;

    cout<<"Enter five integers: ";
    cin>>item0>>item1>>item2>>item3>>item4 <<endl;

    sum = item0 + item1 + item2 + item3 + item4;

    cout<<"The sum of the numbers = "<<sum<<endl;
    cout<<"The numbers in reverse order are: ";
    cout<<item4<<" "<<item3<<" "<<item2<<" " << item1<<" "<<item0<<endl;
    return 0;
}


       TCP1231 Computer Programming I                  4
Arrays
Arrays: are a series of elements (variables) of the same type placed consecutively in
memory that can be individually referenced by adding an index to a unique name.
Explanations: This means that, for example, we can store 5 values of type int without
having to declare 5 different variables each with a different identifier. Instead, using an
array we can store 5 different values of the same type, int for example, with a unique
identifier.

For example, an array to contain 5 integer values of type int called item could be
represented this way:

                                      int item[5];
                      0           1           2           3          4
       item
                     int


where each blank panel represents an element of the array, that in this case are
integer values of type int. These are numbered from 0 to 4 since in arrays the
first index is always 0, independently of its length .

      TCP1231 Computer Programming I                                5
Arrays
Like any other variable, an array must be declared before it is used.
A typical declaration for an array in C++ is:
                        type name [elements];
where type is a valid object type (int, float...), name is a valid
variable identifier and the elements field, that is enclosed within
brackets [], specifies how many of these elements the array
contains. Therefore, to declare item as shown above it is as simple
as the following sentence:
                       int item[5];
NOTE: The elements field within brackets [] when declaring an
array must be a constant value, since arrays are blocks of static
memory of a given size and the compiler must be able to determine
exactly how much memory it must assign to the array before any
instruction is considered.
     TCP1231 Computer Programming I                6
Initializing arrays
When declaring an array of local scope (within a function), if we
do not specify otherwise, it will not be initialized, so its content is
undetermined until we store some values in it. If we declare a
global array (outside any function) its content will be initialized
with all its elements filled with zeros. Thus, if in the global scope
we declare:
                            int item[5];
every element of item will be set initially to 0:


                 0        1         2        3        4

     item            0        0         0        0        0




     TCP1231 Computer Programming I                  7
Initializing arrays
When we declare an Array, we have the possibility to assign initial
values to each one of its elements using curly brackets { }. For
example:
             int item [5] = { 16, 2, 77, 40, 12071 };
This declaration would have created an array like the following one:

                   0          1         2         3          4

      item             16         2         77        44     12071




The number of elements in the array that we initialized within curly brackets { }
must match the length in elements that we declared for the array enclosed within
square brackets [ ].

                 int item [] = { 16, 2, 77, 40, 12071 };

      TCP1231 Computer Programming I                        8
Program 1: Read five numbers, find their sum, and print
the numbers in reverse order
int main()
{
         int item[5]; //declare an array item of five components
         int sum=0;

         cout<<"Enter five numbers."<<endl;

         cin>>item[0] >> item[1] >> item[2] >> item[3] >> item[4] >> item[5] ;
         sum = sum + item[0] + item[1] + item[2] + item[3] + item[4] + item[5];

         cout<<"The sum of the numbers is: "<<sum<<endl;

         cout<<"The numbers in reverse order are: ";
         cout<<item[4]<<“ "<<item[3]<<" "<<item[2]<<" "
                 << item[1]<<" "<<item[0]<<endl;
         return 0;
}

      TCP1231 Computer Programming I                         9
Program 2: Read five numbers, find their sum, and
print the numbers in reverse order
int main()
{
         int item[5]; //declare an array item of five components
         int sum=0, int counter;
         cout<<"Enter five numbers."<<endl;
         for(counter = 0; counter < 5; counter++)
         {
                   cin>>item[counter];
                   sum = sum + item[counter];
         }
         cout<<"The sum of the numbers is: "<<sum<<endl;
         cout<<"The numbers in reverse order are: ";
         for(counter = 4; counter >= 0; counter--)
                   cout<<item[counter]<<" ";
         return 0;
}

     TCP1231 Computer Programming I                         10
Program 3: Read five numbers, find and print the
smallest number among them
int main ()
{
   double a[10];
   double sml;
   for (int i=0; i<=4; i++)
      cin >> a[i];
   sml=a[0];
   for (int i=1; i<=4; i++)
   {
      if (sml > a[i])
            sml=a[i];
   }
   cout << "the smallest number is: " << sml;

    getch();
    return 0;
}

       TCP1231 Computer Programming I           11
Access the values of an Array
• The values of an array can be access using following format:
  name[index]
• From previous example, item has 5 elements and each of those
  elements is of type int
   To store the value of 33 in the second element of item:
   item[1] = 33;
   To pass the value of the second element of item to the variable
     temporary:
   temporary = item[1];
• Notice that the second element of item is specified item[1], since
  first is item[0], therefore, the second is item[1]. By this same
  reason, its last element is item[4]. If we write item[5], we will be
  acceding to the sixth element of item and therefore exceeding the
  size of the array

     TCP1231 Computer Programming I                 12
Access the values of an Array
• In C++ it is perfectly valid to exceed the valid range of indices for
  an Array, which can create problems since they do not cause
  compilation errors but they can cause unexpected results or
  serious errors during execution. The reason why this is allowed
  will be seen farther ahead when we begin to use pointers
• At this point it is important to be able to clearly distinguish
  between the two uses that brackets [ ] have related to arrays
   – To set the size of arrays when declaring them
       int item[5]; // declaration of a new Array (begins with a type
      name)
   – To specify indices for a concrete array element when referring
      to it
      item[1] = 33; // access to an element of the Array


     TCP1231 Computer Programming I                 13
Sort Algorithm (Selection)
1. Search for the smallest value in the array – the smallest value is the value in a[3]
2. Place the smallest value in a[0], and place the value that was in a[0] in a[3], the
   location where the smallest was found
3. Starting at a[1], find the smallest remaining value, swap it with the value
   currently in a[1]
4. Starting at a[2], continue the process until the array is sorted




                                                        14
            http://www.cosc.canterbury.ac.nz/people/mukundan/dsal/appldsal.html
       TCP1231 Computer Programming I
int main ()                             for (int k=0; k<=3; k++)
{                                          {
   double a[5];                               sml=a[k];
   double sml, temp;                          Psml=k;
   int Psml; //index of small                 for (int i=k; i<=4; i++)
                                                 if (sml > a[i])
  for (int i=0; i<=4; i++)                          {
   {                                                   sml=a[i];
     cout << “enter a[“<< i <<“] ” ;                   Psml=i;
     cin >> a[i];                                   }
   }                                          temp=a[Psml];
  cout << "nthe current array ";             a[Psml]=a[k];
  for (int i=0; i<=4; i++)                    a[k]=temp;
     cout << a[i] << 't';                 }
                                           cout << "nthe sorted array: ";
                                           for (int i=0; i<=4; i++)
                                              cout << a[i] << 't';

                                            return 0;
                                        }

       TCP1231 Computer Programming I                   15
Sort Algorithm (Bubble)
#include <iostream>                       for (i=0; i<=4; i++)
using namespace std;                            for (j=0; j<=3; j++)
                                                      if (a[j]>a[j+1])
int main ()                                           {
{                                                        temp=a[j];
   int a[5];                                             a[j]=a[j+1];
   int i,j, temp;                                        a[j+1]=temp;
                                                      }
  for (int i=0; i<=4; i++)                   cout << "nthe sorted array: ";
   {                                         for (i=0; i<=4; i++)
     cout << "enter a["<< i <<"] ";             cout << a[i] << 't';
     cin >> a[i];
   }                                          return 0;
                                          }
  cout << "nthe current array ";
  for (int i=0; i<=4; i++)
     cout << a[i] << 't';


                                                         16
             http://www.cosc.canterbury.ac.nz/people/mukundan/dsal/appldsal.html
        TCP1231 Computer Programming I
Sequential Search Algorithm
•       Sequential search is to determine the index i position
        of an object ‘X’ in an array A
                                                           int search (const int a[], int
 target    8                                               number_used, int target)
                                                           {
          [0]   [1]   [2]   [3]   [4]   [5]   [6]   [7]
                                                              int index = 0;
                                                              bool found = false;
    a     2     7     3      8    4     12     9       5      while ((!found) && (index <
                                                                       number_used))
                                                                   if (target == a[index])
                             Found “8” in position 4                     found = true;
                                                                    else
                                                                         index++;
                                                               if (found)
                                                                  return index;
                                                               else
                                                                  return -1;
                                                           }



                                                           17
               http://www.cosc.canterbury.ac.nz/people/mukundan/dsal/appldsal.html
          TCP1231 Computer Programming I
THE END




TCP1231 Computer Programming I   18

More Related Content

What's hot

Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
C++ Language
C++ LanguageC++ Language
C++ Language
Syed Zaid Irshad
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
ManjeeraBhargavi Varanasi
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2docSrikanth
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6rohassanie
 
Pointers
PointersPointers
Pointers
sanya6900
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
harman kaur
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3rohassanie
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperDeepak Singh
 
C++ theory
C++ theoryC++ theory
C++ theory
Shyam Khant
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
HalaiHansaika
 
computer science sample papers 2
computer science sample papers 2computer science sample papers 2
computer science sample papers 2
Swarup Kumar Boro
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
Chaand Sheikh
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3 rohassanie
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
Sreedhar Chowdam
 
Ch7 C++
Ch7 C++Ch7 C++

What's hot (20)

Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
 
Pointers
PointersPointers
Pointers
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
 
C++ theory
C++ theoryC++ theory
C++ theory
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Functions
FunctionsFunctions
Functions
 
computer science sample papers 2
computer science sample papers 2computer science sample papers 2
computer science sample papers 2
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
Ch7 C++
Ch7 C++Ch7 C++
Ch7 C++
 

Similar to Computer Programming- Lecture 8

Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
MrMaster11
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
GC University Faisalabad
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2Mohamed Ahmed
 
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
arjurakibulhasanrrr7
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-libraryHariz Mustafa
 
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
yamew16788
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptx
JumanneChiyanda
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
Mrhaider4
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
C++ Homework Help
 
Chap 6 c++
Chap 6 c++Chap 6 c++
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
Martin Chapman
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Meghaj Mallick
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1sotlsoc
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
Intro C# Book
 
Advance data structure & algorithm
Advance data structure & algorithmAdvance data structure & algorithm
Advance data structure & algorithm
K Hari Shankar
 

Similar to Computer Programming- Lecture 8 (20)

Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
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
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
 
Lecture1 classes2
Lecture1 classes2Lecture1 classes2
Lecture1 classes2
 
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
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptx
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
Array assignment
Array assignmentArray assignment
Array assignment
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
 
Lec2
Lec2Lec2
Lec2
 
Advance data structure & algorithm
Advance data structure & algorithmAdvance data structure & algorithm
Advance data structure & algorithm
 

Recently uploaded

Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
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
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
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
 
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
 
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
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
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
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
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
 
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
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
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
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 

Recently uploaded (20)

Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
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
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
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
 
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
 
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 ...
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
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...
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
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...
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
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
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 

Computer Programming- Lecture 8

  • 1. Lecture 8 Arrays TCP1231 Computer Programming I 1
  • 2. Objectives • To Learn about arrays • Explore how to declare and manipulate data into arrays • Understand the meaning of “array index out of bounds” • Become familiar with the restrictions on array processing TCP1231 Computer Programming I 2
  • 3. Introduction to Arrays • Given this scenario … – Write a program that reads five numbers, and performs some manipulations on these numbers, such as find their sum, and print the numbers in reverse order – We could use five individual variables of type int, but five variables are hard to keep track of – We could make program more readable by giving the variables related names such as item1, item2, item3, and so forth, but this solution becomes absurd if the number of items is very large TCP1231 Computer Programming I 3
  • 4. Program: Read five numbers, find their sum, and print the numbers in reverse order #include <iostream> using namespace std; int main() { int item0, item1, item2, item3, item4; int sum; cout<<"Enter five integers: "; cin>>item0>>item1>>item2>>item3>>item4 <<endl; sum = item0 + item1 + item2 + item3 + item4; cout<<"The sum of the numbers = "<<sum<<endl; cout<<"The numbers in reverse order are: "; cout<<item4<<" "<<item3<<" "<<item2<<" " << item1<<" "<<item0<<endl; return 0; } TCP1231 Computer Programming I 4
  • 5. Arrays Arrays: are a series of elements (variables) of the same type placed consecutively in memory that can be individually referenced by adding an index to a unique name. Explanations: This means that, for example, we can store 5 values of type int without having to declare 5 different variables each with a different identifier. Instead, using an array we can store 5 different values of the same type, int for example, with a unique identifier. For example, an array to contain 5 integer values of type int called item could be represented this way: int item[5]; 0 1 2 3 4 item int where each blank panel represents an element of the array, that in this case are integer values of type int. These are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length . TCP1231 Computer Programming I 5
  • 6. Arrays Like any other variable, an array must be declared before it is used. A typical declaration for an array in C++ is: type name [elements]; where type is a valid object type (int, float...), name is a valid variable identifier and the elements field, that is enclosed within brackets [], specifies how many of these elements the array contains. Therefore, to declare item as shown above it is as simple as the following sentence: int item[5]; NOTE: The elements field within brackets [] when declaring an array must be a constant value, since arrays are blocks of static memory of a given size and the compiler must be able to determine exactly how much memory it must assign to the array before any instruction is considered. TCP1231 Computer Programming I 6
  • 7. Initializing arrays When declaring an array of local scope (within a function), if we do not specify otherwise, it will not be initialized, so its content is undetermined until we store some values in it. If we declare a global array (outside any function) its content will be initialized with all its elements filled with zeros. Thus, if in the global scope we declare: int item[5]; every element of item will be set initially to 0: 0 1 2 3 4 item 0 0 0 0 0 TCP1231 Computer Programming I 7
  • 8. Initializing arrays When we declare an Array, we have the possibility to assign initial values to each one of its elements using curly brackets { }. For example: int item [5] = { 16, 2, 77, 40, 12071 }; This declaration would have created an array like the following one: 0 1 2 3 4 item 16 2 77 44 12071 The number of elements in the array that we initialized within curly brackets { } must match the length in elements that we declared for the array enclosed within square brackets [ ]. int item [] = { 16, 2, 77, 40, 12071 }; TCP1231 Computer Programming I 8
  • 9. Program 1: Read five numbers, find their sum, and print the numbers in reverse order int main() { int item[5]; //declare an array item of five components int sum=0; cout<<"Enter five numbers."<<endl; cin>>item[0] >> item[1] >> item[2] >> item[3] >> item[4] >> item[5] ; sum = sum + item[0] + item[1] + item[2] + item[3] + item[4] + item[5]; cout<<"The sum of the numbers is: "<<sum<<endl; cout<<"The numbers in reverse order are: "; cout<<item[4]<<“ "<<item[3]<<" "<<item[2]<<" " << item[1]<<" "<<item[0]<<endl; return 0; } TCP1231 Computer Programming I 9
  • 10. Program 2: Read five numbers, find their sum, and print the numbers in reverse order int main() { int item[5]; //declare an array item of five components int sum=0, int counter; cout<<"Enter five numbers."<<endl; for(counter = 0; counter < 5; counter++) { cin>>item[counter]; sum = sum + item[counter]; } cout<<"The sum of the numbers is: "<<sum<<endl; cout<<"The numbers in reverse order are: "; for(counter = 4; counter >= 0; counter--) cout<<item[counter]<<" "; return 0; } TCP1231 Computer Programming I 10
  • 11. Program 3: Read five numbers, find and print the smallest number among them int main () { double a[10]; double sml; for (int i=0; i<=4; i++) cin >> a[i]; sml=a[0]; for (int i=1; i<=4; i++) { if (sml > a[i]) sml=a[i]; } cout << "the smallest number is: " << sml; getch(); return 0; } TCP1231 Computer Programming I 11
  • 12. Access the values of an Array • The values of an array can be access using following format: name[index] • From previous example, item has 5 elements and each of those elements is of type int To store the value of 33 in the second element of item: item[1] = 33; To pass the value of the second element of item to the variable temporary: temporary = item[1]; • Notice that the second element of item is specified item[1], since first is item[0], therefore, the second is item[1]. By this same reason, its last element is item[4]. If we write item[5], we will be acceding to the sixth element of item and therefore exceeding the size of the array TCP1231 Computer Programming I 12
  • 13. Access the values of an Array • In C++ it is perfectly valid to exceed the valid range of indices for an Array, which can create problems since they do not cause compilation errors but they can cause unexpected results or serious errors during execution. The reason why this is allowed will be seen farther ahead when we begin to use pointers • At this point it is important to be able to clearly distinguish between the two uses that brackets [ ] have related to arrays – To set the size of arrays when declaring them int item[5]; // declaration of a new Array (begins with a type name) – To specify indices for a concrete array element when referring to it item[1] = 33; // access to an element of the Array TCP1231 Computer Programming I 13
  • 14. Sort Algorithm (Selection) 1. Search for the smallest value in the array – the smallest value is the value in a[3] 2. Place the smallest value in a[0], and place the value that was in a[0] in a[3], the location where the smallest was found 3. Starting at a[1], find the smallest remaining value, swap it with the value currently in a[1] 4. Starting at a[2], continue the process until the array is sorted 14 http://www.cosc.canterbury.ac.nz/people/mukundan/dsal/appldsal.html TCP1231 Computer Programming I
  • 15. int main () for (int k=0; k<=3; k++) { { double a[5]; sml=a[k]; double sml, temp; Psml=k; int Psml; //index of small for (int i=k; i<=4; i++) if (sml > a[i]) for (int i=0; i<=4; i++) { { sml=a[i]; cout << “enter a[“<< i <<“] ” ; Psml=i; cin >> a[i]; } } temp=a[Psml]; cout << "nthe current array "; a[Psml]=a[k]; for (int i=0; i<=4; i++) a[k]=temp; cout << a[i] << 't'; } cout << "nthe sorted array: "; for (int i=0; i<=4; i++) cout << a[i] << 't'; return 0; } TCP1231 Computer Programming I 15
  • 16. Sort Algorithm (Bubble) #include <iostream> for (i=0; i<=4; i++) using namespace std; for (j=0; j<=3; j++) if (a[j]>a[j+1]) int main () { { temp=a[j]; int a[5]; a[j]=a[j+1]; int i,j, temp; a[j+1]=temp; } for (int i=0; i<=4; i++) cout << "nthe sorted array: "; { for (i=0; i<=4; i++) cout << "enter a["<< i <<"] "; cout << a[i] << 't'; cin >> a[i]; } return 0; } cout << "nthe current array "; for (int i=0; i<=4; i++) cout << a[i] << 't'; 16 http://www.cosc.canterbury.ac.nz/people/mukundan/dsal/appldsal.html TCP1231 Computer Programming I
  • 17. Sequential Search Algorithm • Sequential search is to determine the index i position of an object ‘X’ in an array A int search (const int a[], int target 8 number_used, int target) { [0] [1] [2] [3] [4] [5] [6] [7] int index = 0; bool found = false; a 2 7 3 8 4 12 9 5 while ((!found) && (index < number_used)) if (target == a[index]) Found “8” in position 4 found = true; else index++; if (found) return index; else return -1; } 17 http://www.cosc.canterbury.ac.nz/people/mukundan/dsal/appldsal.html TCP1231 Computer Programming I
  • 18. THE END TCP1231 Computer Programming I 18