Problems with simple variables

Size: px
Start display at page:

Download "Problems with simple variables"

Transcription

1 Arrays Java programming language provides a data structure called the array ( מערך ), which can store a fixed-size sequential collection of elements of the same type. Arrays are widely used within Java programming for different purposes such as sorting, searching and etc. 1

2 Problems with simple variables Hard to give up values high number of variables. Complex to sort a high number of variables by value. Impossible to use loops. Example problem: Read one hundred numbers, compute their average, and find out how many numbers are above the average. We can use an array instead of a variables. 2

3 Array definition An array ) מערך ( is a collection of variables of the same data type, and the collection is assigned a name. Array can be declared for any type. (. עצם ) object In Java an array is an Each variable within the collection is called an array element. An array element is identified by combining the array name and a unique index ) אינדקס (. An index is an integer from zero to 1 minus the maximum number of elements in the array. An array of size N is indexed from 0 to N 1. Array examples: list of students marks series of numbers entered by user vectors matrices 3

4 Array indexing In Java,array indexes always begin at zero. The array mylist has 10 values, indexed from 0 to 9. The i-th element of array mylist is specified by mylist[i-1]. double[] mylist = new double[10]; mylist reference mylist[0] 5.6 mylist[1] 4.5 Array reference variable mylist[2] mylist[3] Array element at index 5 mylist[4] mylist[5] mylist[6] Element value mylist[7] mylist[8] mylist[9]

5 Declaring array variables In Java arrays are objects ( עצם ). To create an array, the reference declared. to the array must be (הפניה ( The array can be created using the new operator, which allocates memory space to store values. Examples: double [ ] mylist = new double [ 10 ]; The variable mylist is declared to be an array of 10 real numbers whose type is written as double[ ]. int [ ] studgrades = new int [ 85 ]; The variable studgrades is declared to be an array of 85 integer numbers whose type is written as int[ ]. Note: once an array is declared to be a certain size, the number of values it can hold cannot be changed. 5

6 Default values and initialization When an array is created, its elements are assigned the default value of : 0 for the numeric primitive data types '\u0000' for char data types False for boolean data types. Declaring, creating, initializing in one step: double [ ] mylist1 = 1.9, 2.9, 3.4, 3.5 }; Note: Don t use new operator if you plan to initialize the array. 6

7 Accessing array elements To access a value in an array, we use the name of array followed by the index in square brackets. int [ ] arr = 69,61,73,19,37 }; arr[ 2 ] = 95; // initial value was 73 Array indexes are integers and we can use integer expression to specify the index. int a = 7, b = 2,c = -3; arr[ a/b ] = 71; // initial value was 19 System.out.println( arr[a + c] ); // output value is 37 NOTE :when accessing array elements, be careful to ensure that the index stays within the array bounds. 7

8 The length of an array In order to get the number of elements in an array, you can use the length attribute of an array. The length attribute of an array returns the size of the array ( number of elements). It can be used by writing arrayname.length For example : int a = mylist.length; // a = 10 int b = studgrade.length; // b = 85 8

9 Array as Java object Java array is a container object that holds a fixed number of values of a single type. The array declaration allocates only enough space for a reference to an array but doesn't create the actual array object. For example: int[ ] num = new int[5]; reference 9

10 The Assignment Operators and Arrays int[ ] lista = 5, 10, 15, 20, 25, 30, 35 }; int[ ] listb = new int[7]; 10

11 The Assignment Operators and Arrays Arrays after assignment statement ListB = ListA; 11

12 Array example 1 The next program section reads N integers into an array and then reverses them and prints. N value reads during the program execution Before revers After revers 12

13 Example 1 - solution System.out.print( "Enter the number of array elements : ); int [ ] arr = new int [reader.nextint()]; for (int i = 0; i < arr.length; i++) System.out.print("Enter number "+ (i+1) + " integer : ); arr[i] = reader.nextint(); } // for for (int i = 0; i < arr.length/2; i++) int temp = arr[i]; arr[i] = arr[arr.length i - 1]; arr[arr.length-i-1] = temp; } // for System.out.println(" The numbers in revers order : "); for (int i = 0; i <arr.length; i++) System.out.println(arr[i]); number of array elements reads during the program running It is often convenient to use for loops when handling array, because the number of its elements is constant. 13

14 Array example 2 This program reads N integer number sequence and builds an array. The program builds an array from a sequence ( some numbers can appear twice or more in the sequence but appears only once in the array ). For example: N = 9 and input sequence is 9, 9, 5, 4, 4, 4, 1, 1, 7 arr Note: maximum array s elements is N, because each number can appears only once in the sequence. 14

15 Example 2 - solution static final int N = 9; public static void main (String[] args) int [ ] arr = new int[n]; int j = 1; // array index int num; // input variable arr[0] = reader.nextint(); for (int i = 0; i < N - 1; i++) num = reader.nextint(); if(num!= arr[j-1]) arr[j] = num; j++; } //if } // for for(int i = 0; i < j; i++) System.out.println(arr[i]); } // main final keyword when used with a variable makes it a constant. 15

16 Array example 3 This program section reads 10 integers into an array, finds the max and min values of array elements and prints them. static final int N=10; public static void main (String[] args) int [] arr = new int[n]; for (int i = 0; i < N; i++) arr[i] = reader.nextint(); int max = arr[0],min = arr[0]; for (int i = 1; i < N; i++) max = (arr[i]>max)? arr[i] : max; min = (arr[i]<min)? arr[i] : min; } //for System.out.println(" The max element is : "+max); System.out.println(" The min element is : "+min); } //void main If a variable is marked as final then the value of that variable cannot be changed i.e final keyword when used with a variable makes it a constant. if (arr[i]) > max max = arr[i]; else max = max; 16

17 Array example 4 This program calculates the number of different values in array of integers. public static void main (String[] args) int a[ ] = 5, 5, 2, 9, 3, 2, 5, 9, 3, 5 }; // array of integers int i, j; // loop counters int count = 1; // accumulator for(i =1; i < a.length; i++) for(j = 0; j < i; j++) if(a[j] == a[i]) break; if(j == i) count++; } // for System.out.println( The number of different values is : + count); } // main 17

