1 / 29

CHAPTER 7: Arrays (Numeric Arrays)

CHAPTER 7: Arrays (Numeric Arrays). CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon. Topics. Introduction to one-dimensional (1-D) numeric arrays Operations on arrays: Declaring arrays Initializing arrays Assigning values to array elements

ronli
Télécharger la présentation

CHAPTER 7: Arrays (Numeric Arrays)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CHAPTER 7: Arrays (Numeric Arrays) CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon BS (May 2012)

  2. Topics • Introduction to one-dimensional (1-D) numeric arrays • Operations on arrays: • Declaring arrays • Initializing arrays • Assigning values to array elements • Reading and displaying values of array elements • More about numeric arrays • Passing 1-D arrays to functions • Two-dimensional (2-D) arrays BS (May 2012)

  3. Topic 1 Introduction to arrays BS (May 2012)

  4. What is an Array? (Part 1) • An array is nothing more than a collection of similar data types such as integers, float and characters. • Programmer often uses a set of identical data that have the same type and are used for the exact same purpose. • For example, a programmer may wish to keep track of the training attendance for 5 working days. • Suppose below pattern is observed: BS (May 2012)

  5. What is an Array? (Part 2) • The attendance data serves a common purpose, so it is natural to group them together in a table. • When stored in a computer memory, it is best to store this data in adjacent (consecutive) memory cells as follows: • This kind of arrangement is called an array. • In C, an array has same name and stores data of the same data type. Mon Tue Wed Thu Fri 48 55 60 36 50 Address 430 432 434 436 438 BS (May 2012)

  6. Why Use an Array? • Based on the attendance data, we could easily sum up the attendance of 5 working days if we use five different variables and an expression as follows: • However, this solution is not at all elegant and is way too long for such a simple task. • On the other hand, the use of an array could provides a shorter and elegant solution as we will see next. intmon, tue, wed, thu, fri, sum; printf(“Enter the daily attendance:”); scanf(%d %d %d %d %d”, &mon, &tue, &wed, &thu, &fri); sum = mon + tue + wed + thu + fri; BS (May 2012)

  7. 1-D Array • An array is identified by its name, type, dimension and number of elements. • This is an example of a 1-D array declaration: • Because of this declaration: • The array size is static (fixed) throughout the program execution. • It is a one-dimension (1-D) array (because it has only one pair of [ ]). • The array can be conceptually visualised as: int day[5]; Type of each element of the array Array size (maximum no. of elements in the array). Array name Position: [0] [1] [2] [3] [4] or index number day By default begins with zero BS (May 2012)

  8. Topic 2 Operations on arrays BS (May 2012)

  9. Operations of Arrays • Before you could use an array, you must declare it. Then, you may want to assign initial values to the array elements. • Once declared you could assign values to the array elements. • Alternatively, you could also declare and assign initial values to the array elements in one declaration statement. • Once the elements of the arrays have been assigned with values, you could read and manipulate them (such as by printing them on the screen). • Working with arrays in C programs is best implemented with looping statements, in particular the for loop. BS (May 2012)

  10. Declaring Arrays • Array declaration is made by specifying: • data type of the array’s elements • array’s name • array’s size • General syntax: • Examples: • intmyarray[100]; • double bigval[5*200]; • int a[27], b[10], c[76]; data_typearray_name[size]; Declaring multiple arrays of the same data type #define SIZE 20 double test_score[SIZE]; int tax[SIZE+2]; Constant BS (May 2012)

  11. Initializing Arrays (1) • After an array is declared, it must be initialized. • 2 ways to initialize an array: compile-time and run-time • Compile-time, example: • int age[3] = {90, 21, 22}; num day 0 0 0 0 0 • int day[5] = {0}; [0] [1] [2] [3] [4] [0] [1] [2] 1 2 • int num[ ] = {1, 2, 3, 4}; 3 age 90 21 22 [0] [1] [2] Initialize as many elements as we want. The array size is not specified. BS (May 2012)

  12. Initializing Arrays (2) 2. Run-time, example: • Using for loop to initialize the array elements [0] [1] [2] [3] [4] salary ? ? ? ? ? int salary[5]; for (i = 0; i < 5; i++) salary[i] = 50; [0] [1] [2] [3] [4] salary 50 50 50 50 50 BS (May 2012)

  13. Assigning Values to Array Elements • You can: • Assign a value to a specific array element by using its position number or index number. Example: • Assign values to several array elements using the looping statement. Example: int day[5]; day[0] = 50; day[3] = day[0] + 2 day 50 52 [0] [1] [2] [3] [4] • int day[5], i=0; • while(i<=4){ • day[i] = 50; • i++; • } int day[5], i=0; for(i=0; i<=4;i++) day[i] = 50; BS (May 2012)

  14. Reading and Displaying Values • To read and display value from an array element, refer to the position number(or index). • For example: • Output: int house[4] = {3,2,6,4}; intnop; nop = house[2]; printf(“House 3 has %d people.”, nop); • printf(“House 1 has %d people.”, house[0]); house 3 2 6 4 [0] [1] [2] [3] House 3 has 6 people. House 1 has 3 people. BS (May 2012)

  15. Example #include <stdio.h> #define SIZE 4 void main(void) { int house[SIZE] = {3,2,6,4}; int index, total = 0; for (index = 0; index < SIZE; index++) { printf(“House %d: %d”, index+1, house[index]); total = total + house[index]; } printf("The total: %d", total); } house 3 2 6 4 [0] [1] [2] [3] House 1: 3 House 2: 2 House 3: 6 House 4: 4 The total: 15 BS (May 2012)

  16. More Example #include <stdio.h> void main(void) { int rain[5], i, sum=0; for (i=0; i<=4; i++) { printf(“Enter daily rain:”); scanf(“%d”, &rain[i]); } for (i=0; i<=4; i++) { printf(“Daily rain: %d”, rain[i]); sum = sum + rain[i]; } printf(“Total rain: %d”, sum); } BS (May 2012)

  17. Exercise • Write a program to report the total number of rainy days for every month in a year. Get the monthly rainy days from the user one by one and print the total on the screen. • In the first program, use twelve variables declared as follows: int Jan, Feb, Mac, Apr, May, Jun; int Sep, Oct, Nov, Dec; • In the second program, use an array of 12 elements as declared below: int Mon[12]; • Write a program to analyze the final exam marks for a class of 60 students. Ask the user to get the marks one by one. Then calculate and print on the screen the total and average marks of the students. BS (May 2012)

  18. Topic 3 More about arrays BS (May 2012)

  19. Passing Arrays to Functions • In C, passing an array to a function means that the function is granted direct access to all of the elements of that array, not a copy of the array. • When we want to pass an array to a function, we need to know these 3 things. • How to write the function prototype? • How to do function call? • How does the function definition header would look like? BS (May 2012)

  20. Example #include <stdio.h> void displayArray(ints[]); //function prototype void main(void) { intx[3]={9,7,6}; displayArray(x); // function call } void displayArray(ints[]) // function definition header { inti; for (i=0; i<3; i++) printf(“%d\n", s[i]); } Without array size 9 7 6 BS (May 2012)

  21. More Example Marks student 1: 66 Marks student 2: 77 Marks student 3: 88 Marks student 4: 99 Marks student 5: 100 Average for marks: 86.00 • #include <stdio.h> • #define SIZE 5 • void getMarks(float s[ ]); • float calcAverage(float sc[ ]); • void main(void) • { • float marks[SIZE] = {0.0}; //initializing the array • getMarks(marks); /* function call */ • printf("Average for marks: %.2f\n“, calcAverage(marks)); • } • void getMarks(float s[ ]) • { • inti; • for (i=0; i<SIZE; i++) • { • printf("Marks student %d:",i+1); • scanf("%f", &s[i]); • } • } • float calcAverage(float sc[ ]) • { • float total = 0.0; • inti; • for (i=0; i<SIZE; i++) • { • total = total + sc[i]; • } • return (total / size); • } BS (May 2012)

  22. Exercise • Write a program that declares an array of 30 elements named income in the main function. • Then call and pass the array to a programmer-defined function named getIncome. • Within the getIncome function, ask the user for annual income of 30 employees. Then, calculate and print the total income on the screen. • Use the following function prototype in the: void getIncome( ai[]); BS (May 2012)

  23. Topic 3-2 2-dimensional (2-d) arrays BS (May 2012)

  24. 2-D Arrays • It is possible to create an array which has more than one dimension. • In C, we can go up to 12-dimensional arrays. • 2-D arrays (because there are two pairs of [][]): • Declaration: • Example: Data_type array[row][column] intcarrymarks[4][2] Row Column BS (May 2012)

  25. 2-D: Conceptual View This 2D array has 4 rows and 2 columns. Row size Column size int m[4][2] = {10, 12, 33, 14, 25, 56, 77, 85}; Column m [0] [1] [0] [1] Row [2] [3] m[0][0] m[0][1] m[1][0] m[1][1] m[2][0] m[2][1] m[3][0] m[3][1] BS (May 2012)

  26. Initializing 2-D Arrays 2 ways to initialize an array: compile-time and run-time 1. Compile-time • Variable initialization can also be done this way: • This method is less confusing since we can see the rows and columns division more clearly. int m[4][2] = {{10,12},{33,14},{25,56},{77,85}}; BS (May 2012)

  27. Initializing 2-D Arrays 2. Run-time • Using nested for statements: • Although it is possible to create a multi-dimensional array, arrays above 2-dimensions are rarely used. for (row = 0; row < 4; row++) { for (column = 0; column < 2; column++) m[row][column] = 0; } BS (May 2012)

  28. Passing a 2-D Array to a Function • When a 2D (or higher dimensional) array is passed to a function, the size of the second (or subsequent) subscript needs to be specified. • For example, if we have: int m[4][5]; • Then the function header which would takem as an argument should be declared like this:void Process2D(int td[ ][5]) • An array is stored consecutively in memory regardless of the number of dimensions. Therefore, specifying the subscripts in the function parameter will help the compiler to know the boundary of the different dimensions. BS (May 2012)

  29. Summary • An array is a collection of data of the same type and are used for the exact same purpose. • The use of an array could provides a shorter and elegant solution. • Dimension of an array is determined by number of [ ] of the array declaration. • Operations of an array include: • Declaration – by specifying data type of array element, array name and array size. • Initialize and assign values to arrays elements at: compile-time and run-time • To read and display value from an array element, refer to the position number(or index). • Passing arrays to a function require you to deal with the function prototype, function call and function definition header . BS (May 2012)

More Related