SlideShare uma empresa Scribd logo
1 de 24
ARRAYS
  in
 JAVA
TOPICS TO COVER:--
  Array declaration and use.

  One-Dimensional Arrays.
  Passing arrays and array elements as parameters
  Arrays of objects
  Searching an array
  Sorting elements in an array
ARRAYS
 An array is group of like-typed variables that are referred to
  by a common name.

The entire array                 Each value has a numeric index
has a single name
               0       1     2        3      4      5       6

    scores   50.5 12.8 4.05 78 66 100 125
              50 12 45       7.8 0.66 1.00 12.5
                An array of size N is indexed from zero to N-1
                                                         INTEGER
                                                          FLOAT
 An array can be of any type.
 Specific element in an array is accessed by its index.
 Can have more than one dimension
2D Array Elements
                          Row
 Requires two indices
 Which cell is
          CHART [3][2]?
                                   Column

                    [0]    [1]    [2]    [3]    [4]   [5]
              [0]    0     97     90     268    262   130
              [1]   97     0      74     337    144   128
              [2]   90     74     0      354    174   201
              [3]   268   337    354        0   475   269
              [4]   262   144     174    475     0    238
              [5]   130   128     201    269    238    0
                                 CHART
Arrays
 A particular value in an array is referenced using the array
  name followed by the index in brackets

 For example, the expression

                             scores[2]

  refers to the value 45 (the 3rd value in the array)



           0      1      2      3      4      5     6

          50     12     45      78    66    100 125
  5
DECLARAING ARRAYS
 The general form of 1-d array declaration is:-
          type var_name[ ];      1. Even though an array variable
                                    “scores” is declared, but there
   int, float, char array name      is no array actually existing.
                                 2. “score” is set to NULL, i.e.
 E.g.:--- int scores [ ];           an array with NO VALUE.

scores
               int[] scores = new int[10];
             NULL



     To link with actual, physical array of integers….
Declaring Arrays
 Some examples of array declarations:

     double[] prices = new double[500];

     boolean[] flags;

     flags = new boolean[20];

     char[] codes = new char[1750];




                                          8
ARRAY INITIALIZATION
 Giving values into the array created is known as
  INITIALIZATION.
 The values are delimited by braces and separated by commas
 Examples:
  int[ ] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476};
  char[ ] letterGrades = {'A', 'B', 'C', 'D', ’F'};
 Note that when an initializer list is used:

    the new operator is not used

    no size value is specified

 The size of the array is determined by the number of items in the
  initializer list. An initializer list can only be used only in the array
  declaration
ACCESSING ARRAY
   A specific element in an array can be accessed by
    specifying its index within square brackets.
   All array indexes start at ZERO.


  Example:- System.out.println(units[4]);

         mean = (units[0] + units[1])/2;



                0     1   2   3    4     5   6     7    8   9
int[ ] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476};
PROCESSING ARRAY ELEMENTS
 Often a for( ) loop is used to process each of the elements
  of the array in turn.

 The loop control variable, i, is used as the index to access array
  components
  EXAMPLE:- int i;
                                         score [0]
                for(i=0;i<=2;i++)
                 {
                  System.out.println(+score[i]);
                  } 0        1     2     3       4        5     6
              score
                          50   12   45     78        66   100   125
int i;                   score [1]
         for(i=1;i<=2;i++)
        {
           System.out.println(+score[i]);
        }



        0      1    2      3      4      5    6
score
        50    12     45    78     66    100   125
Bounds Checking
 Once an array is created, it has a fixed size

 An index used in an array reference must specify a valid
  element

 That is, the index value must be in bounds (0 to N-1)

 The Java interpreter throws an
  ArrayIndexOutOfBoundsException if an array index
  is out of bounds

 This is called automatic bounds checking



 14
Bounds Checking
 For example, if the array score can hold 100 values, it
     can be indexed using only the numbers 0 to 99

 If i has the value 100, then the following reference will
     cause an exception to be thrown:

              System.out.println (score[i]);

 It’s common to introduce off-by-one errors when using
     arrays                      problem


 for (int i=0; i <= 100;                             i++)
 score[i] = i*50;
