Write a program that reads 12 integers into a 2D integer array with 4 rows and 3 columns. The program then outputs the 2D array in reverse order according to both rows and columns.
Ex: If the input is:
5 7 3
6 4 3
5 6 9
5 2 8
then the output is:
8 2 5
9 6 5
3 4 6
3 7 5
For coding simplicity, output a space after every integer, including the last one on each row.
#include <iostream>
using namespace std;
int main() {
const int ROWS = 4;
const int COLS = 3;
int arr[ROWS][COLS];
int i, j;
for(i = 0; i < ROWS; i++){
for(j = 0; j < COLS; j++){
cin>>arr[i][j];
}
}
cout << arr[3][2] << " " << arr[3][1] << " " << arr[3][0] << " " << endl;
cout << arr[2][2] << " " << arr[2][1] << " " << arr[2][0] << " "<< endl;
cout << arr[1][2] << " " << arr[1][1] << " " << arr[1][0] << " "<< endl;
cout << arr[0][2] << " " << arr[0][1] << " " << arr[0][0] << " "<< endl;
return 0;
}
I ended up having to hardcode this question because I couldnt find a way to reverse the 2D array with a loop and get it to be outputted in the form of a graph. Is there a way i could reverse the 2D array using for loops and would it be possible to be able to change the amount of rows and columns and still output the corresponding graph of values?
try this:
#include <iostream>
using namespace std;
int main() {
const int ROWS = 4;
const int COLS = 3;
int arr[ROWS][COLS];
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
cin >> arr[i][j];
}
}
// output the reversed array
for (int i = ROWS - 1; i >= 0; i--) {
for (int j = COLS - 1; j >= 0; j--) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
You can reverse a 2D array using nested for loops, try
#include <iostream>
using namespace std;
int main() {
const int ROWS = 4;
const int COLS = 3;
int arr[ROWS][COLS];
int i, j;
// Input the values into the 2D array
for(i = 0; i < ROWS; i++) {
for(j = 0; j < COLS; j++) {
cin >> arr[i][j];
}
}
// Reverse the rows and columns of the 2D array
for(i = ROWS - 1; i >= 0; i--) {
for(j = COLS - 1; j >= 0; j--) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
As mentioned in comments below if you don't know ROWS and COLS size at compile time dynamically allocate the memory for 2D array(arr) in C++ using new operator.
There is very little point reading the data into a 2D array for this program. A std::vector would do the trick, sized with ROWS * COLS values. You then have the benefit of being able to read those dimensions from the user, which addresses the second part of your question.
size_t size = ROWS * COLS;
// Read data
std::vector<int> data;
data.reserve(size);
for (int value; std::cin >> value; )
{
data.push_back(value);
}
// Validate data
if (data.size() != size)
{
std::cerr << "Unexpected end of input!\n";
return EXIT_FAILURE;
}
When outputting, you can use a reverse iterator through the vector, and simply write a newline every COLS values.
// Output in reverse
int col = 0;
for (auto it = data.rbegin(); it != data.rend(); it++)
{
std::cout << *it << " ";
if (++col == COLS)
{
std::cout << "\n";
col = 0;
}
}
You can even easily fix the "space at the end of the line" problem by adjusting your output loop as follows:
// Output in reverse
int col = 0;
for (auto it = data.rbegin(); it != data.rend(); it++)
{
std::cout << *it;
if (++col == COLS)
{
std::cout << "\n";
col = 0;
}
else
{
std::cout << " ";
}
}
I have created a 2d array, so lets say as I did in the code below the array elements shows like this:
3 4
8 2
I want to compare the" ROWS" and get the minimum number, like what I do with 3 & 4, I get 3 is the min number and with the second row between 8 & 2, I get 2 is the min number.
My problem is that I can't get it to compare the columns as in 3 & 8 to get the max out between them, and 4 & 2.
In the code it just outputs the max number in the rows it still comparing the "ROWS"
P.S sorry for the long explanation. I just had to clarify it .
int main()
{
int d;
int max;
//array dimention
cout << "Enter the array dimention :- " << endl;
cin >> d;
//max_min for the final maximum numbers
int max_num[d];
//the 2d array
int arr[d][d];
// array input
cout << "please enter the array elements :- " << endl;
for (int i = 0; i < d; i++) {
for (int j = 0; j < d; j++) {
cin >> arr[i][j];
}
}
//array output
cout << "the array elements you enterd :-" << endl;
for (int i = 0; i < d; i++) {
for (int j = 0; j < d; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
//the max numbers
for (int i = 0; i < d; i++) {
max = arr[0][i];
for (int j = 0; j < d; j++) {
if (max < arr[j][i]) {
max = arr[j][i];
}
}
max_num[i] = max;
}
cout << "the maximum elements in array :-" << endl;
for (int i = 0; i < d; i++) {
cout << max_num[i] << endl;
}
}
Lets suppose we have a 5 X 5 random array
1 2 3 7 8
4 7 3 6 5
2 9 8 4 2
2 9 5 4 7
3 7 1 9 8
Now I want to print the right side of the diagonal shown above, along with the elements in the diagonal, like
----------8
--------6 5
------8 4 2
---9 5 4 7
3 7 1 9 8
The code I've written is
#include <iostream>
#include <time.h>
using namespace std;
int main(){
int rows, columns;
cout << "Enter rows: ";
cin >> rows;
cout << "Enter colums: ";
cin >> columns;
int **array = new int *[rows]; // generating a random array
for(int i = 0; i < rows; i++)
array[i] = new int[columns];
srand((unsigned int)time(NULL)); // random values to array
for(int i = 0; i < rows; i++){ // loop for generating a random array
for(int j = 0; j < columns; j++){
array[i][j] = rand() % 10; // range of randoms
cout << array[i][j] << " ";
}
cout << "\n";
}
cout << "For finding Max: " << endl;
for(int i = 0; i < rows; i++){//loop for the elements on the left of
for(int j = columns; j > i; j--){//diagonal including the diagonal
cout << array[i][j] << " ";
}
cout << "\n";
}
cout << "For finding Min: " << endl;
for(int i = rows; i >= 0; i++){ //loop for the lower side of
for(int j = 0; j < i - columns; j++){ //the diagonal
cout << array[i][j] << " ";
}
cout << "\n";
}
return 0;
}
After running the code the shape I get is correct , but the elements do not correspond to the main array. I have no idea what the problem is.
Left side:
for (size_t i = 0; i < rows; i++) {
for(size_t j = 0; j < columns - i; j++) {
cout << array[i][j] << " ";
}
cout << "\n";
}
Right side:
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < columns; j++) {
if (j < columns - i - 1) cout << "- ";
else cout << vec[i][j] << " ";
}
cout << "\n";
}
So I have 2 arrays. Let's say the first one it's called a and the second one b. The first one uses "i" for it's elements and the second one uses "j".
For example we have a[ 1 2 3 4] and b[3 4 5] it should show c[1 2]. In the array c I want to show the elements that are in a and aren't in b.
This is what I've tried, but without succes:
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int a[50], b[50], c[50], i, j, k, n, m;
cout << "n= "; cin >> n;
//Read arrays
for (i = 0; i < n; i++) {
cout << "a[" << i << "]: "; cin >> a[i];
}
cout << "\nm= "; cin >> m;
for (j = 0; j < m; j++) {
cout << "b[" << j << "]: "; cin >> b[j];
}
//Show the arrays
cout << endl;
cout << "\na[ ";
for (i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << "]";
cout << endl;
cout << "\nb[ ";
for (j = 0; j < m; j++) {
cout << b[j] << " ";
}
cout << "]";
//Calculate the difference
k = 0; i = 0;
for (j = 0; j < m; j++) {
if (a[i] != b[j])
c[k] = a[i];
k++;
while (j == m && i < n)
i++;
}
//Show the difference array
cout << endl;
cout << "\nc[ ";
for (i = 0; i < k; i++) {
cout << c[i] << " ";
}
cout << "]";
return 0;
}
If the items are sorted, use std::set_difference:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
int a[] = { 1, 2, 3, 4 };
int b[] = { 3, 4, 5 };
std::vector<int> cv;
std::set_difference(std::begin(a), std::end(a),
std::begin(b), std::end(b),
std::back_inserter(cv));
for (auto& s : cv)
std::cout << s << "\n";
}
Output:
1
2
The advantage of using the STL algorithms is that the purpose of the code is known immediately just by looking at the name of the function, and that they work every time (if you give them the correct parameters). Note the lack of comments -- any competent C++ programmer understands right away what's being done.
On the other hand, if you didn't mention what your original code was trying to do (including removing the comments), it would take much more effort to figure out what it's supposed to be doing, and as you've seen, it contains bugs.
Your logic is wrong.
Explanation
So the thing that we will do
For each element in a we will have to check if it is there in array b or not.
If we see any element of a[i] in b[1..m] then we can't add it to c.
So in code we just mark it by f=1
When I get out of that second for loop I want to check if that a[i] is eqaul to any of the element in b[1..m] in which case f will be 1. But if it is 0 then add it to array c[].
Correct one
int k=0;
for(int i=0;i<n;i++)
{
int f=0;
for(int j=0;j<m;j++)
if(a[i]==b[j])
f=1;
if(!f)
c[k++]=a[i];
}
Where OP went wrong?
Being not equal to one element of b[] doesn't guarantee that the element is not appearing b[0..m-1] . This is where op went wrong.
In the for loop
for(j=0;j<m;j++) you are checking if particular a[i] is equal to b[j] or not. If that is the case then it is added to c[] . It is wrong. Also i is not incremented in the loop unless j==m and as in the for loop the condition is j<m so i is never incremented. And k is incremented every time so not every element in c is valid they may contain garbage value even after processing.
k = 0; i = 0;
for (j = 0; j < m; j++) {
if (a[i] != b[j]) // this doesn't mean that it is not appearing in `b`
c[k] = a[i];
k++; // k is incremented in every iteration which is wrong. It should be only when we are sure that `a[i]` is not in `b[0..m-1] `
while (j == m && i < n)
i++; // OP is not using it anywhere...this is redundant.
}
what op did?
Compared first element of a[0] with every element of b[0..m-1] and array c[] contains m elements irrespective of what a[] and b[] is, out of which
c[i]={ a[0] if b[j]==a[0]
{ garbage value if b[j] not equal to a[0]
Dry Run of OP's code
k = 0; i = 0;
for (j = 0; j < m; j++) {
if (a[i] != b[j])
c[k] = a[i];
k++;
while (j == m && i < n)
i++;
}
Input
Case: 1 2 3 4 :a[]
2 3 4 1 :b[]
Step 1: i=0 a[0]!=b[0] is true so c[0]=a[0]. the `while loop` not entered.
j++
Step-2: i is still 0. a[0]!=b[1] so it is added c[1]=a[0]. While loop not entered.
j++
Step-3: i is still 0. a[0]!=b[2]. So c[2]=a[0]. While loop skipped.
j++
Step-4: i is still 0. a[0]==b[3] is true so no assignment done. But k is incremented. so c[3]=garbage. j=3 so while loop skipped
j++
Out of for loop.
Output: [here x is garbage value]
a[]: 1 2 3 4
b[]: 2 3 4 1
c[]: 1 2 3 x
Example test case
1 2 3 4 :=a
2 3 4 1 :=b
Corrected Code
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int a[50], b[50], c[50], i, j, k, n, m;
cout << "n= "; cin >> n;
//Read arrays
for (i = 0; i < n; i++) {
cout << "a[" << i << "]: "; cin >> a[i];
}
cout << "\nm= "; cin >> m;
for (j = 0; j < m; j++) {
cout << "b[" << j << "]: "; cin >> b[j];
}
//Show the arrays
cout << endl;
cout << "\na[ ";
for (i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << "]";
cout << endl;
cout << "\nb[ ";
for (j = 0; j < m; j++) {
cout << b[j] << " ";
}
cout << "]";
//Calculate the difference
k = 0; i = 0;
int k=0;
for(int i=0;i<n;i++)
{
int f=0;
for(int j=0;j<m;j++)
{
if(a[i]==b[j])
f=1;
if(!f)
c[k++]=a[i];
}
}
//Show the difference array
cout << endl;
cout << "\nc[ ";
for (i = 0; i < k; i++) {
cout << c[i] << " ";
}
cout << "]";
return 0;
}
Your code seems to check if the elements in a are equal to all elements of b. If you just want to check the elements in a if they are equal to at least one element of b, you can do
for (int i=0; i<n; i++) {
bool found = false;
for (int j=0; j<m; j++) {
if (a[i] == b[j]) {
found = true;
break;
}
}
if (!found) {
std::cout << "a["<<i<<"] is not in b"<<std::endl;
}
}
Or add the element to c, but I would recommend to use std::vector<int> c for that.
In the array c I want to show the elements that are in a and aren't in b
It seems like you are looking for std::set_difference
int a[4] = {1, 2, 3, 4}, b[3] = {3, 4, 5};
int c[2] = {}; // declare c with enough space to hold all the elements in result
std::set_difference(a, a + 4, b, b + 3, c); // now c contains the element that are in a but not in b
You can do this very easily using 'set'.
#include<iostream>
#include<set>
int main(){
std::set<int> a = {1,2,3,4} , b = {3,4,5};
for(int const inB : b)
a.erase(inB);
for(int const inA : a)
std::cout << inA << " ";
std::cout << std::endl;
return 0;
}
Im supposed to display grades in a graph that shows how many grades are in each interval 0-10, 10-20, 20-30 etc. By putting a * for each grade in the interval. My only problem is that when the array grade[] has 1, 2, 3 or 5 slots it puts an extra * in the 0-10 interval. It works with every other ammount of slots.
void sort_grades(int grades[],int students)
cout << endl << endl;
cout << " THE GRADES GRAPH"<< endl;
cout << "=============================="<<endl;
const int max_grade = 100;
const int interval=10;
for (int j = 0; j < max_grade; j+=10)
{
cout << j << " - " << (j+interval) << " : ";
for (int k = 0; k <= students; k++)
{
if (j==90 && grades[k] ==(j+interval) )
{
cout<< "*";
}
else if (grades[k] < (j+interval) && grades[k] >= j)
{
cout<< "*";
}
}
cout << endl;
}
I assume that students is the size of the array grades[].
In this case, you access too many elements in the following loop:
for (int k = 0; k <= students; k++)
Instead the line should read:
for (int k = 0; k < students; k++)
This problem does not only occur for the cases where grade[] has a size of 1, 2, 3 or 5. You only see the problem for that sizes, because the output depends on the content of the array.