Array Basics: Christian Roi D. Elamparo Bscoe-2A

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

CHRISTIAN ROI D.

ELAMPARO
BSCOE-2A

Array Basics
1.) Write a program that displays an age of 19.
#include <iostream>
using namespace std;
int main()
{
short age;
age=19;
std::cout << age << std::endl;
return 0;
}

Output: 19
2.) Reverse number using array.
#include<iostream>
using namespace std;
int main()
{
int n,array [100],i;
cout<<Enter no. of digits in your number:;
cin>>n;

cout<<Enter Number:;
for(i=0;i<n;i++)
cin>>array[i]; //storing each no. in array
cout<<endl;

cout<<Reverse no. is :;
for(i=n-1;i>=0;i--)
cout<<array[i]; //printing array in reverse order
cout<<endl;
}

Output: Enter no. of digits in your number: 5


Enter Number: 1 2 3 4 5
Reverse no. is: 54321
3.) Reverse number (column) using array.
#include<iostream>
using namespace std;
int main()
{
int n,c,d,a[100],b[100];

cout<<"Enter the number of elements in array: ";


cin>>n;

cout<<"Enter the array elements:\n";

for(c=0;c<n;c++)
cin>>a[c];

//copying elements into array b starting from end of array a

for(c=n-1,d=0;c>=0;c--,d++)
b[d]=a[c];

//copying reversed array into original


//Here we are modifying original array, this is optional

for(c=0;c<n;c++)
a[c]=b[c];
cout<<"Reverse array is :\n";

for(c=0;c<n;c++)
cout<<a[c]<<"\n";
return 0;
}

Output: Enter the number of elements in array:5


Enter the array elements:
1
2
3
4
5
Reverse array is:
5
4
3
2
1

Multidimensional Arrays

4.) Displays the contents of rows by 3 array.


//test multi-dimensional array
#include<iostream>
using namespace std;
void printArray(const int[][3],int);

int main(){
int myArray[][3]={{8,2,4},{7,5,2}}; //2x3 initialized
//only the first index can be omitted and implied
printArray(myArray,2);
return 0;
}
//print the contents of rows-by-3 array (columns is fixed)
void printArray(const int array[][3],int rows){
for(int i=0; i<rows;++i){
for(int j=0;j<3;++j){
cout<<array[i][j]<<" ";
}
cout<<endl;
}
}

Output: 8 2 4
752

5.) Displays the contents of rows by 3 array.


//test multi-dimensional array
#include<iostream>
using namespace std;
void printArray(const int[][3],int);

int main(){
int myArray[][3]={{1,0,0},{2,0,0}}; //2x3 initialized
//only the first index can be omitted and implied
printArray(myArray,2);
return 0;
}
//print the contents of rows-by-3 array (columns is fixed)
void printArray(const int array[][3],int rows){
for(int i=0; i<rows;++i){
for(int j=0;j<3;++j){
cout<<array[i][j]<<" ";
}
cout<<endl;
}
}

Output: 1 0 0
200

You might also like