C++ Program Debugging - c++

I seem to be having some problems with my program. It compiles fine, but when I get to my first loop it asks me for a positive integer than it asks me again like its suppose too. Than it hops down a blank space and wont run any further until you enter another number which its not suppose to do. But than when you enter a number it goes back and asks me to enter an integer also like its suppose to the problem is, IT will do this infinite amount of times until I quit the program. Any suggestions as to why this is happening?
/* Search the entries of the n X n matrix mat in rowwise order for an entry to item */
#include <iostream>
using namespace std;
int main(void)
{
int n=10, item, row=3, col=3, mat[row][col];
bool found;
for (int row = 0; row < 3; row++)
for (int col = 0; col < 3; col++)
{
cout << "Enter Positive Integer : ";
cin >> row;
cout << " Enter Positive Integer : ";
cin >> mat[row][col];
}
cout << "Enter a positive integer you want to be searched: ";
cin >> item;
for(int i=0; i<row; ++i)
{
for(int j=0; j<col; ++j)
{
if(mat[row][col] == item)
found = true;
else
found = false;
}
}
if(found==true)
cout << "item found" ;
else
cout << "item found ";
return 0;
}

The line for (int cols = 0; cols < 5; col++) increments the variable col, not cols. Since cols is always 0, the loop will never terminate.
You've done the same in for (int rows = 0; rows < 5; row++). Infinite loops often occur due to typos in loop conditions ;)
I would also like to point out some logic errors during your search:
for(int i=0; i<row; ++i)
{
for(int j=0; j<col; ++j)
{
if(mat[row][col] == item)
found = true;
else
found = false;
}
}
When that loop ends, found will only be true if mat[row-1][col-1] == item (the very last element). Heck, row and col never change in the loop so you are repeatedly checking the exact same element every time! You should also expect even more funky program behavior if you don't get a grasp on your variable names. I strongly recommend adding debug statements to see how your variables are being modified throughout the program (aka: cout << "rows = " << rows << endl;, and cout << "i = " << i << endl;, etc). You're preparing a recipe for disaster when you reuse your variables.
Disclaimer: Reusing variables is not always a bad thing. However, it's best to avoid it until you have a stronger understanding of variables.

In your loop you are incrementing row and col not rows and cols.

It looks to me like you are using the same variable for the loop counter and the user input storage. That is doomed to not do what you want.
Do something like:
for (rowCounter = 0; rowCounter < 3; rowCounter++) {
for (colCounter = 0; colCounter < 3; colCounter++) {
cout << “Give me value for (“ << rowCounter << “,” << colCounter << “) :”;
cin >> mat[rowCounter][colCounter];
}
}
and then the rest of your code

It seems you had a couple of issues.
In the first for loop, you were incrementing the wrong variable (col instead of cols), you also went from 0 to 4 in a 3x3 matrix
you asked the user for 2 numbers then you asked the user to put in a number in the matrix, but its only a 3x3 matrix, the user could easy go out of bounds. I think what you were trying to do was populate the matrix with users number. So i made that change.
In the second for loop, you set found =true, but the loop will keep going, meaning the last number it searched, if it was false, then found = false, also changed it to mat[i][j] instead of mat[row][col], so it doesn't check the same one every time.
both found = true and found = false would return "item found", i think you left off the "not" in the second hard coded string.
I added a pause so you can read the output at the end.
I fixed them and I think this code should do what you want it to now.
#include <iostream>
using namespace std;
int main(void)
{
int n=10, item, row = 3, col = 3;
int mat[3][3];
bool found = false;
int j,k;
for (int rows = 0; rows < 3; rows++)
for (int cols = 0; cols < 3; cols++)
{
cout << "Enter row Integer: ";
cin >>j;
cout << "Enter col Integer: ";
cin >> k;
cout << "Enter Positive Integer : ";
cin >> mat[j][k];
}
cout << "Enter a poistive integer you want to be searched: ";
cin >> item;
int flag = 0;
for(int i=0; i<row; ++i)
{
for(int j=0; j<col; ++j)
{
if(mat[i][j] == item)
{
flag = flag + 1;
}
}
}
if(flag > 0)
found = true;
if(found==true)
cout << "item found" ;
else
{
cout << "item not found ";
}
system("PAUSE");
return 0;
}

