in c Assume that an array of integers named a that contains

in c++

Assume that an array of integers  named  a that contains exactly five elements has been declared and initialized .

Write a single statement that assigns a new value to the first  element of the array . This new value should be equal to twice the value  stored in the last  element of the array .

Do not modify any values in the array other than the first element .

Solution

Here is the answer:

a[0] = 2 * a[(sizeof(a)/sizeof(*a)) - 1];

Here is sample code to test:

#include <iostream>
#include <array>
using namespace std;

int main()
{
int a[] = {10, 2, 3, 17, 50};
for(int i=0;i<(sizeof(a)/sizeof(*a));i++)
cout << a[i] << \" \";
a[0] = 2 * a[(sizeof(a)/sizeof(*a)) - 1];
cout << \"\ after changing\ \";
for(int i=0;i<(sizeof(a)/sizeof(*a));i++)
cout << a[i] << \" \";
cout << endl;
return 0;
}

Output:

10 2 3 17 50                                                                                                  

after changing                                                                                                

100 2 3 17 50

in c++ Assume that an array of integers named a that contains exactly five elements has been declared and initialized . Write a single statement that assigns a

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site