18 Array example 4 Trace table ( i < 3 only ) count i i < 3 j j < i a[ j ] == a[ i ] 1 1 T 0 T T 2 T 0 T F 1 T F 2 F 2 public static void main (String[] args) int a[ ] = 5, 5, 2 }; // array of integers int i, j; // loop counters int count = 1; // accumulator for(i =1; i < a.length; i++) j == i for(j = 0; j < i; j++) if(a[j] == a[i]) break; if(j == i) count++; F } // for System.out.println(count); } // main T 18

19 Array example 5 static final int N = 26; public static void main (String[] args) int [] arr = new int[n]; int m = 0; // help variable for (int i = 0; i < N; i++) This program reads 100 letters and? arr[i] = 0; for (int i = 0; i < 100; i++) System.out.println(" Enter a letter: "); char ch = reader.next().charat(0); arr[ch a ] ++; } // for for (int i = 1; i < N; i++) if(arr[i] > arr[m]) m = i; char mch = (char)(m + a ); System.out.println(" mch : + mch); } // main 19

20 (מיון ( Sorting Sorting is the process of arranging a list of items in well defined order. Sorting values of array elements is one of the basic array manipulations. Many sorting algorithms have been developed over the years. In this course we examine two sorting algorithms: מיון ( sort and insertion (מיון בחירה) selection sort.(הכנסה 20

21 Selection sort algorithm The selection sort algorithm selects for each position in the list the value, that should go in this position, and puts it there Scan starting with is smallest. Exchange 6 and Scan starting with is smallest. Exchange 7 and Scan starting with is smallest. Exchange 15 and Scan starting with is smallest. Exchange 23 and

22 Selection sort implementation This program section uses a selection sort to arrange a list of integer ). סדר עלה ( order values into ascending int [ ] arr = 23,15,6,7,20 }; for(int i = 0; i < arr.length; i++) int min_pos = i; for(int j = i+1; j < arr.length; j++) if ( arr[j] < arr[min_pos] ) min_pos = j; int temp = arr[i]; // help variable arr[i] = arr[min_pos]; arr[min_pos] = temp; } // inner for } // outer for The outer loop controls the position where the next smallest value will be stored. The inner loop finds the smallest value in the rest of the list. When the smallest value is determined, it is exchanged with the value stored at the index. ) סדר יורד ( order The algorithm can easily be changed to put values in descending by finding the largest value each time. 22

23 Insertion sort algorithm The insertion sort algorithm works by inserting each value into a previously sorted subset of the list is sorted. Shift nothing. Insert and 9 are sorted. Shift 9 to the right. Insert ,6 and 9 are sorted. Shift 9,6 and 3 to the right. Insert ,3,6 and 9 are sorted. Shift 9,6 and 3 to the right. Insert All values are sorted 23

24 Insertion sort implementation int [ ] arr = 3,9,6,1,2 }; for (int i = 1; i < arr.length; i++) int j = i; int a = arr[i]; while ( j > 0 && arr[ j-1] > a) arr[ j ] = arr[ j-1]; j--; } // block while arr[ j ] = a; } // block for The outer loop controls the index in the array of the next value to be inserted. The inner loop compares the current insert values with values stored with lower indexes. If the current insert value is less then the value at j position, that value is shifted to the right. 24

25 )חיפוש ( searching Java Searching (חיפוש) is an operation which finds the location of a given element in an array. The search is said to be successful or unsuccessful depending on whether the element that is to be searched is found or not. Definition: A key is a value that you are looking for in an array. If found, the index of the first location of the key will be returned. If not found, a value of -1 will be returned. In this course we examine two searching algorithms: (חיפוש סדרתי) - linear search.(חיפוש בינארי) - binary search 25

26 Linear search The simplest type of search is the liner (sequential) search. In the liner search, each element of the array is compared to the key, in the order it appears in the array, until the desired element is found. System.out.println( enter search key ); int num = reader.nextint(); // input key value boolean flag = false; for( int i = 0; i < arr.length; i++) if (arr [i] == num) flag = true; break; } // if } // for if (flag ) System.out.println(num + " is at position + i); else System.out.println(num + " not found "); This searching type can be applied to a sorted or an unsorted list. Searching in case of unsorted list starts from the 0 th element and continues until the element is found or the end of list is reached. 26

27 Linear search in sorted array int i; // loop counter System.out.println( enter search key ); int num = reader.nextint(); // input key value for(i=0; i< arr.length && num > = arr[i]; i++) if (arr [i] == num) System.out.println(num + " is at position "+i); break; In case of sorted list we breaks the loop if the key value founded. } } //for if (i==0 i==arr.length num>arr[i] ) System.out.println(num + " not found "); 27

28 Binary search example Index Find 6 in -1, 5, 6, 18, 19, 25, 46, 78, 102, 114 }. low index = 0, high index = 9. Step 1 (middle element is 19 > 6): middle index = ( ) / 2 = 4 low index = 0, high index = 4-1=3 Step 2 (middle element is 5 < 6): middle index = (0 + 3 ) / 2 = 1 low index =0 +1, high index = 3 Step 3 (middle element is 6 == 6): middle index= (1 + 3 ) / 2 = 2 searched element is found! 28

29 Binary search example 2 index Find 103 in -1, 5, 6, 18, 19, 25, 46, 78, 102, 114}. low index = 0, high index = 9. Step 1 (middle element is 19 <103): middle index = ( ) / 2 = 4 low index =4+1, high index = 9 Step 2 (middle element is 78 < 103): middle index = (5 + 9 ) / 2 = 7 low index =7 +1, high index = 9 Step 3 (middle element is 102 <103): middle index= (8 + 9 ) / 2 = 8 low index =8 +1, high index = 9 Step 4 (middle element is 114 >103): middle index= (9 + 9 ) / 2 = 9 low index =9, high index = 9 1 = 8 low index > high index : searched value is absent! 29

30 Binary search algorithm 1. Get the middle element; 2. If the middle element equals to the searched value, the algorithm stops; 3. Otherwise, two cases are possible: searched value is less, than the middle element. In this case, go to the step 1 for the part of the array, before middle element. searched value is greater, than the middle element. In this case, go to the step 1 for the part of the array, after middle element. Now we should define, when iterations should stop. First case is when searched element is found. Second one is when sub-array has no elements. In this case, we can conclude, that searched value isn't present in the array. 30

