C++程序设计课件:Chapter12 Arrays

上传人:努力****83 文档编号:187469593 上传时间:2023-02-14 格式:PPT 页数:89 大小:456KB
收藏 版权申诉 举报 下载
C++程序设计课件:Chapter12 Arrays_第1页
第1页 / 共89页
C++程序设计课件:Chapter12 Arrays_第2页
第2页 / 共89页
C++程序设计课件:Chapter12 Arrays_第3页
第3页 / 共89页
资源描述:

《C++程序设计课件:Chapter12 Arrays》由会员分享,可在线阅读,更多相关《C++程序设计课件:Chapter12 Arrays(89页珍藏版)》请在装配图网上搜索。

1、2/14/2023C+程序设计 教师:1Chapter 12.Arrays2/14/2023C+程序设计 教师:2C+Data Typesstructuredarray struct union class addresspointer referencesimple integral enumchar short int long boolfloatingfloat double long double3Declare variables to store and total 3 blood pressures int bp1,bp2,bp3;int total;400240004004bp

2、2bp1bp3cin bp1 bp2 bp3;total=bp1+bp2+bp3;4What if you wanted to store and total 1000 blood pressures?int bp 1000 ;/declares an array of 1000 int valuesbp0 bp1 bp2 .bp9995000 5002 5004 5006 .5One-Dimensional Array Definition P461An array is a structured collection of components(called array elements)

3、,all of the same data type,given a single name,and stored in adjacent memory locations.The individual components are accessed by using the array name together with an integral valued index in square brackets.The index indicates the position of the component within the collection.6Another ExamplenDec

4、lare an array called temps which will hold up to 5 individual float values.float temps5;/declaration allocates memorytemps0 temps1 temps2 temps3 temps4 7000 7004 7008 7012 7016 number of elements in the arrayindexes or subscriptsBase Address7Declaration of an Arraynthe index is also called the subsc

5、ript nin C+,the first array element always has subscript 0.The second array element has subscript 1,etc.nthe base address of an array is its beginning address in memory SYNTAX DataType ArrayName ConstIntExpression;8Yet Another ExamplenDeclare an array called name which will hold up to 10 individual

6、char values.char name10;/declaration allocates memory number of elements in the arrayname0 name1 name2 name3 name4 .name9 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009Base Address9Assigning Values to Individual Array Elementsfloat temps 5 ;/allocates memory for arrayint m=4;temps 2 =98.6;temps 3

7、 =101.2;temps 0 =99.4;temps m =temps 3 /2.0;temps 1 =temps 3 -1.2;/what value is assigned?temps0 temps1 temps2 temps3 temps4 7000 7004 7008 7012 7016 99.4?98.6 101.2 50.610What values are assigned?float temps 5 ;/allocates memory for arrayint m;for(m=0;m=0;m-)cout temps m endl;temps0 temps1 temps2 t

8、emps3 temps4 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8 12Variable Subscriptsfloat temps 5 ;/allocates memory for arrayint m=3;.What is temps m+1?What is temps m +1?temps0 temps1 temps2 temps3 temps4 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8 13A Closer Look at the Compilerfl

9、oat temps5;/this declaration allocates memoryTo the compiler,the value of the identifier temps alone is the base address of the array.We say temps is a pointer(because its value is an address).It“points”to a memory location.temps0 temps1 temps2 temps3 temps4 7000 7004 7008 7012 7016 100.0 100.2 100.

10、4 100.6 100.814Initializing in a Declaration P464int ages 5 =40,13,20,19,36 ;for (int m=0;m 5;m+)cout ages m ;ages0 ages1 ages2 ages3 ages4 6000 6002 6004 6006 6008 40 13 20 19 36 15Passing Arrays as Argumentsnin C+,arrays are always passed by reference nwhenever an array is passed as an argument,it

11、s base address is sent to the called function 16In C+,No Aggregate Array Operations P469nthe only thing you can do with an entire array as a whole(aggregate)with any type of component elements is to pass it as an argument to a function nEXCEPTION:aggregate I/O is permitted for C strings(special kind

12、s of char arrays)nchar str=“hello”;ncoutstr;17Using Arrays as Arguments to Functions Generally,functions that work with arrays require 2 items of information as arguments:nthe beginning memory address of the array(base address)nthe number of elements to process in the array 18#include#include void O

