wrong output in common number array program [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I need my code to output the common numbers from two arrays but I can't seem to find the issues in my code. Here are some more words so I can fill the quota for stack's post requirement.
Here's the code.
#include <iostream>
using namespace std;
int main()
{
//Variables
int list1[5], list2[5];
cout << "Enter numbers for List No.1" << endl;
for (int i = 1; i <= 5; i++) {
cout << "Enter number " << i << ":";
cin >> list1[i];
}
cout << "Enter numbers for List No.2" << endl;
for (int i = 1; i <= 5; i++) {
cout << "Enter number " << i << ":";
cin >> list2[i];
}
{
cout << "common elements" << endl;
for (int i = 0; list1; i < i++) {
for (int i = 0; list2; i < i++)
if (list1[i] == list2[i]) {
cout << " " << list1[i];
}
}
}
return 0;
}

You should use different counter for each loop and also your loop has wrong parameters. Do it like:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (list1[i] == list2[j]){
cout<<" "<<list1[i];
}
}
}
Also for initial values start from zero index([0]) as zero index is the first element for each array:
for (int i = 0; i < 5; i++) {
cout << "Enter number " << i << ":";
cin >> list1[i];
}
Another way to do this is by using std::array. It acts very similar to a normal array but it is much better to work with.
for example if you want a char array of length of 10 you can simply write:
std::array<char, 10> My_happy_array.
First please read this to understand why you should not using namespace std. Second consider reading about Range-based for loop
Third, here is the modified version of your program which uses std::array instead of a normal array:
#include <iostream>
#include <array>
int main() {
std::array<int,5> list1;
std::array<int,5> list2;
std::cout << "Enter numbers for List No.1" << std::endl;
for (int i = 0; i < list1.size(); ++i) {
std::cout << "Enter number " << (i+1) << ":";
std::cin >> list1[i];
}
std::cout << "Enter numbers for List No.2" << std::endl;
for (int i = 0; i < list2.size(); ++i) {
std::cout << "Enter number " << (i+1) << ":";
std::cin >> list2[i];
}
for(auto i : list1){
for(auto j : list2){
if(i==j){
std::cout << " " << i;
}
}
}
return 0;
}

Here's fixed code
#include <iostream>
using namespace std;
int main()
{
//Variables
int list1[5] ,list2[5];
cout << "Enter numbers for List No.1" << endl;
for(int i = 0; i < 5; i ++)
{
cout << "Enter number " << i << ":";
cin >> list1[i];
}
cout << "Enter numbers for List No.2" << endl;
for(int i = 0; i < 5; i ++)
{
cout << "Enter number " << i << ":";
cin >> list2[i];
}
cout<<"common elements"<<endl;
for (int i = 0;i<5; i++)
{
for (int j = 0;j<5; j++)
{
if (list1[i] == list2[j])
{
cout<<" "<<list1[i];
}
}
}
return 0;
}
mistakes in code:
you used for loops wrongly whole the time.
array of 5, stores values in index (0,1,2,3,4) not (1,2,3,4,5), so always start loop from 0 and ends before max index (for this case '4' ie. use 'i<5')
while using for loop inside other for loop never use same iterable variable like you used i in both loops use i and j different for each loop,
take a look in my code..
ask me if you get any difficulties.

Related