15
ARRAY OF OBJECTS
   Create a class student containing data members Name,
    Roll_no, and Marks.WAP in JAVA to accept details of 5
    students. Print names of all those students who scored
    greater than 85 marks

       student

                                       Chris,101,85
                  student[0]
                  student[1]           Brad, 102,75.8
                  student[2]
                  student[3]           Andrew, 103,75.9
Recursion
• Recursion is the process of defining something
  in terms of itself.
• It allows a method to call itself.

                      compute()

In general, to solve a problem using recursion, you
break it into sub problems.
          AREAS WHERE RECURSION CAN BE USED…………….
              FACTORIAL OF A NUMBER.
             FIBONACCI SERIES.
             GCD OF TWO NUMBERS.
             TOWER OF HANOI.
             QUICK SORT.
             MERGE SORT.
Recursion Example
                 cal (5)


               return 5 +cal (4)


               return 4 +cal (3)
                         6
               return 3 +cal (2)
                            3
               return 2 +cal (1)
                           TO WHOM??????
                 return 1       1
  5   cal(5)            CALLING FUNCTION
Iteration vs. Recursion
        ITERATION                     RECURSION

• Certain set of instructions • Certain set of
  are repeated without          instructions are repeated
  calling function.             calling function.

• Uses for, while, do-while   • Uses if, if-else or switch.
  loops.

• More efficient because of   • Less efficient.
  better execution speed.
COMPARSION contd….
• Memory utilization is   • Memory utilization is
  less.                     more.

                          • Complex to implement.
• Simple to implement.

• More lines of code.     • Brings compactness in
                            the program.

• Terminates when loop
                       • Terminates when base
  condition fails.
                            case is satisfied.