13、btain(int ,int);/prototypes here void FindWarmest(const int,int,int&);void FindAverage (const int,int,int&);void Print(const int ,int);using namespace std;int main()int temp31;/array to hold up to 31 temperatures int numDays;int average;int hottest;int m;Example with Array Parameters19 cout numDays;

14、Obtain(temp,numDays);/call passes value of numDays and /address of array temp to function cout numDays “temperatures“endl;Print(temp,numDays);FindAverage(temp,numDays,average);FindWarmest(temp,numDays,hottest);cout endl “Average was:“average endl;cout “Highest was:“hottest 0/Postcondition:/temp 0.nu

15、mber-1 are assigned int m;for(m=0;m number;m+)cout temp m;21void Print(/*in*/const int temp ,/*in*/int number )/Prints number temperature values to screen/Precondition:/number is assigned&number 0/temp 0.number-1 are assigned/Postcondition:/temp 0.number-1 have been printed 5 to a line int m;cout “Y

16、ou entered:“;for(m=0;m number;m+)if (m%5=0)cout endl;cout setw(7)0/temp 0.number-1 are assigned/Postcondition:/avg=arithmetic average of temp0.number-1 int m;int total=0;for(m=0;m 0/temp 0.number-1 are assigned/Postcondition:/largest=largest value in temp0.number-1 int m;largest=temp0;/initialize la

17、rgest to first element /then compare with other elements for(m=0;m largest)largest =tempm;26Using arrays for CountersnWrite a program to count the number of each alphabet letter in a text file.letterASCII A 65 B 66 C 67 D 68 .Z 90 This is my text file.It contains many things!5+8 is not 14.Is it?A:my

18、.dat27 const int SIZE=91;int freqCountSIZE;freqCount 0 0freqCount 1 0 .freqCount 65 2freqCount 66 0 .freqCount 89 1freqCount 90 0 unused counts A and acounts B and b .counts Y and ycounts Z and z28Main Module Pseudocode Level 0Open dataFile(and verify success)Zero out freqCountRead ch from dataFileW

19、HILE NOT EOF on dataFileIf ch is alphabetic characterIf ch is lowercase alphabeticChange ch to uppercaseIncrement freqCountch by 1Read ch from dataFilePrint characters and frequencies29/Program counts frequency of each alphabetic character in text file.#include#include#include const int SIZE 91;void

20、 PrintOccurrences(const int );/prototype using namespace std;Counting Frequency of Alphabetic Characters30int main()ifstream dataFile;int freqCount SIZE ;char ch;char index;dataFile.open(“A:my.dat”);/open and verify success if (!dataFile)cout “CANT OPEN INPUT FILE!“endl;return 1;for(int m=0;m SIZE;m

21、+)/zero out the array freqCount m =0;31 /read file one character at a time dataFile.get(ch);/priming read while(dataFile)/while last read was successful if(isalpha(ch)if(islower(ch)ch =toupper(ch);freqCount ch =freqCount ch +1;dataFile.get(ch);/get next character PrintOccurrences(freqCount);return 0

22、;32 void PrintOccurrences(/*in*/const int freqCount )/Prints each alphabet character and its frequency/Precondition:/freqCount A.Z are assigned/Postcondition:/freqCount A.Z have been printedchar index;cout “File contained“endl;cout “LETTER OCCURRENCES”endl;for (index=A ;index =Z;index+)cout setw(4)i

23、ndex setw(10)freqCount index endl;33More about Array Indexnarray index can be any integral type.This includes char and enum types nit is programmers responsibility to make sure that an array index does not go out of bounds.The index must be within the range 0 through the declared array size minus on

24、e nusing an index value outside this range causes the program to access memory locations outside the array.The index value determines which memory location is used 34Array with enum Index TypeDECLARATIONenum Department WOMENS,MENS,CHILDRENS,LINENS,HOUSEWARES,ELECTRONICS;float salesAmt 6 ;Department

25、which;USEfor (which=WOMENS;which=ELECTRONICS;which=Department(which+1)cout salesAmt which endl;35 float salesAmt6;salesAmt WOMENS (i.e.salesAmt 0 )salesAmt MENS (i.e.salesAmt 1 )salesAmt CHILDRENS (i.e.salesAmt 2 )salesAmt LINENS (i.e.salesAmt 3 )salesAmt HOUSEWARES (i.e.salesAmt 4 )salesAmt ELECTRO

26、NICS (i.e.salesAmt 5 )36Parallel ArraysDEFINITIONParallel arrays are 2 or more arrays that have the same index range,and whose elements contain related information,possibly of different data types.EXAMPLE const int SIZE 50;int idNumber SIZE ;float hourlyWage SIZE ;parallel arrays37const int SIZE=50;

27、int idNumber SIZE ;/parallel arrays holdfloat hourlyWage SIZE ;/related information idNumber 0 4562 hourlyWage 0 9.68idNumber 1 1235 hourlyWage 1 45.75 idNumber 2 6278 hourlyWage 2 12.71 .idNumber 48 8754 hourlyWage 48 67.96idNumber 49 2460 hourlyWage 49 8.9738Array of Structures const int MAX_SIZE=

28、500;enum HealthType Poor,Fair,Good,Excellent ;struct AnimalType/declares struct data typelong id;string name;string genus;string species;string country;/8 struct members int age;float weight;HealthType health;AnimalType bronxZoo MAX_SIZE ;/declares array39 AnimalType bronxZooMAX_SIZE;bronxZoo 0 1 .4

29、98 499 bronxZoo 0.id 3456219 bronxZoo 0.name “camel”bronxZoo 0.genus “Camelus”bronxZoo 0.species “dromedarius”bronxZoo 0.country “India”bronxZoo 0.age 10 bronxZoo 0.weight 992.8bronxZoo 0.health Fair40AnimalType bronxZooMAX_SIZE;.id .name .genus .species .country.age.weight.healthbronxZoo 0 3456219“

30、camel”“Camelus”“dromedarius”“India”10 992.8 FairbronxZoo 1 bronxZoo 2 bronxZoo 3.bronxZoo498bronxZoo49941Find total weight of all elements of the bronxZoo arrayfloat total=0.0;for(j=0;j MAX_SIZE;j+)total +=bronxZoo j.weight;42Specification of TimeTypeclass TimeType/timetype.hpublic:/7 function membe

31、rsvoid Set(int hours,int minutes,int seconds);void Increment();void Write()const;Boolean Equal(TimeType otherTime)const;Boolean LessThan(TimeType otherTime)const;TimeType(int initHrs,int initMins,int initSecs);/constructor TimeType();/default constructorprivate:/3 data membersint hrs;int mins;int se

32、cs;43Array of Class Objects const int MAX_SIZE=50;/declare array of class objects TimeType trainSchedule MAX_SIZE ;The default constructor,if there is,is invoked for each element of the array.44Two-Dimensional Array P476 is a collection of components,all of the same type,structured in two dimensions

33、,(referred to as rows and columns).Individual components are accessed by a pair of indexes representing the components position in each dimension.DataType ArrayName ConstIntExpr ConstIntExpr.;SYNTAX FOR ARRAY DECLARATION450 1 2 3 4 5 6 7 8 9 10 1166 64 72 78 85 90 99 105 98 90 88 80row 2,col 7might

34、beArizonashigh forAugustEXAMPLE-To keep monthly high temperatures for all 50 states in one array.const int NUM_STATES =50;const int NUM_MONTHS =12;int stateHighs NUM_STATES NUM_MONTHS ;0 1 2.stateHighs 2 7.48 49 46Viewed another way.stateHighs 0 0 stateHighs 0 1 stateHighs 0 2 stateHighs 0 3 stateHi

35、ghs 0 4 stateHighs 0 5 stateHighs 0 6 stateHighs 0 7 stateHighs 0 8 stateHighs 0 9 stateHighs 0 10 stateHighs 0 11 stateHighs 1 0 stateHighs 1 1 stateHighs 1 2 stateHighs 1 3.To locate an element such asstateHighs 2 7 the compiler needs to know that there are 12 columnsin this two-dimensional array.

36、At what address will stateHighs 2 7 be found?Assume 2 bytes for type int.Base Address 800047Arrays as Parametersnjust as with a one-dimensional array,when a two-(or higher)dimensional array is passed as an argument,the base address of the callers array is sent to the function nthe size of all dimens

37、ions except the first must be included in the function heading and prototype p503nthe sizes of those dimensions in the functions parameter list must be exactly the same as declared for the callers array 48const int NUM_STATES =50;const int NUM_MONTHS =12;int stateHighs NUM_STATES NUM_MONTHS ;int sta

38、teAverages NUM_STATES ;0 62 1 85 2 .48 49 0 1 2 3 4 5 6 7 8 9 10 1143 42 50 55 60 78 80 85 81 72 63 4066 64 72 78 85 90 99 105 98 90 88 80 Write a function using the two-dimensional stateHighs array to fill a one-dimensional stateAverages arrayAlaska Arizona49void FindAverages(/*in*/const int stateH

39、ighs NUM_MONTHS,/*out*/int stateAverages )/PRE:stateHighs 0.NUM_STATES 0.NUM_MONTHS assigned/POST:stateAverages 0.NUM_STATES contains rounded average/high temperature for each state int state;int month;int total;for (state=0;state NUM_STATES;state+)total=0;for(month=0;month NUM_MONTHS;month+)total+=

40、stateHighs state month ;stateAverages state =int(total/12.0+0.5);FindAverages(stateHighs,stateAverages)50 Using typedef with Arrayshelps eliminate the chances of size mismatches between function arguments and parameters.P505 FOR EXAMPLE,typedef int StateHighsType NUM_STATES NUM_MONTHS ;typedef int S

41、tateAveragesType NUM_STATES ;void FindAverages(/*in*/const StateHighsType stateHighs,/*out*/StateAveragesType stateAverages ).51Declaring Multidimensional Arrays P489EXAMPLE OF THREE-DIMENSIONAL ARRAYconst NUM_DEPTS =5;/mens,womens,childrens,electronics,furnitureconst NUM_MONTHS =12;const NUM_STORES

42、 =3;/White Marsh,Owings Mills,Towsonint monthlySales NUM_DEPTS NUM_MONTHS NUM_STORES ;rows columns sheets OR USING TYPEDEFtypedef int MonthlySalesType NUM_DEPTS NUM_MONTHS NUM_STORES;MonthlySalesType monthlySales;2/14/2023C+程序设计 教师:52TRUE/FALSE In C+,the index type of a one-dimensional array can be

43、any integral or enumeration type.A)TrueB)False2/14/2023C+程序设计 教师:53TRUE/FALSEvTRUE2/14/2023C+程序设计 教师:54TRUE/FALSE An individual array component can be passed as an argument to a function.A)TrueB)False2/14/2023C+程序设计 教师:55TRUE/FALSEvTRUE2/14/2023C+程序设计 教师:56TRUE/FALSE The components of an array are a

