Write a C++ program that declares an array alpha of 50 components of type double. Initialize the array so that the first 25 components are equal to the square of the index variable, and the last 25 components are equal to three times the index variable. Output the array so that 10 elements per line are printed.

Respuesta :

Answer:

The c++ program is as per the given scenario.  

#include <iostream>  

using namespace std;  

int main() {  

int len = 50;  

double alpha[len];  

int j;  

for(j=0;j<len; j++)  

{  

// first 25 elements are square of their index value  

if(j<len/2)  

alpha[j]=j*j;  

// last 25 elements are cube of their index value  

if(j>=len/2 && j<len)  

alpha[j]=j*j*j;  

}  

cout<<"The elements of the array are"<<endl;  

for(j=0; j<len; j++)  

{  

// after 10 elements are displayed, new line is inserted  

if(j==10 || j==20 || j==30 || j==40)  

cout<<endl;  

cout<<alpha[j]<<"\t";  

}  

}  

OUTPUT  

The elements of the array are  

0 1 4 9 16 25 36 49 64 81  

100 121 144 169 196 225 256 289 324 361  

400 441 484 529 576 15625 17576 19683 21952 24389  

27000 29791 32768 35937 39304 42875 46656 50653 54872 59319  

64000 68921 74088 79507 85184 91125 97336 103823 110592 117649  

Explanation:

This program declares an array of double data type of size 50. The size of array 50 is assigned to an integer variable, len.  

int len = 50;  

double alpha[len];  

The variable len holds value 50; hence, len/2 will have value 25.  

The first half of the elements are initialized to square of their index value. The second half of the elements are initialized to cube of their index values.  

This is done using a for loop as shown. The variable j used in the for loop is declared outside the loop.  

int j;  

for(j=0;j<len; j++)  

{  

// first 25 elements are square of their index value  

if(j<len/2)  

alpha[j]=j*j;  

// last 25 elements are cube of their index value  

if(j>=len/2 && j<len)  

alpha[j]=j*j*j;  

}  

After initialization is done, the elements of the array are displayed, 10 elements in one line.

This is achieved by the following.

for(j=0; j<len; j++)

   {

       // after 10 elements are displayed, new line is inserted

       if(j==10 || j==20 || j==30 || j==40)

           cout<<endl;            

       cout<<alpha[j]<<"\t";

   }