How to test to see if an array element is empty? - c++

To simplify it, I need to read numbers from a file and store them in a 2D array. I then must check to make sure that the there were enough numbers in the file to fill the array.
the first two numbers in the file are the ones that declare how many rows and columns there should be for the array.
The part I am struggling with is that the numbers in the file can also include a 0 in them.
I was using this method to test if an element was empty
double numbers[MAX_ROW][MAX_COL];
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(!numbers[i][n]){
cout << "Error: There is not enough data found file :(...." << endl;
cout << "The Program will now exit....." << endl;
return 0;
}
}
}
But then I realized that the program would exit if the file contained the number 0. Which is something that I don't want to happen.
I also tried to using a pointer and testing for NULL but that gave me a warning about (comparison between NULL and non-pointer) and it would still do the same thing, if there was a 0 in the file it would just exit.
double (*ptrNumbers)[MAX_COL] = numbers;
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(ptrNumbers[i][n] == NULL){
cout << "Error: There is not enough data found file :(...." << endl;
cout << "The Program will now exit....." << endl;
return 0;
}
}
}
Example files:
This one works fine
3 3
1 3 4
3 2 4
3 5 2
This will not works because of the zero in the file
3 3
1 3 4
3 0 4
3 5 2
This is the type of error i would like to test for.
It says there are 3 rows and 3 columns but there aren't numbers to fill the rest of the array. Therefore they will be initialized to 0 which as you can conclude will also cause the same problem.
3 3
1 3 4
3 2 4
3
Anyone have any idea how I can test for "empty" elements but not elements containing 0s?? Or am I just doing something wrong?
Thanks in advance for any help :)
After I altered my program from the previous recommendations.
I set up a bool function to return a false statement if there was not enough numbers in the file. However even if the file had the correct amount of numbers the file would still execute the if statement and return a false value. Is my syntax wrong in some way?
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(!(inFile >> numbers[i][n])) {
return false;
}
else {
inFile >> numArray[i][n];
}
}
}
return true;

You have to catch error while reading the contents of the file.
std::ifstream ifile("The input file");
ifile >> row >> col;
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if( ! (ifile >> ptrNumbers[i][n]))
{
// Problem reading the number.
cout << "Error: There is not enough data found file :(...." << endl;
cout << "The Program will now exit....." << endl;
}
}
}
Update
The updated function is faulty.
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(!(inFile >> numbers[i][n])) {
return false;
}
else {
// You are now reading into the same element
// of the array again.
inFile >> numArray[i][n];
}
}
}
return true;
You don't need the else part in that function.
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(!(inFile >> numbers[i][n])) {
return false;
}
}
}
return true;

Related

Why some compiler shows unfavorable output for a specific input?

Look at this code, In my VS code or some online compilers it gives favorable output, but when I'm submitting this on HackerRank or this online compiler I'm getting wrong output but only when I provide input as: 1 1 1 100...and I'm not able to spot the Error?..I'm providing question for reference.
/*There will be two arrays of integers. Determine all integers that satisfy
the following two conditions:
The elements of the first array are all factors of the integer being
considered
The integer being considered is a factor of all elements of the second array
These numbers are referred to as being between the two arrays. Determine how
many such numbers exist.
*/
#include <iostream>
int main()
{
int count1, count2;
int num1[20], num2[20];
std::cin >> count1 >> count2;
for (int i = 0; i < count1; i++)
{
std::cin >> num1[i];
}
for (int i = 0; i < count2; i++)
{
std::cin >> num2[i];
}
int occurence_firstarray = 0, occurence_secondarray = 0, totalvalid_occurence = 0;
for (int i = num1[count1 - 1]; i < num2[1]; i++)
{
occurence_firstarray = 0;
occurence_secondarray = 0;
for (int j = 0; j < count1; j++)
{
if (i % num1[j] == 0)
{
occurence_firstarray++;
}
}
if (occurence_firstarray == count1)
{
for (int p = 0; p < count2; p++)
{
if (num2[p] % i == 0)
{
occurence_secondarray++;
}
}
}
if (occurence_secondarray == count2)
{
totalvalid_occurence++;
}
}
std::cout << totalvalid_occurence;
return (0);
}
Considering your inputs: 1 1 1 100,
What are you doing in this code is You are pointing on index beyond your second array's size limit i < num2[1], this is why you are getting wrong outputs.
Do some changes as, i <= num2[0];

