I came upon this and I would love to know how this works Th
I came upon this and I would love to know how this works :-)
The majority of your development may take place in the function task2().
1. You need to implement code to output the following line to the screen:
–- Task 2 –-
2.Declare an int array named numbers and initialise it with the following values: 1 4 9 16 9 7 4 9 11 (2 marks)
3. Declare a second array of the same size and using a loop populate it with random numbers in the range of 1 – 25 inclusive.
4. Use a loop to compute the ‘total’ of the numbers based on the following rule: If the number being considered is odd then add this to the total, however if the number to be added is even then subtract this from the total. For example for the initialised array it would compute: 1 4 + 9 16 + 9 + 7 4 + 9 + 11 = 22
5. Print both of the arrays and the results of the ‘total’ operation. For example for the initialised array the output could resemble: [ 1, 4, 9, 16, 9, 7, 4, 9, 11 ] the total is RESULT Where RESULT is the calculated value from the ‘total’ operation. Notice that the lists should be comma space separated and that the final element in the list is not terminated with a comma but with a space followed by a square bracket. Also note that each line should begin with a left square bracket followed by a space.
Solution
// C++ code
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main ()
{
int array1[] = {1,4,9,16,9,7,4,9,11};
int size = sizeof(array1)/sizeof(array1[0]);
int array2[size];
for (int i = 0; i < size; ++i)
{
// random numbers in the range of 1 – 25 inclusive.aa
array2[i] = rand() % 25 + 1;
}
int total1 = 0;
int total2 = 0;
for (int i = 0; i < size; ++i)
{
if(array1[i]%2 == 0)
total1 = total1 - array1[i];
else
total1 = total1 + array1[i];
if(array2[i]%2 == 0)
total2 = total2 - array2[i];
else
total2 = total2 + array2[i];
}
cout << \"\ [ \";
for (int i = 0; i < size-1; ++i)
{
cout << array1[i] << \", \";
}
cout << array1[size-1] << \" ] the total is \" << total1 << endl;
cout << \"\ [ \";
for (int i = 0; i < size-1; ++i)
{
cout << array2[i] << \", \";
}
cout << array2[size-1] << \" ] the total is \" << total2 << endl;
return 0;
}
/*
output:
[ 1, 4, 9, 16, 9, 7, 4, 9, 11 ] the total is 22
[ 9, 12, 3, 16, 19, 11, 12, 18, 25 ] the total is 9
*/