C++ [Error] invalid conversion from 'int' to 'int (*)[2]' [-fpermissive] [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am a beginner and I keep getting an error when I am calling my function. I am trying to get the user to input a value for the array and then get it to display it in a table format. Also, I am trying to display a 3x3 matrix in the end.
void DMMatrix(int DM[2][2]){
int number;
cout << "Input 0's and 1's to the DM[2][2]\n\n";
for (int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
cout << "DM[" << i << "]"<< "[" << j << "]: ";
cin >> number;
DM[i][j] = number;
}
}
}
int main(){
int i, j, sum = 0;
int DM[2][2];
DMMatrix(DM[2][2]);
cout << "\n\nOutput (table format)\n\n";
for(i = 0;i < 3;i++){
for(j = 0;j < 3;j++){
cout << " " << DM[i][j] << " ";
}
cout << "\n";
}
sum = DM[0][0] + DM[0][1] + DM[0][2] + DM[1][0] + DM[1][1] + DM[1][2] + DM[2][0] + DM[2][1] + DM[2][2];
if (sum % 2 == 0){
cout << "\nSum is " << sum;
}
}
There are 3 problems in your program.
Mistake 1
You are calling the function DMMatrix incorrectly. The correct way to call DMMatrix would be:
DMMatrix(DM);//CORRECT WAY OF CALLING DMMatrix
Mistake 2
Your 2D array DM has 2 rows and 2 columns and you're accessing 3rd row and 3rd column of the array DM. But since the 3rd row and 3rd column doesn't exist, you have undefined behavior in your program. To solve this you can create a 3x3 2D array as shown below:
#include <iostream>
using namespace std;
void DMMatrix(int DM[3][3]){//2 CHANGED TO 3
int number;
cout << "Input 0's and 1's to the DM[2][2]\n\n";
for (int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
cout << "DM[" << i << "]"<< "[" << j << "]: ";
cin >> number;
DM[i][j] = number;
}
}
}
int main(){
int i, j, sum = 0;
int DM[3][3]; //2 CHANGED TO 3
DMMatrix(DM);
cout << "\n\nOutput (table format)\n\n";
for(i = 0;i < 3;i++){
for(j = 0;j < 3;j++){
cout << " " << DM[i][j] << " ";
sum += DM[i][j];//CALCULATE SUM HERE
}
cout << "\n";
}
cout << "\nSum is " << sum;
}
Mistake 3
You don't need to calculate the sum by writing each element of the array explicitly. You can calculate the sum inside the for loop in my modified above program. Also note that in your original code, while calculating the sum you were going out of bounds which leads to undefined behavior. The above shown program corrected this.
First, the size of the array that you have given to DM is 2x2 but your loop runs for 9 times considering the loop runs for 0, 1 and 2 which will cause a stack smash or Segmentation Fault
#include <iostream>
using namespace std;
void DMMatrix (int DM[3][3])
{
int number;
cout << "Input 0's and 1's to the DM[2][2]\n\n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << "DM[" << i << "]" << "[" << j << "]: ";
cin >> number;
DM[i][j] = number;
}
}
}
int main ()
{
int i, j, sum = 0;
int DM[3][3];
DMMatrix (DM);
cout << "\n\nOutput (table format)\n\n";
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
cout << " " << DM[i][j] << " ";
}
cout << "\n";
}
sum = DM[0][0] + DM[0][1] + DM[0][2] + DM[1][0] + DM[1][1] + DM[1][2] +
DM[2][0] + DM[2][1] + DM[2][2];
if (sum % 2 == 0)
{
cout << "\nSum is " << sum;
}
}

I got infinite loop while practicing array in C++ to find reversed number