How to Print Out 2-D Array in Matrix Format in a While-Loop

I have a big while loop that read integers from a text file into 2-D array(s) and assesses array(s’) length. This loop works perfectly fine.
#include <iostream>
#include <fstream>
#include <string>
#define MAX_ROWS 3
#define MAX_COLUMNS 2
using namespace std;
int main()
{
string fileName = "inFilePgm2A.txt";
ifstream inFile;
inFile.open(fileName);
int checkNbr;
int ArrB[MAX_ROWS][MAX_COLUMNS];
bool bad = false;
bool invalidnum = false;
while (!inFile.eof())
{
bad = false;
for (int i = 0; (i < MAX_ROWS) && !bad; i++) {
for (int j = 0; (j < MAX_COLUMNS) && !bad; j++) {
inFile >> ArrB[i][j];
if (ArrB[i][j] == -1) {
bad = true;
cout << "\nThe array does not have enough integers\n";
}
else {
if (ArrB[i][j] < 1) {
invalidnum = true;
}
}
if (!bad) {
cout << *(*(ArrB + i) + j) << " ";
}
}
}
if (bad == false) {
inFile >> checkNbr;
if (checkNbr == -1) {
cout << "\nThe size of the array is correct." << endl;
}
else {
while (checkNbr != -1)
{
cout << checkNbr;
cout << " ";
inFile >> checkNbr;
}
cout << "\nYou have too many numbers in this array\n";
}
}
if (invalidnum == true) {
invalidnum = false;
cout << "\nThere is/are negative number(s) or zero(s) in the array imported from your text file.\n";
}
}
return 0;
}
For example, if my text file contains the following integers:
1 2 3 4 5 6 -1 1 2 3 7 5 8 -1 -5 9 4 -1
This will be the result:
The problem is, I don’t know how to print a 2-D array in matrix format when the array is in a while loop.
So, instead “1 2 3 4 5 6”, I want it to display
1 2
3 4
5 6
The size of the array is correct….
Usually, I can use the code below to print out an array in matrix format
for(int i = 0; i < MAX_ROWS; i++)
{
for(int j = 0; j < MAX_COLUMNS; j++)
{
cout<<ArrB[i][j]<<"\t";
}
cout<<endl;
}
But this code is not working in the while loop, if I put the code above in my while loop, (with the exactly same integers in the text file), it will just output a bunch of random values…
This is an example, I tested the below code for printing a 2D array in matrix format. You can use printf("%5d"....) instead of cout. %[n]d, where n is the integer adding that many spaces.
while (!inFile.eof())
{
bad = false;
for (int i = 0; (i < MAX_ROWS) && !bad; i++) {
for (int j = 0; (j < MAX_COLUMNS) && !bad; j++) {
inFile >> ArrB[i][j];
if (ArrB[i][j] == -1) {
bad = true;
cout << "\nThe array does not have enough integers\n";
}
else {
if (ArrB[i][j] < 1) {
invalidnum = true;
}
}
if (!bad) {
printf("%3d",ArrB[i][j]);
//cout << *(*(ArrB + i) + j) << " ";
}
}
printf("\n");
}
Output:
1 2
3 4
5 6
The size of the array is correct.
1 2
3 7
5 8
The size of the array is correct.
-5 9
4
The array does not have enough integers
There is/are negative number(s) or zero(s) in the array imported from
your text file.

Condensing output into single line

I'm working on an assignment that allows a user to enter integers (up to 20 entries) and displays a list of odd entries and even entries, when '0' is entered. The assignment requires the user to input a single integer per line.
I have managed to extract and segregate the odd and even entries, however the assignment requires that the odds be displayed on a single line, and the evens on another single line below that.
For example, if the user entered integers 1-9:
Odds: 1 3 5 7 9
Evens: 2 4 6 8
Currently, it returns:
Even: 2
Even: 4
Even: 6
Odd: 1
Odd: 3
Odd: 5
etc...
I am hoping that my program will even allow this, but I suspect the problem lies in the way I have set up the loops.
#include <iostream>
using namespace std;
bool isEven(int x) {
if ((x%2) == 0) {
return true;
} else {
return false;
}
}
int main(){
const int x = 20;
int list[x];
int counter;
cout<<"Enter up to 20 integers or press 0 to display list"<<endl;
for (counter=0; counter<x; counter++) { //main loop
cout<<"Enter number: ";
cin>>list[counter];
if (list[counter]==0) {
for (int i =0; i<counter; i++) {
if (isEven(list[i])==true) {
cout<<"Even: "<<list[i];
}
}
for (int j = 0; j<counter; j++) {
if (isEven(list[j])==false) {
cout<<"Odd: "<<list[j];
}
}
break;
}
}
return 0;
}
Split input and output to separate loops:
for (counter=0; counter<x; counter++) {
// input
}
for (counter=0; counter<x; counter++) {
// output
}
Print labels before going through each value and use \n to print a newline:
cout << "Even: ";
for (int i =0; i<counter; i++) {
if (isEven(list[i])==true) {
cout << list[i];
}
}
cout << "\nOdd: ";
for (int j = 0; j<counter; j++) {
if (isEven(list[j])==false) {
cout << list[j];
}
}
cout << "\n";

Visual studio doesn't take array: int magicSquare[n][n]?

I wrote my code and I'm ready to submit it but the teacher will be testing it on Visual studio 2015. Every time I test it, it gives me an error that this int magicSquare[n][n] is wrong and that n can't be read.
How do i revise this part to make visual studio read this array from n ?
My code:
#include <iostream>
using namespace std;
// This function is to create the requested magic squares
int main()
{
int n;
//asking for n
cout << "Please enter an odd number" << endl;
cin >> n;
//checking in case n doesnt follow rules
if (n < 3 || n % 2 == 0)
{
cout << "Invalid Entry, Please re-enter an odd number that is 3 or larger " << endl;
}
else
{
// A function to generate odd sized magic squares
int magicSquare[n][n];
// Setting every slot to 0
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
magicSquare[j][i] = 0;
}
}
// Initializing position to 1
int j = n / 2;
int i = n - 1;
// Setting each value to generate the magic square
for (int num = 1; num <= n * n; )
{
if (j == -1 && i == n)
{
i = n - 2;
j = 0;
}
else
{
//send to next number
// moving it to the right side
if (i == n)
i = 0;
//send to next number again
// moving it to the upper side
if (j < 0)
j = n - 1;
}
//second condition
if (magicSquare[j][i])
{
i -= 2;
j++;
continue;
}
else
//add the number
magicSquare[j][i] = num++;
//first condition
i++; j--;
}
//displaying sum of col/row
cout << "The sum of each row/col: " << n * (n*n + 1) / 2 << endl;
//Dispplaying magic square
for (j = 0; j<n; j++)
{
for (i = 0; i<n; i++)
cout << " " << magicSquare[i][j];
cout << "\n";
}
}
cout << endl;
//re running program
return main();
}
The standard requires the array length to be a value that is computable at compile time so that the compiler is able to allocate enough space on the stack. In your case, you are trying to set the array length to a value that is unknown at compile time. Yes, i know that it seems obvious that it should be known to the compiler, but this is not the case here. The compiler cannot make any assumptions about the contents of non-constant variables.'n' must be a constant value.
In C++, arrays that are declared that way must use an n that is known at compile time. There are various ways to construct a matrix in C++. Perhaps the simplest is to define a vector of vectors.
Change
int magicSquare[n][n];
to
std::vector<std::vector<int>> magicSquare(n);
for (auto &row : magicSquare) row.resize(n);

