1 / 9

13/4/1435 h

13/4/1435 h. Lecture 2 Accessing Array’s Elements. Named Constants. Q: Mention the benefits of named constants when used as an array size declarator, give an example? This eases program maintenance when the size of the array needs to be changed .

Download Presentation

13/4/1435 h

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. 13/4/1435 h Lecture 2 Accessing Array’s Elements

  2. Named Constants • Q: Mention the benefits of named constants when used as an array size declarator, give an example? • This eases program maintenance when the size of the array needs to be changed. • Ex: const int SIZE = 5; int tests[SIZE];

  3. Q: Define array’s subscripts? • Each element in an array is assigned a unique subscript. • Subscripts start at 0 • The last element’s subscript is n-1 where n is the number of elements in the array. subscripts:

  4. Q: How can we access array’s elements ? By using : • A constant or literal subscript: EX : • Integer expression as subscript: EX cout << tests[3] << endl; • int i = 5; • cout << tests[i] << endl;

  5. Q : Write a general Format for accessing array’s Elements cout<< or cin >> Array Name [Array Subscript]; OR Array Name [integer Number];

  6. Q: Write a c++ program that asks for the number of hours worked by 6 employee and stores the values in an array #include<iostream> using namespace std; int main( ) { const int num_emp = 6; int hours[num_emp]; cout<<“enter the hours worked by 6 employees”;

  7. . // Get the hours worked by each employee cin>>hours[0]; cin>>hours[1]; cin>>hours[2]; cin>>hours[3]; cin>>hours[4]; cin>>hours[5]; //Display the values in the array Cout<<“the values you entered are:”

  8. . cout<< “ “ <<hours[0]; cout<< “ “ <<hours[1]; cout<< “ “ <<hours[2]; cout<< “ “ <<hours[3]; cout<< “ “ <<hours[4]; cout<< “ “ <<hours[5]<<endl; return 0; }

  9. Program output with example of input Here are the contents of the hours array, with the values entered by the user in the example output:

More Related