44、ll of the same data type.A)TrueB)False2/14/2023C+程序设计 教师:57TRUE/FALSEvTRUE2/14/2023C+程序设计 教师:58TRUE/FALSE The size of an array is established at compile time rather than at execution time.A)TrueB)False2/14/2023C+程序设计 教师:59TRUE/FALSEvTRUE2/14/2023C+程序设计 教师:60TRUE/FALSE In C+,an array can be passed as

45、 an argument either by value or by reference.A)TrueB)False2/14/2023C+程序设计 教师:61TRUE/FALSEvFALSE2/14/2023C+程序设计 教师:62TRUE/FALSE Given the declaration int beta20;the expression beta3 accesses the third component of the array.A)TrueB)False2/14/2023C+程序设计 教师:63TRUE/FALSEvFALSE2/14/2023C+程序设计 教师:64TRUE/F

46、ALSE If the word const precedes the declaration of an array in a function heading,the function is prevented from modifying the array.A)TrueB)False2/14/2023C+程序设计 教师:65TRUE/FALSEvTRUE2/14/2023C+程序设计 教师:66TRUE/FALSE The array declared as int bowlingScore612;contains 72 int components.A)TrueB)False2/14

47、/2023C+程序设计 教师:67TRUE/FALSEvTRUE2/14/2023C+程序设计 教师:68TRUE/FALSE The statement int scaleFactor24=5,2,8,-2,6,0,1,7;is a valid statement for declaring and initializing the scaleFactor array.A)TrueB)False2/14/2023C+程序设计 教师:69TRUE/FALSEvTRUE2/14/2023C+程序设计 教师:70TRUE/FALSE If a program contains the declar