Arrays C++ getting values

Working on an exercise that wants to print out the index position of the number in the array once the user inputs what value he chooses.
Here's the code so far but don't know how to organize it to print of the index position of the number they put in from the list of the array
#include <iostream>
using namespace std;
int main()
{
int numbers [11] = {5, 2, 11, 6, 33, 756, 32, 0, 1, 31, -1,};
int num = 0;
int x = 0;
cout << "List:" ;
for (int i = 0; i <= 11; i++)
{
cout << numbers [i] << ", ";
}
cout << endl;
cout << "Enter a number from the list to find its position: ";
cin >> num;
numbers [x] = {num};
cout << numbers [x];
}
basically all its doing now is printing out the number you put in instead of the location it is in the array....
also how do you input values into an array from the user input
First, this is Undefined behavior,
for (int i = 0; i <= 11; i++) // will iterate from 0 to 11
Arrays range starts from 0, so if you want to loop through it or need to go to last element, you should access Array[MaxNum-1].
So you should be using,
for (int i = 0; i < 11; i++) // will iterate from 0 to (11-1)
Now coming to your doubt::
You should iterate through entire array, find your number and then print the index as following::
int nIndex = -1 ;
for (int i = 0; i < 11; i++ )
{
if ( numbers[i] == num )
{
nIndex = i ;
break ;
// Or to end the loop, you can set i = SomeValueToBreakTheCondition
// ex., i = 11
}
}
if( nIndex == -1 )
{
std::cout << Element Not Found ;
}
else
{
std::cout << "Element Found Out Index::" << nIndex ;
}
When you write int numbers[11], that is an array of 11 elements whose indices are 0 through 10.
So when you have i <= 11 in your loop; the last loop iteration reads beyond the end of the array, causing undefined behaviour. Change this to i < 11, or even better i < sizeof numbers / sizeof numbers[0], which you can wrap in a macro if you think it looks nice.
numbers [x] = {num}; would be better written as numbers[x] = num;. Anyway, you then go: cout << numbers[x] which does exactly what you say: it puts out the number at the location indexed by x, which you just stored num in.
If you want to putout the location then do cout << x;.
how do you input values into an array from the user input
You're already doing that , cin >> num; numbers[x] = num; does that. You could go cin >> numbers[x]; directly. If you run a loop then you can input several numbers in a row, for example:
for( x = 0; x < 11; ++x )
cin >> numbers[x];
1- this program does not find the index!! for finding the index you should do a loop on your array and compare the array[i] and the x
for(int i = 0 ; i < 10 ; i++)
{
if(number[i] == x)
{
// do what you want with index i
}
}
2- for inputting an array, you can do something like this
for(int i = 0 ; i < 10 ; i++) { cin >> numbers[i]; }
You are not checking in which index the given number is. The statement:
numbers [x] = {num};
simply assigns num to the x-th item of the array. In your case, x has been initialized to zero. So, the first item of the array gets set to num and
cout << numbers [x];
always prints the first item of the array.
You can fix this by replacing the lies
numbers [x] = {num};
cout << numbers [x];
by
for (int i = 0; i < 11; ++i )
{
if ( numbers[i] == num )
{
cout << i << endl;
break;
}
}
if ( i == 11 )
{
cout << "Number not found" << endl;
}
You can make a loop to find the index by yourself, also you can use std::find:
int* pos = find(&numbers[0], &numbers[11], num);
if (pos == &numbers[11]) {
cout << "not found\n";
} else {
cout << (pos - &numbers[0]) << endl;
}
In addition, you should change
for (int i = 0; i <= 11; i++)
to
for (int i = 0; i < 11; i++)
to avoid array index goes out of range.