2D Array and File Handling [C++] - c++

Background:
I'm attempting to read through a 2d array and find values that coincide with row numbers and column numbers.
Question:
How do I read values off a file and acquire, for example, 1 and 4 vs. 14?
Here's what I have so far...
All constructive criticism is welcome.
int arrayOfNum[5][5] = {
{34,21,32,41,25},
{14,42,43,14,31},
{54,45,52,42,23},
{33,15,51,31,35},
{21,52,33,13,23}};
ofstream arrayFile;
arrayFile.open("arrays.txt");
if (arrayFile.is_open()) {
cout << "File opened successfully..." << endl;
}
for (int i = 0; i <= 4; i++) {
arrayFile << endl;
for (int j = 0; j <= 4; j++) {
arrayFile << arrayOfNum[j][i] << ' ';
}
}

You are writing rows in columns as you wrote "arrayOfNum[j][i]", but I'm writing the code for correct direction. You can change the condition in following code but it's working perfect if you write "arrayOfNum[i][j]" while outputting in 'array.txt'
ifstream arrayFile;
arrayFile.open("arrays.txt");
for (int i = 0; i <= 4; i++)
{
for (int j = 0; j <= 4; j++)
{
arrayFile >> arrayOfNum[i][j];
cout<<arrayOfNum[i][j]<<" ";
if(i+1 == arrayOfNum[i][j] / 10 && j+1 == arrayOfNum[i][j] % 10)
{
cout<<"\n Matched: "<<arrayOfNum[i][j]<<endl;
}
}
cout<<endl;
}
And yes it will work for only 2 digit numbers, if you want for N digit numbers then I can do it for you too! :)

Related

Checking how many times a number has been entered

I'm trying to solve one of the questions on a task sheet I've received, to help me further in my understanding of C++ code from my class.
It kept showing 100000 in output after I entered the values. Where is that 1 coming from?
I know there are better ways to write code for this but I just want to know were is my problem.
The question is
(and I quote):
Write a program that:
Asks the user to enter 10 numbers between 1 and 5 into an array and displays the array on screen.
Creates a second array of size 5 and fills it with zeros.
Counts how many 1s, 2s, , … 5s have been entered into the first array and stores this number in the second array.
Displays the second array as shown in the example below.
Code:
int A1[10];
int A2[5] = { 0,0,0,0,0 };
int count = 10;
for (int i = 0; i < count; i++)
{
here:
cout << endl << i + 1 << "- enter a number between 1 and 5 for value : ";
cin >> A1[i];
if (A1[i] < 1 || A1[i]>5)
{
cout << "eror! enter a number between 1 and 5!";
goto here;
}
}
for (int i = 0; i < 10; i++)
{
for (int j = 1; j < 6; j++)
{
if (A1[i] = j)
{
A2[j - 1]++;
break;
}
}
}
for (int i = 0; i < 5; i++)
cout << A2[i];
The error is on the row 21 or 22, you are using a single = which is the assignment sign, inside the if statement, so you are overwriting the value of A[i] to the value of j, but want to check if the element of A[i] is equal to j... So you have to add a = in the if statement.
I don't recommend that you use goto:, it creates spaghetti code. you can put an i-- in your error clause, like so:
int temp;
for (int i = 0; i < count; i++){
cout << i + 1 << "- enter a number between 1 and 5 for value : " << endl;
cin >> temp;
if (temp >= 1 && temp <=5)
A1[i] = temp;
else
i--;
}
Also, if you want to compare 2 values, you should use the == operator. that is what's causing the problem in your second loop
like so:
for(int i = 0; i < count; i++){
for(int j = 1; j < 6; j++)
if(A1[i] == j)
A2[j-1]++;
}
This should work.

(C++) Input specific pattern accoring to user input