48、ation int salePrice100100;then the statement cout salePrice3;outputs all the values in row 3 of the array.A)TrueB)False2/14/2023C+程序设计 教师:71TRUE/FALSEvFALSE2/14/2023C+程序设计 教师:72TRUE/FALSE In the computers memory,C+stores two-dimensional arrays in row order.A)TrueB)False2/14/2023C+程序设计 教师:73TRUE/FALS

49、EvTRUE2/14/2023C+程序设计 教师:74TRUE/FALSE When you declare an N-dimensional array in a functions parameter list,you can omit the sizes of all but the last dimension.A)TrueB)False2/14/2023C+程序设计 教师:75TRUE/FALSEvFALSE2/14/2023C+程序设计 教师:76CHOICE Which of the following could be used to declare an array alph

50、a and initialize its components to 10,20,and 30?A)int alpha3=10,20,30;B)int alpha=10,20,30;C)int alpha3=10 20 30;D)a and b above E)a,b,and c above 2/14/2023C+程序设计 教师:77CHOICEvD2/14/2023C+程序设计 教师:78CHOICE Which of the following statements about passing C+arrays as arguments is false?A)It is impossibl

51、e to pass an array by value.B)When declaring an array in a functions parameter list,you do not attach an ampersand(&)to the name of the component type.C)When declaring a one-dimensional array in a functions parameter list,you must include its size within square brackets.D)At run time,the base addres