31 Binary search implementation int [ ] arr = -1,5,6,18,19,25,46,78,102,114 }; int i = 0,h = arr.length; // low and high array indexes System.out.pirnt ("enter search key => "); int num = reader.nextint(); // input key value while (i < h) int mid = (i + h) / 2; // Compute mid point. if (num < arr[mid]) h = mid; else if (num > arr[mid]) i = mid+1; else System.out.println( "found in "+mid+" position ); break; } } //while if ( i >= h ) System.out.println(num + " not found ); 31

32 32

33 )מחרוזות ) Strings Java string is a sequence of characters. They are objects of type String. Once a String object is created it cannot be changed. Basic string operations: String st = Hello,word ; String c1 = color red, c2, c3 = color green ; String bl = ; // one character string String day = reader.next(); System.out.println( The day is : + day); String[ ] days = Sunday, Monday, Thursday }; Note: double quotations c o l o r r e d Like array, every character in the string has its index, but we can t access it directly!. index 33

34 String methods 1 1.string.length(); returns the length of this string. String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); System.out.println( "String Length is : " + len ); 2.Concatenating Strings ( + ) returns a new string that is string1 with string2 added to it at the end. String string1 = "saw I was "; System.out.println( "Dot " + string1 + "Tod ); 3.string.charAt(index); returns the character located at the String's specified index. String st = Welcome to Java"; char result = st.charat(11); System.out.println(result); This would produce following result : J This would produce String Length is : 17 This would produce Dot saw I was Tod 34

35 String methods 2 4. string1.compareto(sryring2) - Compares two strings lexicographically: - The result is zero if the strings are equal. - The result is a negative integer if string1 lexicographically precedes the string2 string. - The result is a positive integer if string1 lexicographically follows the string2 string. We cannot just compare strings contents by simple if statement : String st1 = Hello ; String st2 = Hello ; if(st1==st2) } st1 st2 H e l l o H e l l o because st1 and st2 are memory addresses of st1 and st2. 35

36 compareto method - cont. Characters in Java are based on Unicode character set, which defines an ordering of all possible characters that can be used. The compareto method can be used to determine the relative ( lexicographic ) order of strings. For example: String st1 = AARBNML, st2 = AARZK ; st A A R B N M L st A A R Z K int x=st1.compareto(st2); // x = - 24:

37 compareto method - examples For example: String str1 = "Strings are immutable"; String str2 = "Strings are immutable"; String str3 = "Integers are not immutable"; int result = str1.compareto( str2 ); System.out.println(result); result = str2.compareto( str3 ); System.out.println(result); result = str3.compareto( str1 ); System.out.println(result); This produces following result:

38 String methods 3 5. string.substring ( index ) returns a new string that is a substring of the string. The substring begins with the character at the specified index and extends to the end of this string. String st1 = abcdefg ; String st2 = st1.substring(3); // st2 = defg String st3 = st1.substring(6); // st3 = g 6. string1.indexof(string2) returns the index within string1 of the first occurrence of the substring2. If it does not occur as a substring, -1 is returned. String st1 = abcdefg, st2 = cd,st3 = abc ; int p1 = st1.indexof(st2); // p1= 2 int p2 = st1.indexof(st3); // p2 = 0 int p3 = st1.indexof( xy ); // p3 = -1 38

39 String methods 4 7. string1.indexof(string2, ind) returns the index within string1 of the first occurrence of the substring2 from the ind place. If it does not occur as a substring from ind place, -1 is returned. String st1 = abcdefg ; int p1 = st1.indexof( cd,5); // p1= -1 int p2 = st1.indexof ( cd,1); // p2 = 2 int p3 = st1.indexof( ab,3); // p3 = string.substring ( startindex,endindex ) returns a new string that is a substring of the string. The substring begins with the character at the specified startindex and extends to the endindex (but not including). String st1 = abcdefg ; String st2 = st1.substring(3,6); // st2 = def String st3 = st1.substring(2,5); // st3 = cde 39

40 String methods 5 9. string1.lastindexof(string2) returns the index within string1 of the last occurrence of the substring2. If it does not occur as as substring, -1 is returned. String st1 = abcdeabfg ; int p1 = st1.lastindexof( ab ); // p1= 5 int p2 = st1.lastindexof ( abc ); // p2 = 0 int p3 = st1.lastindexof( xyz ); // p3 = string.replace(oldchar, newchar) returns new string resulting from replacing all occurrences of oldchar in this string with newchar. String s1 = abaabcas ; String s2 = s1.replace( a, * ); // s2 = *b**bc*s 40

41 Empty string String in Java is considered empty if its length is zero. Empty String is represented by String literal. For example: String str1 = ; // empty string String with white space are not considered as empty String in Java. String str2 = ; // five characters string We often needs to check if String is empty or not. There are two ways to find if String is empty or not. 1. Checking if String is empty by using length() Java method : if(str1.length() == 0). 2. Checking if String is empty by using boolean type isempty() Java method : if( str1.isempty() ) 41

42 Empty string - example public class EmptyStringDemo public static void main(string[ ] args) String str = "tutorialspoint"; /* prints length of string str */ System.out.println("length of string = " + str.length()); /* checks if the string str is empty or not */ System.out.println("is this string empty? = " + str.isempty()); } // main } // EmptyStringDemo This will produce the following result : length of string = 14 is this string empty? = false 42

43 String methods - example 1 This program section reads the sentences,calculates and prints it word s numbers. int words = 0; // words counter int i = 0; // loop counter String snc = "Welcome to Java course."; do if( snc.charat(i) == ' ') words++; i++; } while( i< snc.length( ) ); This would produce 4 System.out.println( "The number of words is: "+ (++words));? 43

44 String methods - example 2 This program section reads the string and tests it. If the string is palindrome, the program prints YES, otherwise NO. public static void main(string[] args) boolean flag = true; // help variable String str; // input string System.out.println( Enter the string ); str = reader.next(); int size = str.length(); for(int i = 0; i <size/2 && flag; i++) if(str.charat(i)!= str.charat( size 1 i) flag = false; if(flag) System.out.println( YES ); else System.out.println( NO ); } Size = a b c b a 44

