In: Computer Science
Indexing Arrays & Scalar Operations
Create a new array called “myShortArray” that contains the 1st, 3rd, and 5th elements of the array “myArray” as defined below using the indexing method.
myArray = [1, 2, 3, 4, 5, 6];
#include<iostream>
using namespace std;
int main()
{
//DECLARE THE ARRAYS
int
myShortArray[3],myArray[6]={1,2,3,4,5,6};
int i,j;
//loop to scan each element of myArray
for(i=0,j=0;i<6;i++)
{
if(i%2==0) //check the odd position
elements. Since array atarts with 0 index so the index with even
number will be the odd position element
//if you need to store the odd
index element then the condition will be
//if(i%2!=0)
{
myShortArray[j]=myArray[i];//assign the myArray element to
myShortArray
j++;
}
}
//display the elements of myArray
cout<<endl<<"Elements of myArray :
";
for(i=0;i<6;i++)
cout<<" "<<myArray[i];
//display the elements of myShortArray
cout<<endl<<"Elements of myShortArray :
";
for(i=0;i<3;i++)
cout<<" "<<myShortArray[i];
}
output