Related

How can i prohibit duplicate input values on a 2D array?

Here is my code and I want to restrict reoccurring values when the user is trying to input the same value. It would be best if everything is only at the main function because i'm still learning about declaring more functions.
`
#include <iostream>
using namespace std;
int main() {
int num[10][10];
int times;
cout << "Please input the number of times you wish to enter a value but does not exceed to 100: ";
cin >> times;
cout << "Enter a value " << times * times << " times." << endl;
for(int i = 0; i < times; i++) {
for(int k = 0; k < times; k++) {
cout << "Please input a number on index [" << i << "][" << k << "]: ";
cin >> num[i][k];
}
}
//Displaying the inputs
cout << "Printing all values inside the array: " << endl;
for(int i = 0; i < times; i++) {
cout << endl;
for(int k = 0; k < times; k++) {
cout << "\t" << num[i][k] << " ";
}
}
return 0;
}
`
This is my expected output to be when a user tries to input a duplicate value:
Please input a number on index [0][0]: 7
Please input a number on index [0][1]: 7
Value already entered. Please try again.
Please input a number on index [0][1]:
In this context, you could have a function like this:
bool doesExist(
const int array[][10], const size_t size, const int value, int x, int y)
{
for (size_t i = 0; i < size; i++)
for (size_t j = 0; j < size; j++) {
if (x == i && y == j)
continue; // Skip the new element.
// If duplicate found
if (value == array[i][j])
return true;
}
return false;
}
It takes the array, its size, the value to be compared, and the position of the unique element inserted for the first time as arguments.
You could implement it this way:
cin >> num[i][k];
if (doesExist(num, times, num[i][k], i, k)) {
cout << "Already exists.\n";
...
}
This is not the best approach to this problem. In C++, it is recommended to apply STL containers as they provide more safety and iterators.
You just want the use not to enter duplicate values :-
First very basic you can just check all the previous values,
if it matches with the current one then you can tell the user to change the value.
You can use unordered_map, as map is (key,value) pair whenever you insert any value in map just set its corresponding value to 1, and then you can check in your map if thats value is already present in map or not if its present then you can tell the user to change, in map it will be easy to search.(code is simple)

How can I check input validation for negative values in a 2D array in C++?