45 String methods - example 3 This program reads the string and builds the array of all characters from the input string which appears only one time. For example: b - 2 times f - 4 times input string = "abcbdefdfffgh" d - 2 times output array is : a c e g h 45

46 example 3 public static void main(string[] args) String st = reader.next(); int i, j, k; // loop counters boolean flag; // help variable int len = str.length(); char[] helparray = new char[len]; // help array for(i = 0;i < len;i++) helparray[i] = str.charat(i); for(i = 0; i < len-1; i++) for(j = i+1,flag = false; j < len; j++) if(helparray[i] == helparray[j]) for(k = j ;k < len-1; k++) helparray[k] = helparray[k+1]; flag = true; j--; len--; } // if solution 46

47 example 3 solution, cont. if( flag ) for(k = i ;k <len-1; k++) helparray[k] = helparray[k+1]; i--; len--; } // if(flag) } // outer for char[ ] finarr = new char[len]; // creating output array for(i = 0;i< len;i++) finarr[i] = helparray[i]; /* printing output array */ for(i = 0;i< len;i++) System.out.print (helparray[i]); System.out.println(); } // main 47

48 Exam question example כתוב תכנית הקולטת מחרוזת של טקסט ומדפיסה מחרוזת חדשה המכילה את אותו טקסט כאשר: 48

49 Exam question - solution String s = reader.next(); String fixstr = ""; for(int i = 0; i < s.length(); i++) if (s.charat(i) == '.' s.charat(i) == ',') /* Remove spaces before point or comma */ for (int j = i-1; j >= 0 && s.charat(j) == ' '; j--) fixstr = fixstr.substring(0,fixstr.length() - 1); fixstr += s.charat(i) + " "; /* Remove redundant spaces after point or comma */ while ( i+1 < s.length() && s.charat(i+1) == ' ') i++; } // if else fixstr += s.charat(i); } // for /* Remove redundant characters after the last point */ for (int i = fixstr.length() - 1; i >= 0 && fixstr.charat(i) == ' '; i--) fixstr = fixstr.substring(0,fixstr.length() - 1); System.out.println( The new string is : + fixstr); 49

50 Two - dimensional arrays Java, as with most languages, supports multi-dimensional arrays - 1-dimensional, 2-dimensional, 3-dimensional,... In practice most arrays are one-dimensional, and two-dimensional. 2-dimensional arrays ( 2D array) are usually represented with a row-column "spreadsheet" style. Two-dimensional arrays are usually visualized as a matrix, with rows and columns. Assume we have an array, arr, with two rows and four columns. int [][] arr = new int[2][4]; // Two rows and four columns Row index Column index

51 Two - dimensional arrays A 2D Array in JAVA is really an Array of Arrays: Assume we have an array : int [ ][ ] nums = new int[5][4]; The above is really equivalent to a 3- step process: 1. create the single reference nums (yellow square) int [ ][ ] nums; 2. create the array of references (blue squares) nums = new int[5][ ]; 3. this create the second level of arrays (red squares) for (int i = 0; i < 5 ; i++) nums[ i ] = new int[4]; // create arrays of integers 51

52 Two - dimensional arrays A 2 - dimensional array in Java can have different numbers of elements in different rows. In other words: a 2-dimensional array in Java is made up with many rows of 1- dimensional arrays. For example: NOTE : We will only discuss and use rectangular 2-dimensional arrays in this course. 52

53 Declaring, Creating and Initializing You can also use an array initializer to declare, create and initialize a two-dimensional array. For example : int [ ][ ] array = 1, 2, 3}, 4, 5, 6}, 7, 8, 9}, 10, 11, 12} }; Same as int [ ][ ] array = new int[4][3]; array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12; static final int ROW = 4; static final int COL = 3; int array = new int [ ROW ][ COL ]; for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) arr[i][ j ] = reader.nextint(); Two-dimensional arrays are almost always processed with nested for loops. The two index variables are often called i and j. 53

54 Lengths of Two-dimensional arrays x int[ ][ ] x = new int[3][4]; x[0] x[0][0] x[0][1] x[0][2] x[0][3] x[0].length is 4 x[1] x[2] x.length is 3 x[1][0] x[1][1] x[1][2] x[1][3] x[2][0] x[2][1] x[2][2] x[2][3] x[1].length is 4 x[2].length is 4 for (int i = 0; i < x.length; i++) for (int j = 0; j < x[ i ].length; j++) System.out.print ( +x[ i ][ j ]); System.out.println ( ); } // for You can get the size of each dimension with the length attribute. This is the most general style. 54

55 Lengths of Two-dimensional arrays If a is a 2- dimensional array then: a[i] is a 1- dimensional array. In other words: a 2- dimensional array in Java is made up with many rows of 1-dimensional arrays. The variable a[i].length contains the number of columns in row i. 55

56 Lengths of Two-dimensional arrays, example. This program section calculates and prints the sum of each column of a 2D rectangular matrix. int sum; // sum of column elements for (int col = 0; col < matrix[0].length; col++) sum = 0; for (int row = 0; row < matrix.length; row++) sum = sum + matrix[row][col]; System.out.println("Sum of column " + (col + 1) + " = " + sum); // outer for 56

57 Lengths of Two-dimensional arrays, example. public static void main(string[ ] args) String[ ][ ] strarray = "this","is","the","first","row"}, "this","is","the","second","row"}, "this","is","the","third","row"} }; for(int i = 0; i < strarray.length; i++) for(int j = 0; j < strarray[ i ].length; j++) System.out.print(strarray[ i ][ j ]+" "); System.out.println(); } // outer for } // main This would produce : this is the first row this is the second row this is the third row 57

58 Lengths of Two-dimensional arrays, example. This program section calculates and prints the maximum element of each row in a 2D matrix. for ( int row = 0; row < matrix.length; row++) largest = matrix[row][0]; for (int col = 1; col < matrix[row].length col++) if (largest < matrix[row][col]) largest = matrix[row][col]; System.out.println("The largest element of row " + (row + 1) + " = " + largest); // outer for 58

