Exercise 2 (Filename: ArrayExr2.cpp)
a) Create a new C++ program called ArrayProgram in your C++ folder
- declare and create an array newNumbers which can contain 12 int numbers
- assign these values into newNumbers
- 10, 6, 88, 91, 25, 77, 14, 23 ,4, 235, 66, 81.
- find and display the length of the array
- display the value stored in the 5th element of the array
- change the value in the 5th element to 35. Display again.
- calculate and display the average of the values stored in the array (use the length attribute)
Exercise 3 (Filename: ArrayExr3.cpp)
Extend your program ArrayProgram to
- declare and create an array to hold the module code IT211 as a list of char values. Draw the resulting array.
- Change the value in the last element to 2 and output the array contents.
Exercise 4 (Filename: ArrayExr4.cpp)
Create a new program to do the following:
a) declare an array numbers which will contain the following values:
5, 6, 17, 81, 43, 90, 66, 30, 76, 12
Decide yourself how you are going to initialise the array.
b) Using a for loop write the code to
- display all values in the array numbers
- increment all elements in the array by 1 and display the values again
- display last 5 values from the array numbers
c) We can find the sum of all numbers in an array by:
· declaring a variable to hold the sum
· initialising the variable to zero
· iterating through the array and adding each number in turn to the
· existing sum
The following code finds the sum of all integers in the array numbers:
int sum = 0;
for ( i =0; i
sum = sum + numbers[i];
i) Add the code to calculate the sum of all elements in the array numbers into your program and output the result.
ii) Add more Java statements to your code to calculate the average of the array numbers.Use the array attribute length in the calculation. Output all results.
Why is the calculation of the average 'inaccurate'?
e) Re-write the code so that the program reads the array values from the keyboard.
Exercise 5 (Filename: ArrayExr5.cpp)
A variable representing the array index is used as a loop variable to iterate through all elements in an array. The loop variable can also be used to assign values to the array elements.
- Declare an array of 20 int and fill it with numbers from 1 to 20 using the values of the loop variable
- Output the array values
- Output the values in reverse order
- Output the even numbers
- Output the odd numbers
0 Comments