just a quick question here. I am trying to check for negative values for input validation, I want my program to only accept positive value only for the user input, this is my code here.
//loop to array.
for(int i = 0; i < 3; i++) //loop to row first
{
//take in input into data.
for(int j = 0; j < 5; j++) //loop to column
{
//take input data.
cout <<"Monkey " << i+1 <<" ";
cout <<"Day " << j +1 << ":";
cin >> pound_food[i][j];
if(pound_food[i][j] < 0)
{
cout <<"Invalid number, number can't be negative, please try again\n";
break;
}
}
I try to break out the loop or continue when they find the negative number, however it just keep end up storing the number even though I don't want negative number to store in the array. I just want it to store positive integer only and re prompt the user to enter the number again. I can't figure out why, I hope to hear you guys opinion!
If you encounter a negative number, then instead of breaking out of the entire column loop, you can just decrement the column index j. This way, the next number will be inserted into the same position where the negative number was just inserted:
if(pound_food[i][j] < 0)
{
cout <<"Invalid number, number can't be negative, please try again\n";
--j; // instead of break
}
Another solution is write an inner while loop, and only break out until the input is ok:
for(int j = 0; j < 5; j++) //loop to column
{
//take input data.
cout <<"Monkey " << i+1 <<" ";
cout <<"Day " << j +1 << ":";
bool ok = false;
while (!ok)
{
cin >> pound_food[i][j];
if(pound_food[i][j] < 0)
cout <<"Invalid number, number can't be negative, please try again\n";
else
ok = true;
}
}
Or:
for(int j = 0; j < 5; j++) //loop to column
{
//take input data.
cout <<"Monkey " << i+1 <<" ";
cout <<"Day " << j +1 << ":";
while (true)
{
cin >> pound_food[i][j];
if(pound_food[i][j] < 0)
cout <<"Invalid number, number can't be negative, please try again\n";
else
break;
}
}

Input number, then print stairs vertically mirrored

as in the title.
I could do the easier one, just print them normally, but I have no clue how to mirror them. Here's my code for the "backwards" stairs.
int szam;
cin >> szam;
for (int i = 0; i < szam; i++) {
for (int j = 0; j <= i; j++) {
cout << "*";
}
cout << endl;
}
So when the input number is 4, It's printing this,
*
**
***
****
but i need them mirrored vertically, like this
*
**
***
****
Thanks for the help in advance, and I'd appreciate if you would explain what why happened.
This just comes down to arithmetic, really.
Study the shape again.
Now pretend you're not "mirroring" it, but just adding some whitespace to the start of each line. Because, really, you are.
How much whitespace? It starts at 3 for the first line (i=0) and ends at 0 for the last line (i=3). What's the pattern there?
When we work it out, it comes to szam-1+1 spaces.
Now we can just add those spaces, which is easy:
int szam;
cin >> szam;
for (int i = 0; i < szam; i++) {
// This loop is new
for (int j = 0; j < szam-1+1; j++) {
cout << ' ';
}
for (int j = 0; j <= i; j++) {
cout << "*";
}
cout << endl;
}
There are fancier ways using std::string or stream formatting, but this is the quick fix to your existing code.
Another way, which only involves one inner loop, is to always write szam characters but decide within the loop whether those characters should be * or a whitespace, again using arithmetic:
int szam;
cin >> szam;
for (int i = 0; i < szam; i++) {
for (int j = 0; j < szam; j++) {
cout << (j < szam-i-1 ? ' ' : '*');
}
cout << endl;
}
With this version, your original "unmirrored" output can be obtained by using (j <= i ? '*' : ' ').
By the way, you shouldn't use endl in a loop — it's pointless. endl flushes the stream, whereas you just want a newline. The way to write a newline is cout << '\n'.
Also, check cin >> szam for success before proceeding.
There are really many many solutions for this problem. I show here an example using a std::string to create a string with the reuired number of stars.
I use also IO manipulators. Maybe that is what the teacher wants to see. So, we do right alignment and set a field width.
Please see:
#include <iostream>
#include <string>
#include <iomanip>
int main() {
// Inform the user what to do
std::cout << "\nEnter the width of the stair: ";
// Read the width of the stair and check, if the read operation was successful
if (unsigned int width{}; std::cin >> width) {
// Now print the full stair
for (unsigned int i = 0U; i < width; ++i) {
// Print stars
std::cout << std::right << std::setw(width) << std::string(i+1,'*') << "\n";
}
}
return 0;
}
for (int i = 1; i <= szam; i++) {
cout << string((szam-i),' ')<<string(i,'*') << endl;
}
If you want cout then just do this. The answers are numerous.

Creating a function to find duplicates in array without sorting C++

I've been working on a lottery checking program. The goal is to create a function that finds duplicates and allows the user to choose another number in the case of userTicket, and generate another random number in case of winningNums. So this function must be reusable between the two, or with any array for the matter. I am not familiar with sorting and scanning through the array just yet. I have created a nested for loop to go through each index and compare the two between [i] and [j]. My function only works on the first number for some reason. Any ideas are greatly appreciated.
void getLottoPicks(int userArray[])
{
cout << "Please enter your 7 lotto number picks between 1 and 40.\n";
for (int i = 0; i < NUMS; i++)
{
cout << "selection #" << i + 1 << ":";
cin >> userArray[i];
cin.ignore();
if (noDuplicates(userArray) == true)
{
cout << "You already picked this number. Please enter a different number: " << endl;
cin >> userArray[i];
}
}
}
void genWinNums(int winArray[])
{
srand((int)time(NULL));
for (int i = 0; i < NUMS; i++)
{
winArray[i] = rand() % 40 + 1;
if (noDuplicates(winArray) == true)
{
winArray[i] = rand() % 40 + 1;
}
}
}
bool noDuplicates(int dupArray[])
{
int temp = 0;
for (int i = 0; i < NUMS; i++)
{
//temp += dupArray[i];
for (int j = 0; j < i; j++)
{
if (dupArray[i] == dupArray[j])
{
return true;
}
else
{
return false;
}
}
}
}
You can use std::set, it's faster and much less code
void getLottoPicks(std::set<int> userArray)
{
cout << "Please enter your 7 lotto number picks between 1 and 40.\n";
for (int i = 0; i < NUMS; i++)
{
cout << "selection #" << i + 1 << ":";
int num;
cin >> num;
cin.ignore();
// while the num is already in the set
while (userArray.find(num) != userArray.end())
{
cout << "You already picked this number. Please enter a different number: " << endl;
cin >> num;
}
}
}
In both cases your calls to noDuplicates() are nested inside the loops which are constructing the array that you pass to noDuplicates(). That won't work. First you need to construct the array, and once you are done constructing it, then you pass it to noDuplicates().

Use C++ to Print a Floyd triangle

I'm trying to build a program which will accept numbers from user and create Floyd triangle.
I tried using the logic of Floyd triangle, but its printing as a line.
Example:
Enter total numbers: 5
Enter the numbers: 3,8,2,4,9
O/p:
3
82
249
Here's my code:
#include <iostream>
using namespace std;
int main()
{
int totalnos, j, i;
cout << "Enter total numbers: ";
cin >> totalnos;
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[i];
}
for (i = 1; i <= totalnos; i++)
{
for (j = 1; j <= 1; j++)
{
cout << numbers[i];
}
}
}
You have a problem with the kind of loops shown below. I don't know wether this kind of solution is due to you coming from the Pascal world, or because you've seen it elsewhere. Anyway, you should not make loops start in 1 and go to i, or at least, you should take into account that in the C-like world (C, C++, Java, C#, and many others), arrays start at index 0, and end at index n - 1, being n the size of the array.
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[i];
}
The problem is actually not what indexes you use for loops, but that you must always use 0..n-1 when accessing arrays. So you can change your loop to just access the array correctly:
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[ i - 1 ];
}
Or you can do as all programmers in the C-like world, and directly start your indexes at 0:
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 0; i < totalnos; i++)
{
cin >> numbers[i];
}
Instead of going from 1 to totalnos, now you go from 0 to totalnos - 1 (notice the i < totalnos instead of the i <= totalnos, that's a sutil change).
You were accessing memory past the limit of the array, which means that your program will show undefined behaviour (this means that it will probably crash, though under some conditions, nothing seems to happen, which is even more dangerous).
Now the algorithm itself. I haven't heard about the Floyd triangle. It seems that it is built with the natural numbers starting from 1. However, you are asking for totalnos numbers. You will need more than totalnos numbers in order to build a Floyd triangle with totalnos rows. That's why you need to adjust the position of the number being shown taking into account the number of columns for each row (numPos starts with 0).
cout << endl;
for (i = 0; i < totalnos; i++)
{
if ( ( totalnos - i ) < numPos ) {
numPos = totalnos - i;
}
for (j = 0; j < i; j++)
{
cout << numbers[numPos] << ' ';
++numPos;
}
cout << endl;
}
You can find the whole code here: http://ideone.com/HhjFpz
Hope this helps.
Internal loop can be modified as below :
for (i=0; i < 3; i++)
{
for (j=0; j<=i; j++)
{
cout << numbers[i+j];
}
cout<<" ";
}
Hard coded value "3" can be replaced with the "number of rows of Floyd triangle .
I think this will do the trick .
In inner loop you made mistake with j <= 1; should be j <= i;
And you missed '\n' char for new line.
Here is fix:
#include <iostream>
using namespace std;
int main()
{
int totalnos, j, i, k = 0;
cout << "Enter total numbers: ";
cin >> totalnos;
//int numbers[totalnos];
//cout << "Enter the numbers: ";
// for (i = 1; i <= totalnos; i++)
// {
// cin >> numbers[i];
// }
for (i = 1; i <= totalnos; i++)
{
// your code for (j = 1; j <= 1; j++)
for(j=1; j<=i; ++j) // fixed
cout << k+j << ' ';
++k;
cout << endl; // fix
}
}