52、s of the argument is passed to the function.2/14/2023C+程序设计 教师:79CHOICEvC2/14/2023C+程序设计 教师:80CHOICE Given the program fragment char alpha200;char beta200;.Copy(alpha,beta);/Copy all components of beta into alphawhich of the following is the best function heading for the Copy function?A)void Copy(/*

53、out*/char arr1,/*in*/char arr2)B)void Copy(/*out*/const char arr1,/*in*/char arr2)C)void Copy(/*out*/char arr1,/*in*/const char arr2)D)void Copy(/*out*/const char arr1,/*in*/const char arr2)2/14/2023C+程序设计 教师:81CHOICEvC2/14/2023C+程序设计 教师:82CHOICE Given the declaration char table79;which of the follo

54、wing stores the character B into the fifth row and second column of the array?A)table41=B;B)table14=B;C)table52=B;D)table25=B;E)table5=B;2/14/2023C+程序设计 教师:83CHOICEvA2/14/2023C+程序设计 教师:84CHOICE Given the nested For loops for(i=0;i M;i+)for(j=0;j N;j+)cout arrij;what is the appropriate declaration fo

55、r arr?A)int arrMN;B)int arrNM;C)int arrM+N;D)int arrM+1N+1;E)int arrN+1M+1;2/14/2023C+程序设计 教师:85CHOICEvA2/14/2023C+程序设计 教师:86CHOICE Given the declarations float alpha550;float sum=0.0;which of the following computes the sum of the elements in row 2 of alpha?A)for(i=0;i 5;i+)sum=sum+alphai2;B)for(i=0;i 50;i+)sum=sum+alphai2;C)for(i=0;i 5;i+)sum=sum+alpha2i;D)for(i=0;i 50;i+)sum=sum+alpha2i;2/14/2023C+程序设计 教师:87CHOICEvD2/14/2023C+程序设计 教师:88上机课作业预习nChapter 12n34.Book P506 2,4,5,6n35.Book P510 4n36.用筛法求100以内的素数。n37.将一个数组中的元素值按逆序重新存放。n38.求一个33矩阵对角线元素之和。2/14/2023C+程序设计 教师:89课后在线平台评测WWW.ECNUCPP.COM

展开阅读全文
温馨提示:
1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
2: 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
3.本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
关于我们 - 网站声明 - 网站地图 - 资源地图 - 友情链接 - 网站客服 - 联系我们

copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!