Download presentation
Presentation is loading. Please wait.
1
1 Lab Session-IX CSIT121 Fall 2000 w Arrays and Their Usage w Examples and Lab Exercises w Passing Arrays to Functions w Examples and Exercises w Sorting an Array
2
2 Arrays and Their Usage w Arrays consist of several data items that are of same data type and related to each other. w An array associates one name to a group of related data items that belong to the same data type w Example w const int ARRSIZE=5; w int students[ARRSIZE]={0}; w cin>>student_index; w if (student_index <ARRSIZE) w cout <<students[student_index]<<endl;
3
3 Arrays and Their Usage w One serious problem in array handling is the unintentional indexing outside bounds of an array w For example w students[ARRSIZE+2] = 32; w This problem may corrupt memory cells outside the array boundary
4
4 Lab Exercise 9-1 w Let us work on making a histogram of performance for some students in a class. w int grades[ARRSIZE]={7,14,13,13,11,7,7,8,8,13,13,14,14,7,14,8,14,11}; w int frequency[5]; w (We have only 5 different scores reported) w Record frequencies w Plot histogram using # sign
5
5 Passing Arrays to Functions w Arrays are passed to functions as reference arguments w Functions can modify arrays if programmer does not protect the arrays w The way to protect is to add const keyword before the array name in declaration and definition of the function
6
6 Passing Arrays to Functions w As an example, consider multiplying all the elements of an array with a value and storing the results in another array. w We would like to protect the original array when we call this function w int original[5]={4,7,12,31,24}; w int multiplied[5]={0};
7
7 Lab Exercise 9-2 w Define a function that takes in two arrays of the same size and stores the reverse of the first array into the second array. w Protect the first array with const identifier w Check if protection works by trying to violate it w Complete the program by storing the original and reversed array into a file
8
8 Sorting an Array w Let us try to sort an array in ascending order w The basic algorithm is as follows: w Find the smallest value in the array w Bring this value to index [0] w Find the smallest value in the remaining array w Bring this value to index [1]
9
9 Sorting an Array w Continue doing it until the remaining array consists of only one element w Try implementing the algorithm w Lab Exercise 9-3 w Test sorting with a test case as below: w Scores[10] ={9,7,8,4,7,2,4,1,7,5};
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.