
Multi-Dimensional Arrays and Constants in Programming Languages
"Explore the concepts of one-dimensional and two-dimensional arrays, constants, and the #define directive in programming languages. Learn about data types in C/C++, passing arrays to functions, and performing operations on arrays. Dive into key points, exercises, and examples to enhance your understanding of arrays and constants."
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
CS112 Level 1 Programming Languages 1 Lecture 2 One-Dimensional, Two-Dimensional Arrays, Constants, .. and .. the #define Directive Course & Lectures are based on their counterparts in the following courses: o Harvard University'sCS50; An introduction to the intellectual enterprises of computer science and the art of programming, Harvard School of Engineering and Applied Sciences. o UNSW'sCS1: Higher Computing, by Richard Buckland The University of New South Wales. o MIT's6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++ (2013), MIT (Massachusetts Institute of Technology) OpenCourseWare. 1
Data Types in C/C++ Write a C program to calculate the average of an arbitrary number of scores? Arrays Arrays .. Why? Precautions when using an Array Arrays Example Passing Arrays to Functions Arrays: Key Points Multi-Dimensional Arrays Two-Dimensional Arrays Exercise: Calculating the Average Passing 1-D Array to a function Passing a 2-D Array to a function Multiple-Subscripted Arrays: Key Points Write a program in C to print an array s elements using recursion. Write a Program in C to Add two Matrices of the same size. 2 O u t l i n e Outline
Recap Data Types in C/C++ .. bool - a Boolean expression of either true or false char - a single character like a , ? , or 2 float - a real number with a decimal value/point double - a floating-point value with even more digits int - integers up to a certain size, or number of bits, & their negatives long - integers with more bits, so they can count higher string - a(n) string/array of characters ...
Recap Inside our computers, we have chips called RAM, random- access memory, that stores data for short-term use. We might save a program or file to our hard drive (or SSD) for long-term storage, but when we open it, it gets copied to RAM first. Though RAM is much smaller, and temporary (until the power is turned off), it is much faster.
Recap We can think of bytes, stored in RAM, as though they were in a grid: 5
Recap A character or a boolean, stored in 1 byte .. 6
Recap An integer or a float, stored in 4 bytes .. 7
Recap A double, in 8 bytes ..
2.1: Write a C program to calculate the average of 3 numbers. #include <stdio.h> intmain( void ) { // Scores int score1 = 72; int score2 = 73; int score3 = 33; // Print average printf("Average: %f\n", (score1 + score2 + score3) / 3.0); } What if we have 5 numbers entered by the user?
2.2: Write a C program to calculate the average of 5 numbers, and read those numbers from the user. #include <stdio.h> intmain( void ) { // Scores int score1, score2, score3, score4, score5; printf("\nEnter 1st score:"); printf("\nEnter 2nd score:"); printf("\nEnter 3rd score:"); printf("\nEnter 4th score:"); printf("\nEnter 5th score:"); // Print average printf("Average: %f\n", (score1 + score2 + score3 + score4 + score5) / 5.0); } scanf("%d", &score1); scanf("%d", &score2); scanf("%d", &score3); scanf("%d", &score4); scanf("%d", &score5);
2.3: Write a C program to calculate the average of an arbitrary number of scores? We can print the average of 3 or 5 numbers, BUT now we need to make one variable for every score we want to include! And we can t easily use them later! #include <stdio.h> intmain( void ) { // Scores int score1, score2, score3, score4, score5 .. ? printf("\nEnter 1st score:"); printf("\nEnter 2nd score:"); printf("\nEnter 3rd score:"); printf("\nEnter 4th score:"); printf("\nEnter 5th score:"); .. ? // Print average printf("Average: %f\n", (score1 + score2 + score3 + score4 + .. ? ) /.. ?); } scanf("%d", &score1); scanf("%d", &score2); scanf("%d", &score3); scanf("%d", &score4); scanf("%d", &score5);
Arrays It turns out, in memory, we can store variables one after another, back-to- back. And in C, a list of variables stored, one after another in a contiguous chunk of memory, is called an array .. 0 1 2 3 4 5 Arrays are data structures that allow us to store data of the same type in contiguous memory locations .. Note that array indices in C always start at 0!
Arrays .. Why? Various problems in life need arrays, for example: o A group of grades for a student needs to be saved together. If you save these grades for example 5 grades without using an array, you have to define 5 different variables. But if you use arrays, you can define just one variable as an array that contains 5 values. o Thus, when we need a way to hold different homogenous values in order to apply some sort of processing on all of these values. Varying processing types may be applied, such as calculating the average of these values, or the total summation of the values, etc.
Arrays Declare an array by specifying the data type it will store, its name, as well as its size. <data type> name[<size>]; Array declaration The values in this array are three values. number of Declare that the values array are going to be integers. This means that every value is going to be an integer. in this The name of the array is a. To read any value in this array, you are going to use this name.
Arrays Array declaration and initialization: You can set all values of the array in just one line. The number of values in this array are three values. Declare that the values array is going to be integers. This means that every value is going to be integer. in this The values in this array. You will notice that they are 3, and they are all integers. The first value is 4, the second value is 7, the third value is 2. The name of the array is a. To read any value in this array, you are going to use this name.
Arrays RAM o An Array is a consecutive group of variables (memory locations), all those constituting variables have the same type, and share a common name. o Array a: o int a[3] = { 4, 7, 2 }; o In this case, a place in the memory is located for this array. o The name of this place is a. o The values in this place are 4, 7, and 2. o The type of the values is integer. o The size of this place is (3 * 4) bytes, where 3 is the number of integers. 4 7 a 2
Arrays Another Example .. Here, we declare an array of 3 integers called temperature and load it with values. int temperature[3]; temperature[0] = 65; temperature[1] = 87; temperature[2] = 30; 0 1 2 65 87 30 To access any value of an array, you have to know its index. The index is the position of the value in the array. The index of the first element is zero. OR .. Alternatively, you can declare and initialize the array in a single step (in which case stating the size is optional). int temperature[] = { 65, 87, 30 };
Arrays Accessing Array Elements 0 1 2 65 87 30 for (int i = 0; i < 3; i++) { printf("%d\n", temperature[i]); }
Arrays Example RAM #include <stdio.h> int main(){ int a[3]; a Define an array of 3 integers }
Arrays Example RAM #include <stdio.h> int main(){ int a[3]; a[0] = 4; 4 Set the first value by 4 a Notice that arrays are zero-indexed, meaning that the first element, or value, has index 0. }
Arrays Example RAM #include <stdio.h> int main(){ int a[3]; a[0] = 4; a[1] = 7; Set the second value by 7 4 7 a }
Arrays Example RAM #include <stdio.h> int main(){ int a[3]; a[0] = 4; a[1] = 7; a[2] = 2; Set the third value by 2 4 7 2 a }
Arrays Example RAM #include <stdio.h> int main(){ You can not access an element int a[3]; a[0] = 4; a[1] = 7; a[2] = 2; a[3] = 5; outside the array. If you do so, 4 7 2 the program will not run, and a give an error saying : array-index-out-of-bound error } where this index in not included in your array
Arrays Example Use a for loop to set the values of an array by the user #include <stdio.h> int main(){ int a[3]; for ( int i = 0; i < 3; i++ ) { scanf("%d", &a[i]); } Notice that a 3 is the limit of the for loop }
2.3: Write a C program to calculate the average of an arbitrary number of grades? Lets try to solve this problem by using arrays and for loops: #include <stdio.h> int main() { //declare and initialize the array, an array of 5 grades int grades[5] = { 73, 35, 63, 81, 12 }; float avg; int sum = 0; for ( int i = 0; i < 5; i++ ) { sum = sum + grades[ i ]; } avg = (float) sum / 5; printf("The average is: %f", avg); }
2.3: Write a C program to calculate the average of an arbitrary number of grades? Lets try to solve this problem by using arrays and for loops: #include <stdio.h> int main() { //declare and initialize the array, an array of 5 grades int grades[5] = { 73, 35, 63, 81, 12 }; float avg; int sum = 0; for ( int i = 0; i < 5; i++ ) { sum = sum + grades[ i ]; } avg = (float) sum / 5; printf("The average is: %f", avg); } Notice that we repeated the value 5, representing the length of our array, in three different places. So we can use a constant, or fixed value, to indicate it should always be the same in those places.
Arrays Example #include <stdio.h> int main() { const int x = 5; int grades[x]; //declare the array for ( int i = 0; i < x; i++ ) { printf("\nEnter garde %d: ", i); scanf("%d", &grades[i]); } float avg; int sum = 0; for ( int i = 0; i < x; i++ ) { sum = sum + grades[ i ]; } avg = (float) sum / x; printf("The average is: %f", avg); } When declaring an array, the number of values in the array should be a constant variable. because the size of the array should be predefined and can not be during the running of the program. That is changed
Remarks const int x = 5; The const keyword specifies that the object or variable is not modifiable (i.e., specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.) #define PI 3.14 A Pre-processor directive (#define identifier replacement) ... When the pre- processor encounters this directive, it replaces any occurrence of identifier in the rest of the code by replacement.
Here's an example of the usage of an array to keep track of student scores. This code prompts the user to enter a score for each student. Scores are stored in scores_array. #include <stdio.h> #define CLASS_SIZE 30 int main(void) { // declare array int scores_array[CLASS_SIZE]; // populate array for (int i = 0; i < CLASS_SIZE; i++) { printf("Enter score for student %d: ", i + 1); scanf("%d: ", &scores_array[i]); } }
Precautions when using an Array o Two important precautions should be taken into consideration: o You can not define the size of an array using variables o int x = 3; o int a[ x ]; array size cannot be a variable o You can not access an element outside the array (i.e., calling an index that is out of the array size). o int a[ 3 ]; o a[ 4 ] = 5; array-index-out-of-bound
Passing Arrays to Functions Passing arrays: o To pass an array argument to a function, specify the name of the array without any brackets: o int myArray[ 24 ]; o myFunction( myArray, 24 ); o Array size usually passed to function o Function prototype: o void modifyArray( int b[], int arraySize ); o Parameter names are optional in prototypes: o int b[] could be written int []. o int arraySize could be simply int.
Passing Arrays to Functions #include <stdio.h> double getAverage( int arr[], int size ) { int i, sum = 0; double avg; for ( i = 0; i < size; ++i ) { sum += arr[ i ]; } avg = (double) sum / size; return avg; } int main() { const int size = 6; int grades[] = { 73, 35, 63, 81, 12, 70 }; printf("Average: %f ", getAverage( grades, size ) ); return 0; }
Name of array (Note Name of array (Note that that all elements of all elements of this array have the this array have the same name, c) same name, c) Arrays: Key Points Arrays are: o Structures of related data items o Static entity same size throughout the program o Group of consecutive memory locations o Same name and type o To refer to an element, specify o Array name o Position number o Format: o arrayname[position number] o First element at position 0 o n element array named c: c[ 0 ], c[ 1 ], .., c[ n 1 ] c[0] c[0] - -45 45 c[1] c[1] 6 6 c[2] c[2] 0 0 c[3] c[3] 72 72 c[4] c[4] 1543 1543 c[5] c[5] - -89 89 c[6] c[6] 0 0 c[7] c[7] 62 62 c[8] c[8] - -3 3 c[9] c[9] 1 1 c[10] c[10] 6453 6453 c[11] c[11] 78 78 Position number of Position number of the element within the element within array c array c
Arrays: Key Points Array elements are like normal variables o c[ 0 ] = 3; o printf( "%d", c[ 0 ] ); o Perform operations in subscript. If x equals 3 c[ 5 - 2 ] == c[ 3 ] == c[ x ]
Arrays: Key Points When defining arrays, specify: o Name o Type of array o Number of elements o arrayType arrayName[ numberOfElements ]; o Examples: o int c[ 10 ]; o float myArray[ 3284 ]; o Defining multiple arrays of same type: o Format similar to regular variables. o For example: o int b[ 100 ], x[ 27 ];
Arrays Multi- Dimensional Two-Dimensional Arrays
Multidimensional Arrays Arrays can be multidimensional. You can think of multidimensional arrays as "arrays of arrays." 0,0 0,1 0,2 x x char board[3][3]; board[1][1] = 'o'; board[0][0] = 'x'; board[2][0] = 'o'; board[0][2] = 'x'; 1,0 1,1 1,2 o Here, we declared and initialized a 2-dimensional array tic-tac-toe board. 2,0 2,1 2,2 o
Multidimensional Arrays Accessing Multidimensional Array Elements This code uses nested for loops to print out all elements of the tic-tac-toe board array. // print out all elements for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("%c ", board[i][j]); } printf("\n"); }
2 Dimensional Arrays A 2-dimentional array a which contains three rows and four columns can be represented as:
2 Dimensional Arrays A two dimensional array is the same as several identical arrays put together. It is a matrix that consists of a certain number of rows and columns. For example: const int NumRows = 3; const int NumCols = 7; int Array[NumRows][NumCols]; 0 1 2 3 4 5 6 0 1 2 Where: Array[2][5] is the 3rd value (row) in 6th column ..
2 Dimensional Arrays An one-dimensional array is usually processed via a for loop. Similarly, a two-dimensional array may be processed using two nested loops. 0 0 1 0 2 0 3 0 4 0 5 0 6 0 0 const int NumCols = 7; int Array[ NumCols ]; for ( int Col = 0; Col < NumCols; Col++ ) { Array[ Col ] = 0; }
2 Dimensional Arrays A one-dimensional array is usually processed via a for loop. Similarly, a two-dimensional array may be processed using two nested loops. 0 0 0 0 1 0 0 0 2 0 0 0 3 0 0 0 4 0 0 0 5 0 0 0 6 0 0 0 0 1 2 const int NumRows = 3; const int NumCols = 7; int Array[ NumRows ][ NumCols ]; for ( int Row = 0; Row < NumRows ; Row++ ) { for ( int Col = 0; Col < NumCols; Col++ ) { Array[ Row ][ Col ] = 0; } }
2 Dimensional Arrays A one dimensional array can be initialized while declared as follows: int Array[ 7 ]={ 0, 0, 0, 0, 0, 0, 0 }; Also a two dimensional array can be initialized while declared as follows: int Array[ 3 ][ 7 ] = { { 0, 0, 0, 0, 0, 0, 0 }, {0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 } };
2 Dimensional Arrays If you define a two dimensional array as follows: int grades[ 3 ][ 6 ]; What is the size of this array in the memory? There is in an operator in C++ that can yield the size of the array: printf("%d", sizeof( grades ) ); The output of this method in this case is: sizeof( grades ) = 4 * 3 * 6 = 72 where 4 is the size of an integer, 3 is the number of rows, and 6 is the number of columns.
2.4: Exercise: Calculating the Average Let s try to find the average of the grades for a group of students (not a single student as in the previous problem). If you have a set of 6 grades per student, for three students: The grades of the 1st student are: 73, 35, 63, 81, 12, and 70. The grades of the 2nd student are: 63, 56, 31, 31, 52, and 58. The grades of the 3rd student are 53, 45, 73, 31, 12, and 20. o Calculate the average value of the grades for each student. o Print this average.
2.4: Solution: Calculating the Average Thus we have 3 students * 6 subjects Therefore, we need a two dimensional array: with 3 rows, one for each student. with 6 columns, one for each subject. 0 1 2 3 4 5 0 1 2 73 63 53 35 56 45 63 31 73 81 31 31 12 52 12 70 58 20
2.4: Solution: Calculating the Average #include <stdio.h> int main() { int grades[3][6] = { { 73, 35, 63, 81, 12, 70 }, { 63, 56, 31, 31, 52, 58 }, { 53, 45, 73, 31, 12, 20 } }; for ( int i = 0; i < 3; i ++) { int sum = 0; float average; for ( int j = 0; j < 6; j++ ) { sum = sum + grades[ i ][ j ]; } average = (float) sum / 6; printf( "Average of the grades for student %d is: ", i + 1 ); printf( "%f\n", average ); } } The output is : Average of the grades for student 1 is 55 Average of the grades for student 2 is 48 Average of the grades for student 3 is 39
Passing 1-D Array to a function #include <stdio.h> int getMax(int arr[], int R) { int max = 0; for(int i = 0; i < R; i++) if(max < arr[ i ]) max = arr[ i ]; return max; } int main() { int array[2]; for(int i = 0; i < 2; i++) scanf("%d", &array[ i ]); printf("%d", getMax(array, 2) ); } This is called a function call getMax(array, 2) The first parameter is a 1 dimensional array, and the second parameter is an integer just like the function defined above.
Passing a 2-D Array to a function #include <stdio.h> const int C = 4; int getMax(int arr[][C], int R) { int max = 0; for(int i = 0; i < R; i++) for(int j = 0; j < C; j++) if(max < arr[i][j]) max = arr[i][j]; return max; } int main(){ int array[3][C]; for(int i = 0; i < 3; i++) for(int j = 0; j < C; j++) scanf("%d", &array[ i ][ j ]); printf("%d", getMax( array, 3 ) ); } We can also pass C as we pass R, or make them both constants too (but these constants should be global, i.e. can be accessed by both the main and the getMax functions). This is called a function call getMax(array, 3) The first parameter is a 2 dimensional array, and the second parameter is an integer just like the function defined above.