59 Two - dimensional array example 1 This program section checks if the diagonal s elements of square matrix are equal. mat.length = 4 Minor diagonal i mat[i][i] mat[i][4-i-1] Main diagonal int [][] mat = 3,0,9,3},-1,7,7,2}, 10,6,6,-15},4,8,5,4}}; boolean flag = true; // help variable int i = 0; // loop counter while ( i < mat.length && flag) if ( mat[ i ][ i ]!= mat[ i ][mat.length - i - 1] ) flag = false; i++; } // while if ( flag ) System.out.println( Yes"); else System.out.println( No"); 59

60 Two - dimensional array example 2 This program section transposes the integer square matrix. public static void main(string[ ] args) System.out.print ("Enter array size: "); int size = reader.nextint(); // size=3 int[ ][ ] a = new int[size][size]; for (int r = 0; r < a.length; r++) for (int c = 0; c < a[0].length; c++) a[r][c] = reader.nextint(); int startc = 1; for (int r = 0; r < a.length; r++) for (int c = startc; c < a[0].length; c++) int temp = a[r][c]; a[r][c] = a[c][r]; a[c][r] = temp; } // inner loop startc++; } // outer loop } // main Original array: Transposed array:

61 Matrix multiplication Typical applications in science and engineering involve implementing various mathematical operations with matrix,for example matrix multiplication: C i, j Note: the number of columns in the A matrix m equals the number of rows in the matrix B. Square matrix 61

62 Matrix multiplication, cont. static final int N = 3; // square matrix double[ ][ ] c = new double[n][n]; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) for (int k = 0; k < N; k++) c[i][j] + = a[i][k] * b[k][j]; } // for j } // for i 62

63 Puzzle 63

Problems with simple variables

Problems with simple variables Problems with simple variables Hard to give up values high number of variables. Complex to sort a high number of variables by value. Impossible to use loops. Example problem: Read one hundred numbers,

More information

Spring 2010 Java Programming

Spring 2010 Java Programming Java Programming: Guided Learning with Early Objects Chapter 7 - Objectives Learn about arrays Explore how to declare and manipulate data in arrays Learn about the instance variable length Understand the

More information

COE 212 Engineering Programming. Welcome to the Final Exam Monday May 18, 2015

COE 212 Engineering Programming. Welcome to the Final Exam Monday May 18, 2015 1 COE 212 Engineering Programming Welcome to the Final Exam Monday May 18, 2015 Instructors: Dr. Joe Tekli Dr. George Sakr Dr. Wissam F. Fawaz Name: Student ID: Instructions: 1. This exam is Closed Book.

More information

More non-primitive types Lesson 06

More non-primitive types Lesson 06 CSC110 2.0 Object Oriented Programming Ms. Gnanakanthi Makalanda Dept. of Computer Science University of Sri Jayewardenepura More non-primitive types Lesson 06 1 2 Outline 1. Two-dimensional arrays 2.

More information

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points.

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points. Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points. Use the remaining question as extra credit (worth 1/2 of the points earned). Specify which question is

More information

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof Array Lecture 12 Based on Slides of Dr. Norazah Yusof 1 Introducing Arrays Array is a data structure that represents a collection of the same types of data. In Java, array is an object that can store a

More information

COE 212 Engineering Programming. Welcome to the Final Exam Tuesday December 15, 2015

COE 212 Engineering Programming. Welcome to the Final Exam Tuesday December 15, 2015 1 COE 212 Engineering Programming Welcome to the Final Exam Tuesday December 15, 2015 Instructors: Dr. Salim Haddad Dr. Bachir Habib Dr. Joe Tekli Dr. Wissam F. Fawaz Name: Student ID: Instructions: 1.

More information

Tasks for fmri-setting (Tasks of first and second pilot study at the end)

Tasks for fmri-setting (Tasks of first and second pilot study at the end) Tasks for fmri-setting (Tasks of first and second pilot study at the end) 1. Faculty int result = 1; int x = 4; while (x > 1) { result = result * x; x--; 7. Find max in list of numbers public static void

More information

Quadratic: the time that it takes to sort an array is proportional to the. square of the number of elements.

Quadratic: the time that it takes to sort an array is proportional to the. square of the number of elements. ITEC 136 Business Programming Concepts Week 12, Part 01 Overview 1 Week 12 Overview Week 11 review Associative Arrays Common Array Operations Inserting shifting elements right Removing shifting elements

More information

Important Java terminology

Important Java terminology 1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as

More information

Arrays. Eng. Mohammed Abdualal

Arrays. Eng. Mohammed Abdualal Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 9 Arrays

More information

Lecture 13: Two- Dimensional Arrays

Lecture 13: Two- Dimensional Arrays Lecture 13: Two- Dimensional Arrays Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. Nested Loops Nested loops nested loop:

More information

Esc101 Mid Semester Exam - II

Esc101 Mid Semester Exam - II Esc101 Mid Semester Exam - II Time Allowed: 1 Hour Max Marks: 75 Instructions: 1. Do not turn this page until the bell rings. 2. YOU MUST WRITE YOUR NAME, ROLL NUMBER & SECTION ON EACH SHEET. 3. Please

More information

Introducing arrays. Week 4: arrays and strings. Creating arrays. Declaring arrays. Initialising arrays. Declaring and creating in one step

Introducing arrays. Week 4: arrays and strings. Creating arrays. Declaring arrays. Initialising arrays. Declaring and creating in one step School of Computer Science, University of Birmingham Java Lecture notes. M. D. Ryan. September 2001. Introducing arrays Week 4: arrays and strings Arrays: a data structure used to store multiple data,

More information

Assignment2013 Please use this document only for verifying if your programs are right. Do not blindly copy paste and waste your time.

Assignment2013 Please use this document only for verifying if your programs are right. Do not blindly copy paste and waste your time. Please use this document only for verifying if your programs are right. Do not blindly copy paste and waste your time. 11/3/2013 TechSparx Computer Training Center Saravanan.G Please use this document

More information

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF - 1

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF -  1 Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 06: Arrays Instructor: AbuKhleif, Mohammad Noor Sep 2017 AbuKhleiF - 1 Instructor AbuKhleif, Mohammad Noor Computer Engineer

More information

Computer Programming, I. Laboratory Manual. Final Exam Solution

Computer Programming, I. Laboratory Manual. Final Exam Solution Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Final Exam Solution

More information

Full file at

Full file at Chapter 1 Primitive Java Weiss 4 th Edition Solutions to Exercises (US Version) 1.1 Key Concepts and How To Teach Them This chapter introduces primitive features of Java found in all languages such as

More information

Chapter 6 Arrays. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 6 Arrays. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 6 Arrays 1 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average. 2 Solution AnalyzeNumbers Run Run with prepared input 3 Objectives

More information

Java Programming: Program Design Including Data Structures. Chapter Objectives

Java Programming: Program Design Including Data Structures. Chapter Objectives Chapter 9: Arrays Java Programming: Program Design Including Data Structures Chapter Objectives Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of array

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. CSE 114, Computer Science 1 Stony Brook University Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

More information

Top-down programming design

Top-down programming design 1 Top-down programming design Top-down design is a programming style, the mainstay of traditional procedural languages, in which design begins by specifying complex pieces and then dividing them into successively

More information

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8 Today... Java basics S. Bowers 1 of 8 Java main method (cont.) In Java, main looks like this: public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); Q: How

