I created an array of A[rows][columns] random numbers between 100 and -100
saved it in txt file
Now i have to check if all numbers are negative in column and if so save column number in array C[x];
int main()
{
ofstream out("masyvas.txt");
srand(time(0));
int n=rand() % (31 - 10) + 10; // eilutes
int m=rand() % (31 - 10) + 10; // stulepliai
int A[n][m];
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
A[i][j]=rand()%100 + (rand()%100 *(-1)) ;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
out<<setw(5)<<A[i][j]<<" ";
out<<endl;
}
out.close();
//------------------------------------------
return 0;
}
so above everything is ok but
ofstream rez("rez.txt");
for(int i=0; i < m;i++)
{
for(int j=0; j< n;j++) {
if(A[i][j]<0){
rez << i <<" - column" << j << "- row"<< endl;
}
}
}
cout << n << endl << m << endl;
rez.close();
first i wanted to print into txt file if it finds negative numbers correctly but i get some nonsense
and i have no clue what to do im stuck for half an hour trying to do different things
First thing, don't panic, read your code and actually know what it is doing.
To check if all numbers in a column are negative, you need to loop over an entire column first while having something, preferably a boolean, to tell you if any of them is not negative.
For example: create a flag that defaults to true.
bool allNegative = true;
for ( int i =0; i < (sizeof(matrix[0])/sizeof(int)); i++)
{
if(matrix[i][0] > 0) allNegative = false; // change the flag to indicate that it is not all negative
}
Then what you want to do is if the flag is still true, loop that column again to just copy and paste all this code for each row to output that column to a txt file.
out<<setw(5)<<A[i][j]<<" ";
out<<endl;
EDIT: thanks to comment, I have changed the syntax error.
Related
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.
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";
....
I found some answers related to this problem already, but I don't really get how they work. I need to find the biggest sum of each row of a two dimensional and print it out, but don't print any of the other sums out. Here is what I have so far:
#include <iostream>
using namespace std;
int main (int argc, char ** argv)
{
int v[3][5]; // 3 rows, then 5 columns
for (int i=0; i<3; i++){
for (int j=0; j<5; j++){
cin >> v[i][j];
}
}
//test reading value
for (int i=0; i<3; i++){
for (int j=0; j<5; j++){
cout << v[i][j];
if (i!=4)
cout << ' ';
}
cout << '\n';
}
//solve it
for (int i=0; i<3; i++){
int sum = 0;
for (int j=0; j<5; j++){
sum += v[i][j];
}
cout << sum << '\n';
}
return 0;
}
This code right now prints out the sum of each row in the 2D array, but I need my program to print out just the biggest sum of the rows. This is the only problem I have right now. Thanks in advance.
You can accomplish this by keeping track of the largest sum computed for each row of the array.
//solve it
int largestSum = 0;
for (int i = 0; i<3; i++)
{
int sum = 0;
for (int j = 0; j<5; j++)
{
sum += v[i][j];
}
// check to see if we have computed a new larger sum and save it if we have.
if (sum > largestSum)
{
largestSum = sum;
}
}
cout << "largest sum: " << largestSum << '\n';
Alternatively if you are allowed to use other components in the C++ Standard library you can use std::accumulate to calculate the sum instead of using an inner look, and std::max to determine the largest sum between current and previously calculated sum.
#include <algorithm>
#include <numeric>
//solve it
int largestSum = 0;
for (int i = 0; i<3; i++)
{
int sum = std::accumulate(std::begin(v[i]), std::end(v[i]), 0);
largestSum = std::max(sum, largestSum);
}
cout << "largest sum: " << largestSum << '\n';
Here is the shortest solution I could come up with, and also correctly handling negative sums (C++11):
int maxSum = std::numeric_limits<int>::min();
for (const auto& row : v)
maxSum = std::max(maxSum, std::accumulate(std::begin(row), std::end(row), 0));
std::cout << maxSum << std::endl;
int biggestSum = 0;
for (int i=0; i<3; i++) {
int currentSum = 0; // sum of values in this row
for (int j=0; j<5; j++){
currentSum += v[i][j];
}
if ( currentSum > biggestSum) biggestSum = currentSum; // we have new max
}
cout << biggestSum << '\n';
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! :)
I have file that contains 20x20 matrix with random numbers. I've read the numbers on the file and then to store in the array. It seems I had not actually assign the numbers to array, because when I had print one of the number it displayed something like "||" instead of number, see the line cout <<array[0][1]. My complete code is below:
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
#define length 20
int main(){
char array[length][length];
char chs;
ifstream grid;
grid.open("D:\\Example\\digit.txt", ios::in);
while (!grid.eof()){
for (int i = 0; i < 19; i++){
for (int j = 0; j < 19; j++){
grid.get(chs);
if (!grid.eof()){
array[i][j] = chs;
cout << setw(1) << array[i][j];///It display the numbers on file, there is no problem here.*/
}
}
}
}
cout <<array[0][2];//There is problem it can not display the number it display something different than numbers.
grid.close();
while (1);
}
Output of the consol, the numbers on the file exactly look like this. cout <<array[0][3] does not print
I've changed the last part
cout << endl;
for (int i = 0; i < 19; i++){
for (int j = 0; j < 19; j++){
cout << array[i][j];
}
}
cout << endl;
grid.close();
Output of the last part that is different than numbers on the file
Your inner loop only runs for the current value of i, meaning that you read no values into the first row, 1 into the second row etc.
for (int i = 0; i < 19; i++){
for (int j = 0; j < i; j++){
// ^ wrong
If you want to read a 20x20 matrix, both your inner and outer loop should run for 20 iterations.
for (int i = 0; i < 19; i++){
for (int j = 0; j < 19; j++){
// ^^
Note also that you probably need to add some code to handle any newlines in your input file. After each set of 20 digits, you'll have one (\n) or two (\r\n) characters indicating a newline. These are a valid part of the text file but presumably aren't required to be stored in your array.