Hye, Im a beginner trying to learn C++ language. This is my code that I tried to find reverse input numbers using array. Can help me point my mistakes since I always got infinite loop.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int ARRAY_SIZE=50;
int size[ARRAY_SIZE];
unsigned short int i;
cout << "You may enter up to 50 integers:\n";
cout << "\nHow many would you like to enter? ";
cin >> size[ARRAY_SIZE];
cout << "Enter your number: \n";
for (int i = 0; i < ARRAY_SIZE; i++)
{
cin >> size[i];
}
cout << "\nYour numbers reversed are:\n";
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Your infinite loop is because i is unsigned, so i >= 0 is always true.
Here's a C++-ified version:
#include <iostream>
#include <vector>
int main() {
std::cout << "You may enter up to 50 integers:\n";
std::cout << "\nHow many would you like to enter? ";
int count;
std::cin >> count;
// Use a std::vector which can be extended easily
std::vector<int> numbers;
for (int i = 0; i < count; ++i) {
std::cout << "Enter your number: \n";
int v;
std::cin >> v;
// Add this number to the list
numbers.push_back(v);
}
std::cout << "\nYour numbers reversed are:\n";
// Use a reverse iterator to iterate through the list backwards
for (auto i = numbers.rbegin(); i != numbers.rend(); ++i) {
// An iterator needs to be de-referenced with * to yield the value
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}
There's many problems in your original code, but the clincher is this:
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Since you keep adding to i through each cycle you'll never go below zero, especially not for an unsigned short int. This should be:
for (int i = count - 1; i > 0; --i) {
std::cout << numbers[i];
}
Presuming you have a thing called numbers instead of the bizarrely named size and the array size is count, not i, as i is generally reserved for iterators and loop indexes.

C++ mistake in finding a 'x' number in 2D array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
In my code below, I try to find an 'x' in a 2D array and display its row and column. But it always shows the a[0][1] in the result. Can someone tell me where did I wrong and why is that? I tried other code but there is no difference. Thanks
My code:
#include <iostream>
using namespace std;
int main(){
int m, n, i, j, a[m][n], sum, x, sl=0;
cout<<"insert array number of rows: "; cin>>m;
cout<<"insert array number of columns: "; cin>>n;
for(i=0;i<m;i++){
sum=0;
for(j=0;j<n;j++){
cout<<"insert board["<<i<<"]["<<j<<"]: ";
cin>>a[i][j];
sum+=a[i][j];
}
cout<<"the summary of rows "<<i<<" is: "<<sum<<endl;
}
cout<<"search x= "; cin>>x;
for (i=0; i<=m-1; i++){
for (j=0; j<=n-1; j++){
if (a[i][j]==x){
sl++;
cout<<"x is at "<<"a["<<i<<"]["<<j<<"]"<< endl;
}
}
}
if(sl==0){
cout<<"there is no x in the array";
}
cout<<sl;
return 0;
}
My results:
Sources of error in your code:
You were using a variable length array (which is not a part of C++ standard). Moreover you were setting its rows and columns before even initializing/inputting n and m.
Fixed Code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int m, n, x, sl = 0;
cout << "Insert number of rows in the array: ";
cin >> m;
cout << "\nInsert number of columns in the array: ";
cin >> n;
// put the below line after cin >> m; cin >> n;
vector<vector<int>> a(m, vector<int>(n, 0)); // <-- Use this instead of int a[m][n];
cout << endl;
for (int i = 0; i < m; ++i) {
int sum = 0;
for (int j = 0; j < n; ++j) {
cout << "\nInsert board[" << i << "][" << j << "]: ";
cin >> a[i][j];
sum += a[i][j];
}
cout << "\nThe sum of the row " << i << " is: " << sum << endl;
}
cout << "\nSearch x = ";
cin >> x;
cout << '\n' << endl;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (a[i][j] == x) {
sl++;
cout << "x is at a[" << i << "][" << j << "]\n";
}
}
}
if (sl == 0) { cout << "\nThere is no x in the array!"; }
else cout << '\n' << sl;
return 0;
}
Sample Input :
2
2
3
4
7
3
3
Sample Output :
Insert number of rows in the array:
Insert number of columns in the array:
Insert board[0][0]:
Insert board[0][1]:
The sum of the row 0 is: 7
Insert board[1][0]:
Insert board[1][1]:
The sum of the row 1 is: 10
Search x =
x is at a[0][0]
x is at a[1][1]
2
For interactive run, you can remove the newline characters at your wish.

How do you get cin to only accept numbers from user input? [duplicate]