More information

Computer programming Code exercises [1D Array]

Computer programming Code exercises [1D Array] Computer programming-140111014 Code exercises [1D Array] Ex#1: //Program to read five numbers, from user. public class ArrayInput public static void main(string[] args) Scanner input = new Scanner(System.in);

More information

Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen)

Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen) Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen) 1 Lesson 9: Introduction Objectives: To Arrays Write programs that handle collections of similar items. Declare

More information

CS 170 Exam 2. Version: A Fall Name (as in OPUS) (print): Instructions:

CS 170 Exam 2. Version: A Fall Name (as in OPUS) (print): Instructions: CS 170 Exam 2 Version: A Fall 2015 Name (as in OPUS) (print): Section: Seat Assignment: Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do

More information

Question: Total Points: Score:

Question: Total Points: Score: CS 170 Exam 2 Section 001 Fall 2014 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than

More information

Tutorial 11. Exercise 1: CSC111 Computer Programming I. A. Write a code snippet to define the following arrays:

Tutorial 11. Exercise 1: CSC111 Computer Programming I. A. Write a code snippet to define the following arrays: College of Computer and Information Sciences CSC111 Computer Programming I Exercise 1: Tutorial 11 Arrays: A. Write a code snippet to define the following arrays: 1. An int array named nums of size 10.

More information

LECTURE 17. Array Searching and Sorting

LECTURE 17. Array Searching and Sorting LECTURE 17 Array Searching and Sorting ARRAY SEARCHING AND SORTING Today we ll be covering some of the more common ways for searching through an array to find an item, as well as some common ways to sort

More information

CS1150 Principles of Computer Science Arrays

CS1150 Principles of Computer Science Arrays CS1150 Principles of Computer Science Arrays Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Read one hundred numbers, compute their

More information

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff();

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff(); COSC 117 Exam 3 Key Fall 2012 Part 1: Definitions & Short Answer (3 Points Each) 1. A method in a class that has no return type and the same name as the class is called what? How is this type of method

More information

CIS Introduction to Computer Programming Spring Exam 1

CIS Introduction to Computer Programming Spring Exam 1 CIS 110 - Introduction to Computer Programming Spring 2017 - Exam 1 Name: Recitation (e.g. 201): PennKey (e.g. eeaton): My signature below certifies that I have complied with the University of Pennsylvania

More information

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1 Name SOLUTION Page Points Score 2 15 3 8 4 18 5 10 6 7 7 7 8 14 9 11 10 10 Total 100 1 P age 1. Program Traces (41 points, 50 minutes)

More information

Announcements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Announcements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Announcements PS 4 is ready, due next Thursday, 9:00pm Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Room TBD Scope: Lecture 1 to Lecture 9 (Chapters 1 to 6 of text) You may bring a sheet of paper (A4, both

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #43 Multidimensional Arrays In this video will look at multi-dimensional arrays. (Refer Slide Time: 00:03) In

More information

Instructor: Eng.Omar Al-Nahal

Instructor: Eng.Omar Al-Nahal Faculty of Engineering & Information Technology Software Engineering Department Computer Science [2] Lab 6: Introduction in arrays Declaring and Creating Arrays Multidimensional Arrays Instructor: Eng.Omar

More information

Introduction to Software Development (ISD) Week 3

Introduction to Software Development (ISD) Week 3 Introduction to Software Development (ISD) Week 3 Autumn term 2012 Aims of Week 3 To learn about while, for, and do loops To understand and use nested loops To implement programs that read and process

More information

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal APCS A Midterm Review You will have a copy of the one page Java Quick Reference sheet. This is the same reference that will be available to you when you take the AP Computer Science exam. 1. n bits can

More information

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Chapter 6 Single-Dimensional Arrays rights reserved. 1 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average. Solution AnalyzeNumbers rights

More information

CS Week 5. Jim Williams, PhD

CS Week 5. Jim Williams, PhD CS 200 - Week 5 Jim Williams, PhD The Study Cycle Check Am I using study methods that are effective? Do I understand the material enough to teach it to others? http://students.lsu.edu/academicsuccess/studying/strategies/tests/studying

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

AP Computer Science A Unit 7. Notes on Arrays

AP Computer Science A Unit 7. Notes on Arrays AP Computer Science A Unit 7. Notes on Arrays Arrays. An array is an object that consists of an of similar items. An array has a single name and the items in an array are referred to in terms of their

More information

Chapter 8 Search and Sort

Chapter 8 Search and Sort Chapter 8 Search and Sort Goals This chapter begins by showing two algorithms used with arrays: selection sort and binary search. After studying this chapter, you will be able to understand how binary

More information

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. Strings Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and

More information

Computer Science is...

Computer Science is... Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic

More information

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

1 Short Answer (10 Points Each)

1 Short Answer (10 Points Each) 1 Short Answer (10 Points Each) 1. Write a for loop that will calculate a factorial. Assume that the value n has been input by the user and have the loop create n! and store it in the variable fact. Recall

More information

Arrays and ArrayLists. David Greenstein Monta Vista High School

Arrays and ArrayLists. David Greenstein Monta Vista High School Arrays and ArrayLists David Greenstein Monta Vista High School Array An array is a block of consecutive memory locations that hold values of the same data type. Individual locations are called array s

More information

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions COSC 123 Computer Creativity Java Decisions and Loops Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) A decision is made by evaluating a condition in an if/