GCD USING RECURSION
ALGORITHM:-
int GCD(int a, int b)
  {
    if(b>a)
      return (GCD(b, a));
    if(b==0)
      return (a);
    else
          return (GCD(b,(a%b));
  }
FIBONACCI SERIES USING RECURSION
   int fibo(int f1,int f2,int count)
        {
             if(count==0) then
               return 0;
             else
                f3=f1+f2;
                 f1=f2;
                 f2=f3;
                 System.out.print(" "+f3);
                 count--;
                 return fibo(f1,f2,count);

         }
TWO- DIMENSIONAL ARRAY
  DECLARATION:-
       Follow the same steps as that of simple arrays.
  Example:-
     int [ ][ ];             int chart[ ][ ] = new int [3][2];
     chart = new int [3][2];

    INITIALIZATION:-
                                                15     16
     int chart[3][2] = { 15,16,17,18,19,20};    17     18
                                                19     20
int chart[ ][ ] = { {15,16,17},{18,19,20} };
                  15            16             17
                  18            19             20
PROGRAM FOR PRACTISE
   The daily maximum temperature is recorded in 5 cities during 3
    days. Write a program to read the table elements into 2-d array
    “temperature” and find the city and day corresponding to “ Highest
    Temperature” and “Lowest Temperature” .

   Write a program to create an array of objects of a class student. The
    class should have field members id, total marks and marks in 3
    subjects viz. Physics, Chemistry & Maths. Accept information of 3
    students and display them in tabular form in descending order of the
    total marks obtained by the student.
Arrays in Java

Mais conteúdo relacionado

Mais procurados

Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAsivasundari6
 
Java Presentation
Java PresentationJava Presentation
Java Presentationpm2214
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statementsKuppusamy P
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 

Mais procurados (20)

Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Array in c++
Array in c++Array in c++
Array in c++
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 

Semelhante a Arrays in Java

Semelhante a Arrays in Java (20)

Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
 
Array
ArrayArray
Array
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.ppt
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
 
CSEG1001Unit 3 Arrays and Strings
CSEG1001Unit 3 Arrays and StringsCSEG1001Unit 3 Arrays and Strings
CSEG1001Unit 3 Arrays and Strings
 
L10 array
L10 arrayL10 array
L10 array
 
Chapter 13.pptx
Chapter 13.pptxChapter 13.pptx
Chapter 13.pptx
 
Building Java Programas
Building Java ProgramasBuilding Java Programas
Building Java Programas
 
Array-part1
Array-part1Array-part1
Array-part1
 
lecture7.ppt
lecture7.pptlecture7.ppt
lecture7.ppt
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
DSA 103 Object Oriented Programming :: Week 5
DSA 103 Object Oriented Programming :: Week 5DSA 103 Object Oriented Programming :: Week 5
DSA 103 Object Oriented Programming :: Week 5
 

Mais de Abhilash Nair

Sequential Circuits - Flip Flops
Sequential Circuits - Flip FlopsSequential Circuits - Flip Flops
Sequential Circuits - Flip FlopsAbhilash Nair
 
Designing Clocked Synchronous State Machine
Designing Clocked Synchronous State MachineDesigning Clocked Synchronous State Machine
Designing Clocked Synchronous State MachineAbhilash Nair
 
VHDL - Enumerated Types (Part 3)
VHDL - Enumerated Types (Part 3)VHDL - Enumerated Types (Part 3)
VHDL - Enumerated Types (Part 3)Abhilash Nair
 
Introduction to VHDL - Part 1
Introduction to VHDL - Part 1Introduction to VHDL - Part 1
Introduction to VHDL - Part 1Abhilash Nair
 
Feedback Sequential Circuits
Feedback Sequential CircuitsFeedback Sequential Circuits
Feedback Sequential CircuitsAbhilash Nair
 
Designing State Machine
Designing State MachineDesigning State Machine
Designing State MachineAbhilash Nair
 
State Machine Design and Synthesis
State Machine Design and SynthesisState Machine Design and Synthesis
State Machine Design and SynthesisAbhilash Nair
 
Synchronous design process
Synchronous design processSynchronous design process
Synchronous design processAbhilash Nair
 
Analysis of state machines & Conversion of models
Analysis of state machines & Conversion of modelsAnalysis of state machines & Conversion of models
Analysis of state machines & Conversion of modelsAbhilash Nair
 
Analysis of state machines
Analysis of state machinesAnalysis of state machines
Analysis of state machinesAbhilash Nair
 
Sequential Circuits - Flip Flops (Part 2)
Sequential Circuits - Flip Flops (Part 2)Sequential Circuits - Flip Flops (Part 2)
Sequential Circuits - Flip Flops (Part 2)Abhilash Nair
 
Sequential Circuits - Flip Flops (Part 1)
Sequential Circuits - Flip Flops (Part 1)Sequential Circuits - Flip Flops (Part 1)
Sequential Circuits - Flip Flops (Part 1)Abhilash Nair
 

Mais de Abhilash Nair (20)

Sequential Circuits - Flip Flops
Sequential Circuits - Flip FlopsSequential Circuits - Flip Flops
Sequential Circuits - Flip Flops
 
VHDL Part 4
VHDL Part 4VHDL Part 4
VHDL Part 4
 
Designing Clocked Synchronous State Machine
Designing Clocked Synchronous State MachineDesigning Clocked Synchronous State Machine
Designing Clocked Synchronous State Machine
 
MSI Shift Registers
MSI Shift RegistersMSI Shift Registers
MSI Shift Registers
 
VHDL - Enumerated Types (Part 3)
VHDL - Enumerated Types (Part 3)VHDL - Enumerated Types (Part 3)
VHDL - Enumerated Types (Part 3)
 
VHDL - Part 2
VHDL - Part 2VHDL - Part 2
VHDL - Part 2
 
Introduction to VHDL - Part 1
Introduction to VHDL - Part 1Introduction to VHDL - Part 1
Introduction to VHDL - Part 1
 
Feedback Sequential Circuits
Feedback Sequential CircuitsFeedback Sequential Circuits
Feedback Sequential Circuits
 
Designing State Machine
Designing State MachineDesigning State Machine
Designing State Machine
 
State Machine Design and Synthesis
State Machine Design and SynthesisState Machine Design and Synthesis
State Machine Design and Synthesis
 
Synchronous design process
Synchronous design processSynchronous design process
Synchronous design process
 
Analysis of state machines & Conversion of models
Analysis of state machines & Conversion of modelsAnalysis of state machines & Conversion of models
Analysis of state machines & Conversion of models
 
Analysis of state machines
Analysis of state machinesAnalysis of state machines
Analysis of state machines
 
Sequential Circuits - Flip Flops (Part 2)
Sequential Circuits - Flip Flops (Part 2)Sequential Circuits - Flip Flops (Part 2)
Sequential Circuits - Flip Flops (Part 2)
 
Sequential Circuits - Flip Flops (Part 1)
Sequential Circuits - Flip Flops (Part 1)Sequential Circuits - Flip Flops (Part 1)
Sequential Circuits - Flip Flops (Part 1)
 
FPGA
FPGAFPGA
FPGA
 
FPLDs
FPLDsFPLDs
FPLDs
 
CPLDs
CPLDsCPLDs
CPLDs
 
CPLD & FPLD
CPLD & FPLDCPLD & FPLD
CPLD & FPLD
 
CPLDs
CPLDsCPLDs
CPLDs
 

Último

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 

Último (20)

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 

Arrays in Java

  • 1. ARRAYS in JAVA
  • 2. TOPICS TO COVER:--  Array declaration and use.  One-Dimensional Arrays.  Passing arrays and array elements as parameters  Arrays of objects  Searching an array  Sorting elements in an array
  • 3. ARRAYS  An array is group of like-typed variables that are referred to by a common name. The entire array Each value has a numeric index has a single name 0 1 2 3 4 5 6 scores 50.5 12.8 4.05 78 66 100 125 50 12 45 7.8 0.66 1.00 12.5 An array of size N is indexed from zero to N-1 INTEGER FLOAT  An array can be of any type.  Specific element in an array is accessed by its index.  Can have more than one dimension
  • 4. 2D Array Elements Row  Requires two indices  Which cell is CHART [3][2]? Column [0] [1] [2] [3] [4] [5] [0] 0 97 90 268 262 130 [1] 97 0 74 337 144 128 [2] 90 74 0 354 174 201 [3] 268 337 354 0 475 269 [4] 262 144 174 475 0 238 [5] 130 128 201 269 238 0 CHART
  • 5. Arrays  A particular value in an array is referenced using the array name followed by the index in brackets  For example, the expression scores[2] refers to the value 45 (the 3rd value in the array) 0 1 2 3 4 5 6 50 12 45 78 66 100 125 5
  • 6. DECLARAING ARRAYS  The general form of 1-d array declaration is:- type var_name[ ]; 1. Even though an array variable “scores” is declared, but there int, float, char array name is no array actually existing. 2. “score” is set to NULL, i.e. E.g.:--- int scores [ ]; an array with NO VALUE. scores int[] scores = new int[10]; NULL To link with actual, physical array of integers….
  • 7. Declaring Arrays  Some examples of array declarations: double[] prices = new double[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; 8
  • 8. ARRAY INITIALIZATION  Giving values into the array created is known as INITIALIZATION.  The values are delimited by braces and separated by commas  Examples: int[ ] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[ ] letterGrades = {'A', 'B', 'C', 'D', ’F'};  Note that when an initializer list is used:  the new operator is not used  no size value is specified  The size of the array is determined by the number of items in the initializer list. An initializer list can only be used only in the array declaration
  • 9. ACCESSING ARRAY  A specific element in an array can be accessed by specifying its index within square brackets.  All array indexes start at ZERO. Example:- System.out.println(units[4]); mean = (units[0] + units[1])/2; 0 1 2 3 4 5 6 7 8 9 int[ ] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476};
  • 10. PROCESSING ARRAY ELEMENTS  Often a for( ) loop is used to process each of the elements of the array in turn.  The loop control variable, i, is used as the index to access array components EXAMPLE:- int i; score [0] for(i=0;i<=2;i++) { System.out.println(+score[i]); } 0 1 2 3 4 5 6 score 50 12 45 78 66 100 125
  • 11. int i; score [1] for(i=1;i<=2;i++) { System.out.println(+score[i]); } 0 1 2 3 4 5 6 score 50 12 45 78 66 100 125
  • 12.
  • 13. Bounds Checking  Once an array is created, it has a fixed size  An index used in an array reference must specify a valid element  That is, the index value must be in bounds (0 to N-1)  The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds  This is called automatic bounds checking 14
  • 14. Bounds Checking  For example, if the array score can hold 100 values, it can be indexed using only the numbers 0 to 99  If i has the value 100, then the following reference will cause an exception to be thrown: System.out.println (score[i]);  It’s common to introduce off-by-one errors when using arrays problem for (int i=0; i <= 100; i++) score[i] = i*50; 15
  • 15. ARRAY OF OBJECTS  Create a class student containing data members Name, Roll_no, and Marks.WAP in JAVA to accept details of 5 students. Print names of all those students who scored greater than 85 marks student Chris,101,85 student[0] student[1] Brad, 102,75.8 student[2] student[3] Andrew, 103,75.9
  • 16. Recursion • Recursion is the process of defining something in terms of itself. • It allows a method to call itself. compute() In general, to solve a problem using recursion, you break it into sub problems. AREAS WHERE RECURSION CAN BE USED…………….  FACTORIAL OF A NUMBER. FIBONACCI SERIES. GCD OF TWO NUMBERS. TOWER OF HANOI. QUICK SORT. MERGE SORT.
  • 17. Recursion Example cal (5) return 5 +cal (4) return 4 +cal (3) 6 return 3 +cal (2) 3 return 2 +cal (1) TO WHOM?????? return 1 1 5 cal(5) CALLING FUNCTION
  • 18. Iteration vs. Recursion ITERATION RECURSION • Certain set of instructions • Certain set of are repeated without instructions are repeated calling function. calling function. • Uses for, while, do-while • Uses if, if-else or switch. loops. • More efficient because of • Less efficient. better execution speed.
  • 19. COMPARSION contd…. • Memory utilization is • Memory utilization is less. more. • Complex to implement. • Simple to implement. • More lines of code. • Brings compactness in the program. • Terminates when loop • Terminates when base condition fails. case is satisfied.
  • 20. GCD USING RECURSION ALGORITHM:- int GCD(int a, int b) { if(b>a) return (GCD(b, a)); if(b==0) return (a); else return (GCD(b,(a%b)); }
  • 21. FIBONACCI SERIES USING RECURSION int fibo(int f1,int f2,int count) { if(count==0) then return 0; else f3=f1+f2; f1=f2; f2=f3; System.out.print(" "+f3); count--; return fibo(f1,f2,count); }
  • 22. TWO- DIMENSIONAL ARRAY  DECLARATION:- Follow the same steps as that of simple arrays. Example:- int [ ][ ]; int chart[ ][ ] = new int [3][2]; chart = new int [3][2];  INITIALIZATION:- 15 16 int chart[3][2] = { 15,16,17,18,19,20}; 17 18 19 20 int chart[ ][ ] = { {15,16,17},{18,19,20} }; 15 16 17 18 19 20
  • 23. PROGRAM FOR PRACTISE  The daily maximum temperature is recorded in 5 cities during 3 days. Write a program to read the table elements into 2-d array “temperature” and find the city and day corresponding to “ Highest Temperature” and “Lowest Temperature” .  Write a program to create an array of objects of a class student. The class should have field members id, total marks and marks in 3 subjects viz. Physics, Chemistry & Maths. Accept information of 3 students and display them in tabular form in descending order of the total marks obtained by the student.