This question already has answers here:
How to make cin take only numbers
(2 answers)
Closed 6 years ago.
So the requirements for this program is to be able to increment arrays of the same size (size from 5 to 15 indexes) and increment each element in the array by one using for and while loops. The last task is to take values from the first array and put them in reverse order and assign them to the second array.
So everything works as normal, and the program rejects invalid inputs and does not go into an infinite loop. However, the program accepts some inputs that are not wanted.
For example, I would input something like '12 a' or '7 asdfkla;j lasnfg jasklgn asfg' and it would go through. It is interesting too because the code registers only 12 or 7 and completely ignores the rest. I think it is because once it hits a non-integer character, it would stop ignore the rest.
Why is it ignoring the rest of the input? And is there a way to catch this error from going through?
Also, if you see anything that catches your eye, feel free to critique c: I am always looking to improving.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int x;
int j = 0;
bool not_valid = true;
system("color f");
cout << "Program will ask for an input for the size of an array.\n"
<< "With the array size defined, program will generate semi-\n"
<< "true random integers from 0 to 8. First array will then\n"
<< "be assigned to the second in reverse (descending) order.\n\n";
do {
cout << "Enter array size (0 - 15): ";
cin >> x;
if (x >= 5 && x <= 15) {
not_valid = false;
cout << "\nArray size: " << x << endl;
}
else {
cout << "Invalid input.\n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
} while (not_valid);
int *arr0;
int *arr1;
arr0 = new int[x];
arr1 = new int[x];
for (int i = 0; i < x; i++) {
arr0[i] = rand() % 9;
}
for (int i = 0; i < x; i++) {
arr1[i] = rand() % 9;
}
cout << "\nARRAY 0 (unmodified, for):\n";
for (int i = 0; i < x; i++) {
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 0 (modified, for):\n";
for (int i = 0; i < x; i++) {
arr0[i]++;
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 1 (unmodified, while):\n";
for (int i = 0; i < x; i++) {
cout << arr1[i] << "\t";
}
cout << "\n\nARRAY 1 (modified, while):\n";
while (j < x) {
arr1[j]++;
cout << arr1[j] << "\t";
j++;
}
int second = x - 1;
for (int i = 0; i < x; i++) {
arr1[second] = arr0[i];
second--;
}
j = 0;
cout << "\n\nARRAY 1 (array 0, descending):\n";
while (j < x) {
cout << arr1[j] << "\t";
j++;
}
cout << endl << endl;
system("pause");
return 0;
}
Take input in string and then check if it's a number or not.
Example:
#include<iostream>
#include<sstream>
#include <string>
using namespace std;
int main()
{
string line;
int n;
bool flag=true;
do
{
cout << "Input: ";
getline(cin, line);
stringstream ss(line);
if (ss >> n)
{
if (ss.eof())
{
flag = false;
}
else
{
cout << "Invalid Input." << endl;
}
}
}while (flag);
cout << "Yo did it !";
}

Greedy Algorithm for coin change c++

So, I'm creating a coin change algorithm that take a Value N and any number of denomination and if it doesn't have a 1, i have to include 1 automatically. I already did this, but there is a flaw now i have 2 matrix and i need to use 1 of them. Is it possible to rewrite S[i] matrix and still increase the size of array.... Also how can i find the max denomination and the second highest and sooo on till the smallest? Should i just sort it out in an highest to lowest to make it easier or is there a simpler way to look for them one after another?
int main()
{
int N,coin;
bool hasOne;
cout << "Enter the value N to produce: " << endl;
cin >> N;
cout << "Enter number of different coins: " << endl;
cin >> coin;
int *S = new int[coin];
cout << "Enter the denominations to use with a space after it" << endl;
cout << "(1 will be added if necessary): " << endl;
for(int i = 0; i < coin; i++)
{
cin >> S[i];
if(S[i] == 1)
{
hasOne = true;
}
cout << S[i] << " ";
}
cout << endl;
if(!hasOne)
{
int *newS = new int[coin];
for(int i = 0; i < coin; i++)
{
newS[i] = S[i];
newS[coin-1] = 1;
cout << newS[i] << " ";
}
cout << endl;
cout << "1 has been included" << endl;
}
//system("PAUSE");
return 0;
}
You could implement it with std::vector, then you only need to use push_back.
std::sort can be used to sort the denominations into descending order, then it's just a matter of checking whether the last is 1 and adding it if it was missing. (There is a lot of error checking missing in this code, for instance, you should probably check that no denomination is >= 0, since you are using signed integers).
#include <iostream> // for std::cout/std::cin
#include <vector> // for std::vector
#include <algorithm> // for std::sort
int main()
{
std::cout << "Enter the value N to produce:\n";
int N;
std::cin >> N;
std::cout << "Enter the number of different denominations:\n";
size_t denomCount;
std::cin >> denomCount;
std::vector<int> denominations(denomCount);
for (size_t i = 0; i < denomCount; ++i) {
std::cout << "Enter denomination #" << (i + 1) << ":\n";
std::cin >> denominations[i];
}
// sort into descending order.
std::sort(denominations.begin(), denominations.end(),
[](int lhs, int rhs) { return lhs > rhs; });
// if the lowest denom isn't 1... add 1.
if (denominations.back() != 1)
denominations.push_back(1);
for (int coin: denominations) {
int numCoins = N / coin;
N %= coin;
if (numCoins > 0)
std::cout << numCoins << " x " << coin << '\n';
}
return 0;
}
Live demo: http://ideone.com/h2SIHs