Array sheet
A)Write a program to print the contents of an integer array with the
string ", " between elements (but not after the last element).
Answer
#include <iostream>
using namespace std;
#include <cstdlib>
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
int length = sizeof(arr) / sizeof(int);
for (int i = 0; i < length; i++)
{
cout << arr[i];
if (i < length-1)
{
cout << ", ";
}
}
}
Or
#include <iostream>
using namespace std;
#include <cstdlib>
int main()
{
int length;
int* arr;
cout << "plz enter the length of the array: ";
cin >> length;
arr = new int[length];
for (int i = 0; i < length; i++)
{
cout << "plz enter in the array the element No " << i << ": ";
cin >> arr[i];
}
for (int i = 0; i < length; i++)
{
cout << arr[i];
if (i < length - 1) {
cout << ", ";
}
}
B) Assume the existence of two constants WIDTH and LENGTH.
Write a program that should transpose the WIDTH × LENGTH
matrix, into a matrix which is LENGTH × WIDTH (i.e.,
transposing the matrix.
int arr1[3][5];
int transpose[5][3];
cout << "plz enter the matrix: ";
for (int i = 0; i < 3; i++)
{
cout << "enter the 5 elements for row no " << i << " : \n";
for (int j = 0; j < 5; j++)
{
cout << "element in the column no " << j << " : \n";
cin >> arr1[i][j];
}
}
cout << "\nthe matrix is:\n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 5; j++)
{
cout << arr1[i][j]<< "\t";
}
cout << "\n";
}
cout << "\nthe transpose matrix is:\n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 5; j++)
{
transpose[j][i] = arr1[i][j];
}
}
cout << "\nthe transpose matrix is:\n";
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
cout << transpose[i][j] << "\t";
}
cout << "\n";
}