Document Details

Uploaded by Deleted User

Visayas State University

William Evan P. Mancao

Tags

computer programming arrays C programming data structures

Summary

This document is a presentation about arrays in C programming. It discusses one-dimensional and two-dimensional arrays, their initialization, and how they are passed as function arguments. The presentation also includes examples of code snippets in C. This supplementary material is from Visayas State University

Full Transcript

MODULE 7: ARRAYS CSIT 102: COMPUTER PROGRAMMING I 1ST SEMESTER; SY: 2024-2025 | BSIT I Mr. William Evan P. Mancao [email protected] LEARNING OBJECTIVES  LO16: Understand and...

MODULE 7: ARRAYS CSIT 102: COMPUTER PROGRAMMING I 1ST SEMESTER; SY: 2024-2025 | BSIT I Mr. William Evan P. Mancao [email protected] LEARNING OBJECTIVES  LO16: Understand and manipulate arrays in C. W. MANCAO 2024 2 OUTLINE  Lesson 7.1: One-Dimensional Arrays  Input and Output of Array Values  Lesson 7.2: Array Initialization  Lesson 7.3: Arrays as Function Arguments  Lesson 7.4: Two-Dimensional Arrays W. MANCAO 2024 3 OVERVIEW Scalar variables store a single value at a time. o A scalar variable holds an atomic type that cannot be subdivided or further separated. Often, a set of values of the same data type forms a logical group. A single-dimensional array is a list of individual items of the same scalar data type. We will also explore multidimensional arrays and how to declare and use them. W. MANCAO 2024 4 SUMMARY Let us begin with the end in mind. W. MANCAO 2024 5 SUMMARY: Single-Dimensional Array o It is a data structure that can be used to store a list of values of the same data type. ▪ Must be declared by giving the data type of the values that are stored in the array and the array size. e.g., int num; Creates an array of 100 integers. W. MANCAO 2024 6 SUMMARY: Single-Dimensional Array ▪ It is better to use a constant for the array size and then use it in the definition of the array; For example: #define MAXSIZE 100 int num[MAXSIZE]; W. MANCAO 2024 7 SUMMARY: Single-Dimensional Array o Array elements are stored in contiguous memory locations. ▪ Elements are accessed using the array name and a subscript (e.g., num). ▪ A subscript can be any nonnegative integer value. ▪ The subscript 0 refers to the first element in an array. W. MANCAO 2024 8 SUMMARY: Single-Dimensional Array o Single-dimensional arrays can be initialized during declaration. ▪ Initialization is done by listing values within braces, separated by commas. ▪ e.g., int nums[] = {3, 7, 8, 15}; W. MANCAO 2024 9 SUMMARY: Single-Dimensional Array o Single-dimensional arrays are passed to functions by passing the array name as an argument. ▪ The address of the first array element is passed, not a copy of the array. ▪ The called function gets direct access to the original array. ▪ The size of the array can be omitted in the function parameter. W. MANCAO 2024 10 SUMMARY: Two-Dimensional Array o This is declared by specifying both row and column sizes. ▪ The array is declared with the data type and name followed by the sizes in square brackets; e.g., ▪ #define ROWS 5 #define COLS 7 int mat[ROWS][COLS]; ▪ This creates a 2D array with 5 rows and 7 columns of integer values. W. MANCAO 2024 11 SUMMARY: Two-Dimensional Array o Two-dimensional arrays can be initialized during declaration by listing values row-by-row within braces. ▪ Each row's values are enclosed in curly braces and separated by commas. ▪ int vals[ROWS][COLS] = { {1, 2}, ▪ {3, 4}, ▪ {5, 6} }; W. MANCAO 2024 12 SUMMARY: Two-Dimensional Array o Two-dimensional arrays can be initialized during declaration by listing values row-by-row within braces. ▪ This creates a 3x2 array with the following values: ▪ 1 2 3 4 5 6 W. MANCAO 2024 13 SUMMARY: Two-Dimensional Array o Two-dimensional arrays can be initialized during declaration by listing values row-by-row within braces. ▪ C initializes two-dimensional arrays in row-wise order. The inner braces can be omitted in the initialization. ▪ int vals[ROWS][COLS] = {1, 2, 3, 4, 5, 6}; ▪ This is functionally the same as using inner braces and will create the same 3x2 array above. W. MANCAO 2024 14 SUMMARY: Two-Dimensional Array o Two-dimensional arrays are passed to functions by passing the array name as an argument. ▪ In the called function, a parameter must be declared to receive the array. ▪ The row size can be omitted in the parameter declaration. ▪ The column size must still be specified in the parameter. W. MANCAO 2024 15 Lesson 7.1: One-Dimensional Arrays A. Input and Output of Array Values W. MANCAO 2024 16 Lesson 7.1: One-Dimensional Arrays A single-dimensional array (aka. one-dimensional array) - a list of values of the same data type. e.g., an array to store five integers: o int grades; Other examples: o char code; // an array of 4 characters o double prices; // an array of 6 double precision numbers o float amount; // an array of 100 floating-point numbers W. MANCAO 2024 17 Lesson 7.1: One-Dimensional Arrays Each array has enough memory reserved to store the number of elements specified in the declaration. e.g., o code reserves space for 4 characters. o prices reserves space for 6 doubles. o amount reserves space for 100 floats. W. MANCAO 2024 18 Lesson 7.1: One-Dimensional Arrays Each item in an array is called an element (aka. component) of the array. o Array elements are stored sequentially in memory, and can be accessed using the array name and the subscript (or index) of the element. o The subscript starts at 0 for the first element, 1 for the second element, and so on. In C, the array name and subscript are combined using square brackets: o arrayName[subscript]; W. MANCAO 2024 19 Lesson 7.1: One-Dimensional Arrays e.g., #define NUM_MAX 5; int grades[NUM_MAX]; grades = 98; grades = 87; grades = 92; grades = 79; grades = 85; W. MANCAO 2024 20 Lesson 7.1: One-Dimensional Arrays W. MANCAO 2024 21 Lesson 7.1: One-Dimensional Arrays Subscripted variables can be used anywhere that scalar variables are valid. e.g., grades = 98; grades = grades – 11; grades = 2 * (grades – 6); grades = 79; grades = (grades + grades – 3 ) / 2; total = grades + grades + grades + grades + grades ; W. MANCAO 2024 22 Lesson 7.1: One-Dimensional Arrays Any expression that evaluates to an integer may be used as a subscript. e.g., assuming that i and j are integer variables: grades [i]; grades [2*i]; grades [j-i]; W. MANCAO 2024 23 Lesson 7.1: One-Dimensional Arrays The subscript value in each of the subscripted variables in this statement can be replaced by the counter in a for loop to access each element in the array sequentially. e.g., Below sequentially retrieves each array element and adds the element to the total. #define NUMELS 5 total = 0; for (i = 0; i < NUMELS; i++ ) total = total + grades [i]; W. MANCAO 2024 24 Lesson 7.1: One-Dimensional Arrays e.g. 2, When an element with a higher value is located, that element becomes the new maximum. #define NUMELS maximum = price; for (i = 1 ; i < NUMELS; i++) if (price[i] > maximum) maximum = price[i] ; W. MANCAO 2024 25 Input and Output of Array Values Individual array elements - can be assigned values using individual assignment statements or the scanf() function. e.g., price = 10.69 ; scanf (“%d %lf”, &grades , &price ) scanf (“%c”, &code ); scanf (“%d %d %d”, &grades, &grades, &grades); W. MANCAO 2024 26 Input and Output of Array Values for statement - can be used to cycle through the array for interactive data input. e.g., #define NUMELS for (i = 0 ; i < NUMELS; i++) { printf (“Enter a grade : ”); scanf (“%d”, &grade[i]); } W. MANCAO 2024 27 Input and Output of Array Values CAUTION: On storing data in an array, C does not check the value of the index being used (bound check) o If an array has been declared as consisting of 10 elements and you use an index of 12, which is outside the bounds of the array, C will not notify you of the error when the program is compiled. o e.g., printf (“The value of element %d is %d”, i, grades[i]); W. MANCAO 2024 28 Input and Output of Array Values Sample output: Enter a grade: 85 Enter a grade: 90 Enter a grade: 78 Enter a grade: 75 Enter a grade: 92 grades 0 is 85 grades 1 is 90 grades 2 is 78 grades 3 is 75 grades 4 is 92 W. MANCAO 2024 29 Input and Output of Array Values Statement is outside of the second for loop; total is displayed only once, after all values have been added W. MANCAO 2024 30 Lesson 7.2: Array Initialization W. MANCAO 2024 31 Lesson 7.2: Array Initialization  Arrays - like scalar variables, can be declared either inside or outside a function.  Local arrays - declared inside a function  Global arrays - declared outside a function. W. MANCAO 2024 32 Lesson 7.2: Array Initialization 1 #define SIZE1 20 2 #define SIZE2 25 3 #define SIZE3 15 4 5 int gallons[SIZE1]; 6 static int dist[SIZE2]; 7 W. MANCAO 2024 33 Lesson 7.2: Array Initialization 8 int main() 9 { 10 int miles[SIZE3]; 11 static int course[SIZE3]; 12. 13. 14 return 0; 15 } W. MANCAO 2024 34 Lesson 7.2: Array Initialization  Global arrays (dist and gallons)  Declared globally.  Created once at compilation time.  Retain values until main() finishes executing.  Static local array (course)  Declared as static local.  Created once at compilation time.  Retains values until main() finishes executing. W. MANCAO 2024 35 Lesson 7.2: Array Initialization  Automatic local array (miles)  Declared as auto local.  Created and destroyed each time the function is called.  Created and destroyed 10 times during execution. W. MANCAO 2024 36 Lesson 7.2: Array Initialization  Automatic vs. Static AUTOMATIC STATIC Lifetime Created and destroyed Created once and each time the function persists for the duration is called. of the program. Initialization Not initialized unless Automatically initialized explicitly done. to zero if not provided with explicit values. Memory Allocated on the stack Allocated in the data for each function call. segment, retains its memory across function calls. W. MANCAO 2024 37 Lesson 7.2: Array Initialization  E.g., int grades = {98, 87, 92, 79, 85}; char codes = {'s', 'a', 'm', 'p', 'l', 'e'}; double width = {10.96, 6.43, 2.58, 0.86, 5.89, 7.56, 8.22}; W. MANCAO 2024 38 Lesson 7.2: Array Initialization  Initializer order - Values are applied in the order they are written in the initializer list. E.g., int grades = {98, 87, 92, 79, 85}; The first value 98 initializes element 0 of the array grades. The second value 87 initializes element 1, and so on. This process continues until all values in the initializer list have been used. W. MANCAO 2024 39 Lesson 7.2: Array Initialization  Whitespace Ignorance - In C, whitespace (such as spaces, tabs, and newlines) is ignored, so initializations can span multiple lines.  E.g., int gallons = { 19, 16, 14, 19, 20, 18, 12, 10, 22, 15, 18, 17, 16, 14, 23, 19, 15, 18, 21, 5}; W. MANCAO 2024 40 Lesson 7.2: Array Initialization  When Initializers are Fewer than Array Elements  Then, the initializers are applied starting from array and continue until all initializers are used.  The remaining elements (those without initializers) will be automatically initialized to zero.  E.g., float length = {7.8, 6.4, 4.9, 11.2}; W. MANCAO 2024 41 Lesson 7.2: Array Initialization  When Initializers are Fewer than Array Elements  length = 7.8  length = 6.4  length = 4.9  length = 11.2  length, length, and length will be initialized to 0. W. MANCAO 2024 42 Lesson 7.2: Array Initialization  Omitting Array Size with Initializers  The compiler will automatically determine the size based on the number of initializers provided.  E.g., int gallons[] = {16, 12, 10, 14, 11};  The compiler will infer that gallons is an array of size 5, since there are 5 elements in the initializer list. W. MANCAO 2024 43 Lesson 7.2: Array Initialization  Omitting Array Size with Initializers  E.g. 2, char codes = {'s', 'a', 'm', 'p', 'l', 'e’}; char codes[] = {'s', 'a', 'm', 'p', 'l', 'e’};  Both declarations are equivalent. In both cases, the array codes has 6 elements because the initializer list has 6 values. W. MANCAO 2024 44 Lesson 7.2: Array Initialization  Simplification for Initializing Character Arrays  When initializing a character array with a string literal, you can omit the braces and commas.  The string literal automatically initializes the array, with each character in the string assigned to consecutive array elements.  A null terminator ('\0') is automatically added at the end of the string to mark its end. W. MANCAO 2024 45 Lesson 7.2: Array Initialization  Simplification for Initializing Character Arrays  E.g., char codes[] = "sample";  // Equivalent to {'s', 'a', 'm', 'p', 'l', 'e', '\0'} W. MANCAO 2024 46 Lesson 7.2: Array Initialization W. MANCAO 2024 47 Lesson 7.3: Arrays as Function Arguments W. MANCAO 2024 48 Lesson 7.3: Arrays as Function Arguments  Passing Individual Array Elements (by value)  When you pass individual array elements to a function, you pass the value of those specific elements.  The function receives a copy of the element, meaning any changes made to the element inside the function do not affect the original array. W. MANCAO 2024 49 Lesson 7.3: Arrays as Function Arguments  Passing Individual Array Elements (by value)  E.g., findMin(grades, grades);  Here, grades and grades are passed by value, so the function findMin() works with copies of these elements, not the original values in the grades array. W. MANCAO 2024 50 Lesson 7.3: Arrays as Function Arguments  Passing the Entire Array (by reference)  When you pass the entire array to a function, you pass a reference to the actual array (not a copy).  The called function receives access to the original array, meaning any modifications made to the array elements inside the function will affect the array outside the function. W. MANCAO 2024 51 Lesson 7.3: Arrays as Function Arguments  Passing the Entire Array (by reference)  E.g., findMax(grades);  Here, the entire grades[] array is passed by reference, allowing the function findMax() to modify the array elements directly.  NOTE: Passing a complete array to a function is in many respects an easier operation than passing individual elements. W. MANCAO 2024 52 Lesson 7.3: Arrays as Function Arguments  Passing the Entire Array (by reference)  For large arrays, making duplicate copies of the array for each function call would waste computer storage, consume execution time, and frustrate the effort to return multiple element changes made by the called program. W. MANCAO 2024 53 Lesson 7.3: Arrays as Function Arguments Size can be omitted: It is generally advisable to omit the size of the array in the function header line. W. MANCAO 2024 54 Lesson 7.3: Arrays as Function Arguments W. MANCAO 2024 55 Lesson 7.3: Arrays as Function Arguments W. MANCAO 2024 56 Lesson 7.3: Arrays as Function Arguments W. MANCAO 2024 57 Lesson 7.4: Two-Dimensional Arrays W. MANCAO 2024 58 Lesson 7.4: Two-Dimensional Arrays  Aka. table - consists of both rows and columns of elements.  E.g., int val; W. MANCAO 2024 59 Lesson 7.4: Two-Dimensional Arrays  Initialization - done in row order #define NUMROWS 3 #define NUMCOLS 4 int val[NUMROWS][NUMCOLS] = { {8,16,9,52}, {3,15,27,6}, {14,25,2,10} };  The inner braces can be omitted int val[NUMROWS][NUMCOLS] = {8, 16, 9, 52, 3, 15, 27, 6, 14, 25, 2, 10}; W. MANCAO 2024 60 Lesson 7.4: Two-Dimensional Arrays  Initialization - done in row order W. MANCAO 2024 61 Lesson 7.4: Two- Dimensional Arrays W. MANCAO 2024 62 Lesson 7.4: Two-Dimensional Arrays  first display - of the val[] array produced by Program 8.7 is constructed by explicitly designating each array element.  second display - identical to the first, but is produced using a nested for loop.  Nested loops - useful when dealing with two-dimensional arrays because they allow the programmer to easily designate and cycle through each element. W. MANCAO 2024 63 Lesson 7.4: Two-Dimensional Arrays  The display produced by Program 8.7 is: Display of val array by explicit element 8 16 9 52 3 15 27 6 14 25 2 10 Display of val array using a nested for loop 8 16 9 52 3 15 27 6 14 25 2 10 W. MANCAO 2024 64 Lesson 7.4: Two- Dimensional Arrays The nested for loop in Program 8.8 is used to multiply each element in the val array by the scalar number W. MANCAO 2024 65 10 and display the resulting value. Lesson 7.4: Two-Dimensional Arrays  Passing Two-Dimensional Arrays to Functions  The process is similar to passing one-dimensional arrays.  When a 2D array is passed, the function receives access to the entire array—not a copy.  Any modifications made to the array inside the function directly affect the original array. W. MANCAO 2024 66 Lesson 7.4: Two- Dimensional Arrays Row size can be omitted W. MANCAO 2024 67 Lesson 7.4: Two- Dimensional Arrays W. MANCAO 2024 68 ASSIGNMENT 4  DIRECTIONS: Via VSUEE, Answer each question in 3-5 sentences (10 pts).  1. Aside from the examples given in this lecture, what is another practical use for a one-dimensional array? Why do you think so?  2. For a two-dimensional array? Why?  WARNING: Exact "copy-paste" answers from classmates (plagiarism) or the internet (ChatGPT) will get an automatic zero. Make sure to paraphrase your answers.  DEADLINE: Nov. 26 (Tue) @ 1 PM W. MANCAO 2024 69 References  Bronson, G. (2008). A First Book of ANSI C (4th ed.). Thomson Course Technology. Pages 373-440.  Harrison, Lesley. (2016). A First Book of ANSI C Fourth Edition - Chapter 8. Slide Player. https://slideplayer.com/slide/8276886/  Page, Buddy. (2015). A First Book of ANSI C Fourth Edition - Chapter 8. Slide Player. https://slideplayer.com/slide/7498860/ W. MANCAO 2024 70

Use Quizgecko on...
Browser
Browser