I have a line of code that when inputted 3, the result will print out a series of dashes and asterisks to form a diamond:
Expected Input:
3
Expected Output:
--*--
-***-
*****
-***-
--*--
what i have so far is the triangle but I can' seem to get rid of the middle line to make it a full diamond shape. Also "-" is not printing on the right side of the bottom half
this is the code I have made
int n;
cin >> n;
for (int left_stars = 0; left_stars < n; left_stars++) {
for (int column = 0; column < 2 * n - 1; column++) {
int first_star = n - 1 - left_stars;
int last_star = n - 1 + left_stars;
if (column < first_star || column > last_star) {
cout << "-";
} else {
cout << "*";
}
}
cout << endl;
}
for(int i = n; i >= 1; --i) {
for(int space = 0; space < n-i; ++space) {
cout << "-";
}
for(int j = i; j <= 2*i-1; ++j) {
cout << "*";
}
for(int j = 0; j < i-1; ++j) {
cout << "*";
}
cout << endl;
}
return 0;
For removing the double full star line use following code line
for (int i = n-1; i >= 1; --i) {
instead of
for(int i = n; i >= 1; --i) {
(side note: maybe you want to check as suggested by yaodav if you could not write the second part like the first part).

How does c++ react to int array indexes while performing standard mathematical expressions?

The idea I have is pretty simple. What I'd like to do is just have the user input a series of integers and plug those integers specified into an array. So for example, here's a segment of the program I'm writing.
const int size = 1000;
int array_one[size], array_two[size];
for (int i = 0; i < size; i++)
{
std::cin >> array_one[i];
if (array_one[i] == -1) break;
}
for (int i = 0; i < size; i++)
{
std::cin >> array_two[i];
if (array_two[i] == -1) break;
}
The cut off point is -1. Should the user enter this, one index of the array will be all integers greater than -1 with the following indexes housing 0's in this 1000 sized array.
What I'm doing next is simply replicating how you would write out basic addition on paper. So, lets say for example I plugged in 1 0 0 6 -1 as inputs for the first array and then 2 3 4 for the second array. The whole entire output should look something akin to this
1006
+ 234
------
1240
Here's what I've typed out to get this sort of output
int array_size_one = 0;
int array_size_two = 0;
int space_size = 3;
int cut_off_space = 0;
int count = 0;
for (int i = 0; i < size; ++i)
{
if (array_one[i] < 0) break;
array_size_one += 1;
}
for (int i = 0; i < size; ++i)
{
if (array_two[i] < 0) break;
array_size_two += 1;
}
if (array_size_one > array_size_two) space_size += array_size_one;
else if (array_size_two > array_size_one) space_size += array_size_two;
if (array_size_one < array_size_two) cut_off_space += array_size_one;
else if (array_size_two < array_size_one) cut_off_space += array_size_two;
std::cout << std::setw(space_size - array_size_one);
for (int j = 0; j < size; ++j)
{
if (array_one[j] < 0) break;
std::cout << array_one[j];
}
std::cout << "\n+";
std::cout << std::setw((space_size - 1) - array_size_two);
for (int j = 0; j < size; ++j)
{
if (array_two[j] < 0) break;
std::cout << array_two[j];
}
std::cout << "\n";
std::cout << std::setfill('-') << std::setw(space_size) << " " << std::endl;
for (int i = 0; i < (space_size - 3); ++i)
{
count = array_one[i] + array_two[i];
}
std::cout << count << std::endl;
return 0;
This is the part where I think I'm sure I'm having trouble with.
std::cout << "\n";
std::cout << std::setfill('-') << std::setw(space_size) << " " << std::endl;
for (int i = 0; i < (space_size - 3); ++i)
{
count = array_one[i] + array_two[i];
}
std::cout << count << std::endl;
return 0;
The idea was that I wanted to add up everything inside each index of the arrays to perform standard integer expressions. The for loop above isn't really cutting it. I'm getting outputs like 5 or 15. If going by the example above that has inputs of 1 0 0 6 -1 for the first array and then 2 3 4 -1 for the second array. What could I actually do inside the very last for loop iteration to make sure I get the correct outputs replicating standard integer expressions?

How do you calculate the total number of -1s and the total numbers of 1s in the table? (c++)

Here is the coding below :) I have also commented on some parts so that it is easier to understand the output of the code.
I have a slight idea that I need to use an "if statement" with "rand()%" in order to make sure that the program knows we want to calculate the sum of 1s and -1s only. for e.g using "rand()%2-1" can help with getting the total sum of 1s outputted in the table. Again, I'm not sure if this idea will work or not.
So the program should output something like "The amount of 1s in the table is 5 and the amount of -1s in the table is 3" for the first time its ran. Then when it is ran the second time, it could output something like "The amount of 1s in the table is 2 and the amount is -1s in the table is 5"
Sorry for any confusions and All your help will be highly appreciated :) :)
#include<iostream>
#include<iomanip>
#include<ctime>
using namespace std;
int main() {
srand(time(0));
const int ROWS=3;
const int COLS=4;
int table[ROWS][COLS];
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++) {
table[i][j] = rand()%3-1;
}
}
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++)
cout << setw(3) << table[i][j];
cout << endl;
}
bool checkTable [ROWS][COLS];
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++) {
if (table[i][j] !=0) {
checkTable[i][j] = true;
}
else{
checkTable[i][j] = false;
}
//The output in the line below is the final line outputted by the
console. This prints out "1" if there is a value in the index within
the table provided above (the value is represented by 1 or -1), and
prints out "0" if there is no value in the index (represented by 0)
cout << " " << checkTable[i][j];
}
}
return 0;
}
[...] for e.g using "rand()%2-1" can help with getting the total sum of 1s
outputted in the table.
I dont really understand what you mean by that. Counting and randomness dont go well together. I mean of course you can fill a matrix with random numbers and then do some counting, but rand() wont help anything for the counting.
You need something as simple as that:
int main() {
srand(time(0));
const int ROWS=3;
const int COLS=4;
int table[ROWS][COLS];
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++) {
table[i][j] = rand()%3-1;
}
}
unsigned ones_counter = 0;
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++) { // dont forget the bracket
cout << setw(3) << table[i][j];
if (table[i][j] == 1) { ones_counter++;} // <- this is counting
}
cout << endl;
}
std::cout << "number of 1s in the table : " << ones_counter << "\n";
....