More information

Chapter 5: Arrays. Chapter 5. Arrays. Java Programming FROM THE BEGINNING. Copyright 2000 W. W. Norton & Company. All rights reserved.

Chapter 5: Arrays. Chapter 5. Arrays. Java Programming FROM THE BEGINNING. Copyright 2000 W. W. Norton & Company. All rights reserved. Chapter 5 Arrays 1 5.1 Creating and Using Arrays A collection of data items stored under a single name is known as a data structure. An object is one kind of data structure, because it can store multiple

More information

- Thus there is a String class (a large class)

- Thus there is a String class (a large class) Strings - Strings in Java are objects - Thus there is a String class (a large class) - In a statement like this: System.out.println( Hello World ); the Java compiler creates a String object from the quoted

More information

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each Your Name: Your Pitt (mail NOT peoplesoft) ID: Part Question/s Points available Rubric Your Score A 1-6 6 1 pt each B 7-12 6 1 pt each C 13-16 4 1 pt each D 17-19 5 1 or 2 pts each E 20-23 5 1 or 2 pts

More information

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University LISTS WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Lists with Python 2 Lists with Python

More information

CS1150 Principles of Computer Science Arrays

CS1150 Principles of Computer Science Arrays CS1150 Principles of Computer Science Arrays Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Read one hundred numbers, compute their

More information

Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

More information

CS 1301 Ch 8, Part A

CS 1301 Ch 8, Part A CS 1301 Ch 8, Part A Sections Pages Review Questions Programming Exercises 8.1 8.8 264 291 1 30 2,4,6,8,10,12,14,16,18,24,28 This section of notes discusses the String class. The String Class 1. A String

More information

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

L o o p s. for(initializing expression; control expression; step expression) { one or more statements } L o o p s Objective #1: Explain the importance of loops in programs. In order to write a non trivial computer program, you almost always need to use one or more loops. Loops allow your program to repeat

More information

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Java Decisions and Loops Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) A decision is made by evaluating a condition in an if/else

More information

Creating Strings. String Length

Creating Strings. String Length Strings Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and

More information

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use: CSE 20 SAMPLE FINAL Version A Time: 180 minutes Name The following precedence table is provided for your use: Precedence of Operators ( ) - (unary),!, ++, -- *, /, % +, - (binary) = = =,!= &&

More information

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency Introduction Fundamentals Declaring arrays Indexing arrays Initializing arrays Arrays and functions Multidimensional arrays Sorting and algorithm efficiency An array is a sequence of values of the same

More information

Variable initialization and assignment

Variable initialization and assignment Variable initialization and assignment int variable_name; float variable_name; double variable_name; String variable_name; boolean variable_name; Initialize integer variable Initialize floating point variable

More information

CS115 Principles of Computer Science

CS115 Principles of Computer Science CS5 Principles of Computer Science Chapter Arrays Prof. Joe X. Zhou Department of Computer Science CS5 Arrays. Re: Objectives in Methods To declare methods, invoke methods, and pass arguments to a method

More information

COS 126 General Computer Science Spring Written Exam 1

COS 126 General Computer Science Spring Written Exam 1 COS 126 General Computer Science Spring 2017 Written Exam 1 This exam has 9 questions (including question 0) worth a total of 70 points. You have 50 minutes. Write all answers inside the designated spaces.

More information

Recursion. Java recursive programming: Writing methods that call themselves to solve problems recursively.

Recursion. Java recursive programming: Writing methods that call themselves to solve problems recursively. Recursion recursion: The definition of an operation in terms of itself. Solving a problem using recursion depends on solving smaller occurrences of the same problem. Java recursive programming: Writing

More information

You must bring your ID to the exam.

You must bring your ID to the exam. Com S 227 Spring 2017 Topics and review problems for Exam 2 Monday, April 3, 6:45 pm Locations, by last name: (same locations as Exam 1) A-E Coover 2245 F-M Hoover 2055 N-S Physics 0005 T-Z Hoover 1213

More information

Columns A[0] A[0][0] = 20 A[0][1] = 30

Columns A[0] A[0][0] = 20 A[0][1] = 30 UNIT Arrays and Strings Part A (mark questions). What is an array? (or) Define array. An array is a collection of same data type elements All elements are stored in continuous locations Array index always

More information

Principles of Programming. Chapter 6: Arrays

Principles of Programming. Chapter 6: Arrays Chapter 6: Arrays In this chapter, you will learn about Introduction to Array Array declaration Array initialization Assigning values to array elements Reading values from array elements Simple Searching

More information

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method Appendix 3 Java - String charat() Method This method returns the character located at the String's specified index. The string indexes start from zero. public char charat(int index) index -- Index of the

More information

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1 FACULTY OF SCIENCE AND TECHNOLOGY SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1 ACADEMIC SESSION 2014; SEMESTER 3 PRG102D: BASIC PROGRAMMING CONCEPTS Section A Compulsory section Question

More information

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Principle Recursion is useful in expressing solutions to problems that can be recursively defined: Base Cases:

More information

C/C++ Programming Lecture 18 Name:

C/C++ Programming Lecture 18 Name: . The following is the textbook's code for a linear search on an unsorted array. //***************************************************************** // The searchlist function performs a linear search

More information

You will not be tested on JUnit or the Eclipse debugger. The exam does not cover interfaces.

You will not be tested on JUnit or the Eclipse debugger. The exam does not cover interfaces. Com S 227 Fall 2016 Topics and review problems for Exam 2 Thursday, November 10, 6:45 pm Locations, by last name: (same locations as Exam 1) A-C Curtiss 0127, first floor only D-N Hoover 2055 O-Z Troxel

More information

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial: Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Factorial (1) Recall the formal definition of calculating the n factorial: 1 if n = 0 n! = n (n 1) (n 2) 3 2

More information

COE 212 Engineering Programming. Welcome to Exam II Thursday April 21, Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F.

COE 212 Engineering Programming. Welcome to Exam II Thursday April 21, Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F. 1 COE 212 Engineering Programming Welcome to Exam II Thursday April 21, 2016 Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F. Fawaz Name: Student ID: Instructions: 1. This exam is Closed Book.

