programming 1 - yola 9-array.pdf · 2019. 11. 2. · • the second concept of array: we can fill...

61
Programming 1 Arrays

Upload: others

Post on 02-Feb-2021

4 views

Category:

Documents


0 download

TRANSCRIPT

  • Programming 1

    Arrays

  • Objective

    • The importance of arrays.

    • Definition of a one-dimensional array.

    • Access array elements.

    • Operations on the one-dimensional arrays.

    • Pass an array through Methods.

    • Use for-each loop.

    • Definition of a two-dimensional array.

    • Operations on the two-dimensional arrays.

  • The concept of arrays

    • You know what a train is, right? And you also know how the train moves?

    • One locomotive move all those trailers to reach a particular goal and is the only one in the train, which has an engine and require fuel exchange.

  • The concept of arrays

    • What will happen if all the trailers are separate and each one moves in their own way and requires fuel discharge, presence of the leader and so on.

    • This is exactly the concept of arrays. Arrays are created to help you treat objects as groups rather than dealing with each object alone because it requires a special effort and time for each object.

  • The concept of arrays

    • The arrays as mentioned before provide us with a mechanic - a way - to deal with objects as a single group, just like the example of a train.

    One object in each box

    Start with 0

  • The concept of arrays

    • The first concept of array: The array is a train, each trailer in this train contains an object, and this object can be a letter or a number or a word or a human… etc.

    • The second concept of array: we can fill the train (array) with different objects in the first vehicle Reem and the second Abeer and the third Norah, and so on, but all objects must be of the same type.

    • The third array concept: In each box (trailer or locomotive) by train (array) only one object can be placed.

    • Fourth Arrays Concept: You will not be able to reach your girlfriend in any trailer unless you know the number of the trailer, she is sitting in. The numbering starts at zero (the locomotive where the driver is), then 1, 2, 3, etc.

  • An example of the importance of arrays

    • Write a program that reads five numbers, then find the sum of them and print them in reverse order.

  • The importance of arrays

    import java.util.*;

    public classRevOrder{

    public static void main(String[]args){

    Scanner console = new Scanner(System.in); int item0, item1, item2, item3, item4;int sum;System.out.println("Enter 5 numbers: "); item0=console.nextInt(); item1=console.nextInt(); item2=console.nextInt(); item3=console.nextInt(); item4=console.nextInt();sum = item0+item1+item2+item3+item4;System.out.println("Sum = " + sum); System.out.print("Numbers is reverse = ");System.out.println(item4+" "+item3+" "+item2+" "+item1+""+item0);}

    }

    Enter 5 numbers:

    3 6 8 9 0

    Sum = 26

    Numbers is reverse = 0 9 8 6 3

  • The importance of arrays

    • Creating many variables consumes time and boring the programmer, so one of the benefits of arrays is to reduce the number of similar variables, for example, if we want to define 10 variables of their type int, we define a single array of 10 elements of type int.

    • An array is a data type that consists of a continuous, indexed set of memory locations that have one type and one name.

    • The size of the array is fixed and does not allow to change its size during execution time known as Static data structure

  • Array

    • The continuation of array cells allows searches and ranking of data within the array.

    • They are used in all applications where we need to search, sort, or systematically store (storage by a certain condition).

    • Each item is of the same type.

    • They are accessed by using the locations of the elements in the array (index ).

  • Array types

    • Arrays have two types:

    • One-dimensional: Only data is stored in a single row.

    • Multidimensional: Data is stored in rows and columns.

  • One-dimensional arrays

    • One Dimensional Arrays

    • An array that has only one dimension - a single line of numbers ranging

    from zero to the top-level element number specified for the array

  • Create Array

    • Arrays are created by specifying the type of variable to organize within the array and the name of the array.

    • In order to differentiate, you must add brackets [] and arrays are created to contain any type of information that can be stored in a variable, in the following formulas:

    ▪ dataType[ ] arrayName;

    ▪ arrayName = new dataType[size]

    ▪ dataType[ ] arrayName = new dataType[size]

    ▪ dataType[ ] arrayName1,arrayName2;

  • Methods for defining a one-dimensional array

    type[] array_name = new type[ x ];

    The type of items that

    will be reserved in memory-

    int double char String

    The number of

    items we want to

    reserve in memory

    type array_name[] = new type[ x ];

    type array_name[] = { v1,v2,v3,v4};

    The number of values is 4 so an array of 4 will

    be reserved

  • Methods for defining a one-dimensional array

    type [] array1,array2,array3;

    array1 = new type[ x ];

    array2 = new type[ y ];

    array3 = new type[ z ];

    3 variables are

    defined as an array

  • One-dimensional arrays

    • Examples of defining one-dimensional arrays:

    int[] samy = { 90,85,85,75,70,95};

    String[] netWeight;

    String netWeight[];

    boolean[] GradeStudents;

    int[] primes = newint[300];

    String [] colors ={“Blue",“Green",“Red"};

  • Define a one-dimensional array

    int c[] = new int[ 12 ];

    The first index number is

    zero

  • One-dimensional arrays

    ▪ int[] num=newint[5];

    When you create an

    array, it is formatted

    with the default value

    for the data type

    int → 0

    double → 0.0

    String → null

    char → space

    boolean → false

  • One-dimensional arrays

    • Assigning values to elements of a one-dimensional array

    int[] list = newint[10];

    list[3]=10;

    list[6]=35;

    list[5]=list[3]+list[6];

  • Methods of definition of one-dimensional array

    This sentence defines

    an array of integers c

    and two variables for

    aa and bb

    This sentence defines

    3 arrays for integers

    int c[],aa,bb;

    int[] c,aa,bb;

  • An example of a one-dimensional array definition

    When adding [] to the name of a

    variable, it means that it is an array and

    the rest of the variables on the same line

    are not arrays, so a red line appeared

    about trying to create the array for b

    being a variable and not an array.

    When you add [] immediately

    after the data type, it declares

    any variable name on the same

    line as an array

    int[] a,b;

    a=new int[5];

    b=new int[7];

    int a[],b;

    a=new int[5];

    b=new int[7];

  • Define types of arrays

    int[] grades = new int[ 3 ];

    String[] employees = new String[ 5 ];

    float[] salary = new float[ 30 ];

  • Set the size of the array during program execution

    • So we ask the user to enter the size of the array in a variable type int and then create the array after the following example: -

    int arraySize;

    System.out.print("Enter the size of the array:");

    arraySize=console.nextInt();

    int[] list = newint[arraySize];Here the array was created

    based on the entered number

  • Handling array elements

    • Elements Here is the number of items that can be stored in the array. Each item in the array is called an element.

    • Any element of an array can be dealt with by the following code expression, which includes the name of the array as well as the number of the cell to interact with surrounded by square brackets [].

    Array

    nameThe cell number to

    interact with is

    specified from zero

    to cell length - 1

    The value to be

    placed in the cell

    Array [ i ] = k;

  • What does the following code do?

    • Determine the type of array - and the number of elements - with an outline of the array.

    Variable name Index Value

  • The length of the array• We mean the number of items that are reserved for the array, according to

    the following examples:

    i n t [ ] a , c , d ;

    i n t b [ ]= {5 ,10,15} ;

    i n t z ;

    a=new i n t [ 5 ] ;

    c=new i n t [ 9 ] ;

    z=b. l engt h / / z= 3

    z=c. length; / /z=9

    z=a.length / /z=5

    z=d.length / / e r ro r

  • Some operations on arrays

    • Initialize by assigning certain values

    • Input data for array elements

    • Output stored data Print the values of the array elements

    • Find largest/smallest/sum/average of elements

  • Initialize array elements with values

    int[] c = new int[ 12 ];

    c[0]= -45;

    c[1]= 6;

    c[2]= 0;

    c[3]= 72;

    …..

    c[11]= 78;

    What if the

    array of 100

    elements!

    How many

    lines are

    needed to

    enter the

    values of the

    array

    elements

  • Initialize the array with values during creation

    double[] sales = {12.25, 32.50, 16.90, 23,45.68};

    Values, called initial values, are enclosed in brackets and separated by commas, in this way we do not need to use the word new.

    The size of the sales array is the number of elements in brackets (5), and this method is similar to the following method

    double[] sales=new double[5];

    sales[0]= 12.25;

    sales[1]= 32.50;

    sales[2]= 16.90;

    sales[3]= 23.00;

    sales[4]= 45.68.

  • Initialize array elements with values

    • It is good to use loop statements to initialize the array values to save time and effort and shorten the lines of the program.

    int[] c = new int[ 100 ];

    c[0]= -45;

    c[1]= 6;

    c[2]= 0;

    c[3]= 72;

    …..

    c[99]= 252;

    for(int i=0;i

  • Example: Initialize array elements

    • Write a program that creates an array containing 5 integer numbers giving a primitive value of each element of the matrix number 2.

    • Solution

    i n t [ ] a=new i n t [ 5 ] ;

    f o r ( i n t i =0; i< a. l e ngth; i ++)

    a [ i ] = 2 ;

  • Example: Initialize and print array elements

    • Write a program that creates an array containing 5 integer numbers giving a primitive value of each element of the matrix number 2. Then print the contents of the array.

    • Solution

    i n t [ ] a=new i n t [ 5 ] ;

    f o r ( i n t i =0; i< a. l e ngth; i ++)

    a [ i ] = 2 ;

    f o r ( i n t i=0 ; i

  • Example: Initialize array elements with input data

    • Write a program that creates an array of 4 texts, giving each element a text value entered by the user.

    • Solution

    Str ing name[]=new S t r i n g [ 4 ] ;

    Scanner s=new Scanner( System.i n ) ;

    f o r ( i n t i=0; i

  • Notes

    • All applications where we need to access all of the array cells or a certain number of them depending on a condition, we need to use a one loop type.

    • The [] can be used throughout the array definition before or after the name, and both are true.

    • Common error: Not specifying the number of array elements when defined gives a code error unless defined in the following way:

    int x[];

    //And can then be given during the program number in the following format

    x = new int[5];

  • Example: Print array elements

    • Write a program by which to create an array to store pre-defined integers without giving the value to each cell separately, as shown in the figure in front of you, then print the elements of the array

    [0] 32

    [1] 27

    [2] 64

    [3] 18

    [4] 95

    [5] 14

    [6] 90

    [7] 70

    [8] 60

    [9] 37

  • Example: Print array elements

  • Example: Initialize and print array elements

    • Write a program that creates an array to store integer numbers, where multiples of 2 from 0 to 20 are stored and then printed.

    • Solution

  • Example: Arrays and their operations

    • Write a program that creates an array to store ten integer numbers that are received from the user, and then sum even numbers from them and print the result.

    • Solution Scanner sc=new Scanner(System.in);

    System.out.println(“Enter the number”);

    num[i]=sc.nextInt();

    System.out.println(“ Total even numbers=” +sum);

  • Example: Search arrays

    • Write a program that allows the user to search for one of the values entered and print the result (found in cell number ...) or (I do not find).

    • Solution System.out.println(“Enter the number to search for”);

    int wanted=sc.nextInt();

    boolean flag; int j;

    for (j=0 ; j

  • Example: Combine All

    Let's take an example where you want to….

    • Enter the grades of 10 students using the Scanner object.

    • View the grades you entered.

    • Calculate the average grade you entered.

  • Example: Combine All

    Enter the

    array values

    Print matrix

    elements

    Calculate

    the average

    values of

    array

    elements

  • Using the loop for each

    • All the previous examples have used loop statements to perform an operation on the array.

    • There is a loop statement for arrays called for each.

    • The following example illustrates the formulation for each:

    int x[] ={24,52,76};

    for(int val : x)

    System.out.println(val);

    Array type

    It must match

    the type of

    array

    Val The value of an element in the X array

    represents the name of the array the element and

    the array are separated by two colon

  • Using the loop for each

    for (dataType identifier :arrayName)

    • This method can be used to manipulate elements within the

    array and is called enhanced for without having to define a

    counter and determine where it starts and ends.

    • datatype Is the type of array.

    • Identifier A variable with the same type of elements as an array.

    • arrayName

  • The difference between for each and for statement

    String names[]={“Rana”,”Maha”,”Asma”,”Sarah”,”Dana”}

    The outputs of both loop are similar

  • Example: for each

    Write a program for the summation of elements of the array

    used for each

    double a[]={4.5,8.5,16.0,32.0,64.25};

    double sum =0;

    for (double number :a)

    sum = sum + number;

  • Example: for each

    Write a program to print array elements used for each

    String color[]={"red","blue","green","black","white“};

    for (String c :color)

    System.out.println( c );

  • Two- dimensional array (2D Arrays)

    • The data is sometimes in the form of a table (difficult to represent

    using a 1D array).

    • To defines a 2D matrix

    dataType[ ][ ] arrayName= new dataType[row][col];

    int [][]c=new int[4][3];

    / / or int c [][] =new int[4][3];

    c[0][2]=3;

    c[1][2]=9;

    .....

    2 3 9

    3 4 16

    4 5 25

    0 12

    240

    1

    2

    3

  • Methods for the definition of 2D array

    The type of items that

    will be reserved in memory

    int double char String

    R means the number of

    rows and c the number

    of columns

    type[][] array_name = new type[R][C];

    type array_name[][] = new type[R][C];

    type array_name[][]= {{ v1,v2},{v3,v4},{v5,v6}};

    The number of pairs of brackets represents the number of rows 3

    within each pair of brackets two values, the number of columns 2

    Repeating them

    twice means

    two-dimensional

  • 2D Arrays

    • The array can be defined and initialized values

    during the definition.

    int[][] board= { {2,3,1} , {15,25,13} , {20,4, 7} };

    [0] [1] [2]

    [0] 2 3 1

    [1] 15 25 13

    [2] 20 4 7

    board

  • 2D Arrays

    • To access array elements:

    arrayName[row][col];

    Positive numbers row, col >= 0

    row = row position

    col = columnposition

  • 2D Arrays

    int c[][]= new int[ 3][ 4 ];

  • Create 2D array

    double sales[][] = new double[10][5];

  • Access 2D array elements

  • The length of the 2D array

    int [][] matrix = newint[20][15];20rows

    15 columns

    matrix.length = 20 //rows number

    • Each row is a one-dimensional array

    matrix[0].length =15 / /The number of columns in the first row

    matrix[1].length = 15 / /The number of columns in the second row

  • Some operations on 2D array

    • Initialize by assigning certain values

    • Input data for array elements

    • Output stored data Print the values of the array elements

    • Find largest/smallest/sum/average of elements

    For any operation it is necessary to use the nested loop

  • Operations on 2D arrays

    • Example Initialization of all array elements with a value of

    1

    for (introw = 0; row < matrix.length; row++)

    for (int col = 0; col < matrix[row].length;col++)

    matrix[row][col] =10;

  • Operations on 2D arrays

    • Example Print for array elements

    for (int row = 0; row< matrix.length; row++)

    {

    for (int col = 0; col < matrix[row].length;col++)

    System.out.print (matrix[row][col]+”\t”);

    System.out.println();

    }

  • Operations on 2D arrays

    • Input User-entered data for two-dimensional array elements

    for (int row = 0; row < matrix.length; row++){

    for (int col = 0; col < matrix[row].length; col++){

    System.out.println("enter the elements for the Matrix [row]=“+row+”[col]=”+col);

    matrix[row][col] = console.nextInt(); }

    System.out.println();

    }

  • Operations on 2D arrays

    for(int row = 0; row < matrix.length;row++)

    {

    sum = 0;

    for (col = 0; col < matrix[row].length; col++)

    sum = sum + matrix[row][col];

    System.out.println("Total row number" + (row + 1) + " = "+ sum);

    }

    • Sum by Row Example of adding rows to a two-dimensional array

  • Operations on 2D arrays

    • Sum by Column Example of adding columns to a two-dimensional

    array

    for (int col = 0; col

  • Summary

    • The importance of arrays.

    • Definition of a one-dimensional array.

    • Access array elements.

    • Operations on the one-dimensional arrays.

    • Pass an array through Methods.

    • Use for-each loop.

    • Definition of a two-dimensional array.

    • Operations on the two-dimensional arrays.