C++ For loops and multidimensional arrays

So I have an assignment for my C++ class. Basically we have to create a 3x3 multidimensional array, calculate the sum of rows, sum of columns, sum of diagonal values and sum of anti-diagonal values, I usually just input 1 2 3 4 5 6 7 8 9 as values as a starting point.
Now, I'm not trying to be rude but my teacher is not very good, we basically spend 2 hours on a single problem without her doing much explaining. Other than that I started with C++ Primer and Programming: Principles and Practice Using C++ so I believe I'll be able to learn a lot on my own.
Anyhow my questions are probably quite stupid, but if anyone feels like helping, here they are:
My /**/ commented for loop for anti-diagonal value gives me a wrong sum. I'm assuming it has something to do with the nature of for-loops or I just type it out wrong, but I didn't figure it out yet.
2.The teacher's solution for calculating the anti-diagonal values is the following:
for (i = 0; i < row_num; ++i)
for (j = 0; j < col_num; ++j)
if (i + j == row_num - 1)
anti-diagonal += A[i][j];
How is it different from my approach? I believe mine is simpler and works better.
3.In line:
int sumRows[row_num] = { 0 };
Why do {} have to be used? Our teacher didn't bother with explaining that. I tried without {} but I got an error.
Here is the full code for my version:
#include "../../std_lib_facilities.h"
#include <iostream>
using namespace std;
#define row_num 3 //no. of rows
#define col_num 3 //no. of columns
int main()
{
int i = 0;
int j = 0;
int diagonal = 0;
int antidiagonal = 0;
int sumRows[row_num] = { 0 };
int sumCol[col_num] = { 0 };
int A[row_num][col_num];
//Input to matrix
for(i=0; i<row_num; i++)
for (j = 0; j < col_num; j++)
{
cout << "A[" << i << "]" << "[" << j << "]: ";
cin >> A[i][j];
sumRows[i] += A[i][j];
sumCol[j] += A[i][j];
}
cout << endl;
//Print out the matrix
for (i = 0; i < row_num; i++)
{
for (j = 0; j < col_num; j++)
cout << A[i][j] << '\t';
cout << endl;
}
//prints sum of rows
for (i = 0; i < row_num; i++)
cout << "Sum of row " << i + 1 << " "<< sumRows[i] << endl;
//prints sum of columns
for (j = 0; j < row_num; j++)
cout << "Sum of column " << j + 1 << " " << sumCol[j] << endl;
//Sum of diagonal values
for (i = 0; i < row_num; i++)
diagonal += A[i][i];
//Sum of antidiagonal values
for (i = 0, j = 2; i < row_num, j >= 0; i++, j--)
antidiagonal += A[i][j];
/*for(i=0; i<row_num; i++)
for (j = 2; j >= 0; j--)
{
antidiagonal += A[i][j];
}
*/
cout << "\nSum of diagonal values: " << diagonal << endl;
cout << "Sum of antdiagonal values: " << antidiagonal << endl;
return 0;
}
1) Your commented out loop sums all values, not just those along the antidiagonal.
2) It is different from your approach in that it will iterate over every value in the matrix, but then it will only add to the total if it detects it is in one of the appropriate cells. Your solution only iterates over the appropriate cells and doesn't have to evaluate any ifs, so it will be more efficient. However, you need to change your loop condition to i < row_num && j >= 0. Using a comma here will discard the result of one of the checks.
3) int sumRows[row_num] = { 0 }; initializes the whole sumRows array with 0's.
1) This
for(i=0; i<row_num; i++)
for (j = 2; j >= 0; j--)
{
antidiagonal += A[i][j];
}
is wrong, because for i=0 you iterate through all j values, ie
i=0 , j=2,1,0 then i=1
2) Your teachers loop is easier to read and correct. Yours has a wrong break condition:
for (i = 0, j = 2; i < row_num, j >= 0; i++, j--)
^------------------------ WRONG
Read about the comma operator to understand what is actually going on here. You just didnt realize the problem, because the two conditions are by chance equivalent.
3) You dont have to use it, it is just a new and fancy way to initialize the array.