More information

CSE 114 Computer Science I

CSE 114 Computer Science I CSE 114 Computer Science I Iteration Cape Breton, Nova Scotia What is Iteration? Repeating a set of instructions a specified number of times or until a specific result is achieved How do we repeat steps?

More information

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it Last Class Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it public class February4{ public static void main(string[] args) { String[]

More information

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java Electrical and Computer Engineering Object-Oriented Topic 2: Fundamental Structures in Java Maj Joel Young Joel.Young@afit.edu 8-Sep-03 Maj Joel Young Java Identifiers Identifiers Used to name local variables

More information

Objectives of This Chapter

Objectives of This Chapter Chapter 6 C Arrays Objectives of This Chapter Array data structures to represent the set of values. Defining and initializing arrays. Defining symbolic constant in a program. Using arrays to store, list,

More information

CIS 110 Introduction to Computer Programming. 12 February 2013 Midterm. Answer Key

CIS 110 Introduction to Computer Programming. 12 February 2013 Midterm. Answer Key CIS 110 Introduction to Computer Programming 12 February 2013 Midterm Answer Key 0. (1 point) Miscellaneous (a) Write your name, recitation number, and PennKey (username) on the front of the exam. (b)

More information

Computer Applications Answer Key Class IX December 2017

Computer Applications Answer Key Class IX December 2017 Computer Applications Answer Key Class IX December 2017 Question 1. a) What are the default values of the primitive data type int and float? Ans : int = 0 and float 0.0f; b) Name any two OOP s principle.

More information

Lecture #8-10 Arrays

Lecture #8-10 Arrays Lecture #8-10 Arrays 1. Array data structure designed to store a fixed-size sequential collection of elements of the same type collection of variables of the same type 2. Array Declarations Creates a Storage

More information

Chapter 4: Control Structures I

Chapter 4: Control Structures I Chapter 4: Control Structures I Java Programming: From Problem Analysis to Program Design, Second Edition Chapter Objectives Learn about control structures. Examine relational and logical operators. Explore

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #04: Fall 2015 1/20 Office hours Monday, Wednesday: 10:15 am to 12:00 noon Tuesday, Thursday: 2:00 to 3:45 pm Office: Lindley Hall, Room 401C 2/20 Printing

More information

Last Class. While loops Infinite loops Loop counters Iterations

Last Class. While loops Infinite loops Loop counters Iterations Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

More information

Chapter 9 Introduction to Arrays. Fundamentals of Java

Chapter 9 Introduction to Arrays. Fundamentals of Java Chapter 9 Introduction to Arrays Objectives Write programs that handle collections of similar items. Declare array variables and instantiate array objects. Manipulate arrays with loops, including the enhanced

More information

To become familiar with array manipulation, searching, and sorting.

To become familiar with array manipulation, searching, and sorting. ELECTRICAL AND COMPUTER ENGINEERING 06-88-211: COMPUTER AIDED ANALYSIS LABORATORY EXPERIMENT #2: INTRODUCTION TO ARRAYS SID: OBJECTIVE: SECTIONS: Total Mark (out of 20): To become familiar with array manipulation,

More information

CMPS 12A - Winter 2002 Final Exam A March 16, Name: ID:

CMPS 12A - Winter 2002 Final Exam A March 16, Name: ID: CMPS 12A - Winter 2002 Final Exam A March 16, 2002 Name: ID: This is a closed note, closed book exam. Any place where you are asked to write code, you must declare all variables that you use. However,

More information

Computer Programming, I. Laboratory Manual. Experiment #9. Multi-Dimensional Arrays

Computer Programming, I. Laboratory Manual. Experiment #9. Multi-Dimensional Arrays Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #9

More information

COMPUTER SCIENCE. 4. Arrays. Section 1.4.

COMPUTER SCIENCE. 4. Arrays. Section 1.4. COMPUTER SCIENCE S E D G E W I C K / W A Y N E 4. Arrays Section 1.4 http://introcs.cs.princeton.edu Basic building blocks for programming any program you might want to write objects functions and modules

More information

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Michele Van Dyne Museum 204B  CSCI 136: Fundamentals of Computer Science II, Spring Michele Van Dyne Museum 204B mvandyne@mtech.edu http://katie.mtech.edu/classes/csci136 CSCI 136: Fundamentals of Computer Science II, Spring 2016 1 Review of Java Basics Data Types Arrays NEW: multidimensional

More information

Write a C program using arrays and structure

Write a C program using arrays and structure 03 Arrays and Structutes 3.1 Arrays Declaration and initialization of one dimensional, two dimensional and character arrays, accessing array elements. (10M) 3.2 Declaration and initialization of string

More information

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers; Arrays What are they? An array is a data structure that holds a number of related variables. Thus, an array has a size which is the number of variables it can store. All of these variables must be of the

More information

Arrays and Strings. Arrays - homogeneous indexed collections Selection sort as array example. String class, revisited

Arrays and Strings. Arrays - homogeneous indexed collections Selection sort as array example. String class, revisited Arrays and Strings Arrays - homogeneous indexed collections Selection sort as array example Introduction to complexity analysis String class, revisited 1 Arrays Homogeneous collections of elements of same

More information

The data in the table are arranged into 12 rows and 12 columns. The process of printing them out can be expressed in a pseudocode algorithm as

The data in the table are arranged into 12 rows and 12 columns. The process of printing them out can be expressed in a pseudocode algorithm as Control structures in Java are statements that contain statements. In particular, control structures can contain control structures. You've already seen several examples of if statements inside loops,

More information

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS ARRAYS A Java array is an Object that holds an ordered collection of elements. Components of an array can be primitive types or may reference objects, including other arrays. Arrays can be declared, allocated,

More information

Strings, Strings and characters, String class methods. JAVA Standard Edition

Strings, Strings and characters, String class methods. JAVA Standard Edition Strings, Strings and characters, String class methods JAVA Standard Edition Java - Character Class Normally, when we work with characters, we use primitive data types char. char ch = 'a'; // Unicode for

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014 M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014 Question One: Choose the correct answer and write it on the external answer booklet. 1. Java is. a. case

More information