Getting error in an array comparing program in a specific input - c++

I have written a small program which compares two arrays with custom array size. Whenever I set the array size to 4, the program does not work correctly on comparing the fourth member of each array.
(when I set x to 4, the fourth array members does not get compared correctly)
This is the code:
#include <iostream>
using namespace std;
int main()
{
int x;
std::cin >> x;
int i =1;
int arr[x];
int arr2[x];
while(i <= x)
{
std::cout << "Enter row " << i << " of arr\n";
std::cin >> arr[i];
i++;
}
i = 1;
while(i <= x)
{
std::cout << "Enter row " << i << " of arr2\n";
std::cin >> arr2[i];
i++;
}
for(int a = 0;a <= x;a++)
{
if(arr[a] == arr2[a])
std::cout << "row " << a << " is true\n";
}
}

You have an out of bound access, which yields undefined behavior. Recall that indices into raw arrays start with zero, not with one. Hence,
int i = 0;
is the correct initialization of the index, while the first loop must be changed to
while (i < x) { /* ... */ }
Then, the assignment of i needs again to be adjusted to
i = 0;
and the two remaining loops to
while (i < x) { /* ... */ }
for (int a = 0; a < x; a++) { /* ... */ }
As a side note, you are using variable length arrays (arr and arr2), which is non-standard C++ (see this thread for more info). Prefer std::vector for a simple container with runtime-dependant size.

i = 1;
while(i <= x)
{
std::cout << "Enter row " << i << " of arr2\n";
std::cin >> arr2[i];
i++;
}
you are storing element in array starts with 1 index
for(int a = 0;a <= x;a++)
{
if(arr[a] == arr2[a])
std::cout << "row " << a << " is true\n";
}
But comparing by starting from 0 index.
keep consistency either start from 0 or 1
for(int a = 1;a <= x;a++)
{
if(arr[a] == arr2[a])
std::cout << "row " << a << " is true\n";
}
it will work..

Related

why isn't my vector pushbacking even and odd numbers

i tried to separate even and odd numbers using vectors from a array ==>
so i made a function that returns true is number is even and false for if number is odd
then i used an if else statement where if the function returns true then it pushbacks the value in a vector and if the function returns false then it pushbacks the value in another vector , finally i printed all the elements in the vector but the output does not show any element except it shows one in the odd vector.
#include <iostream>
#include <vector>
using namespace std;
bool sort(int arr[] , int i){
if(arr[i] %2 == 0){
return true;
}
return false;
}
int main(){
int n;
cin >> n;
int *arr = new int[n];
for(int i=1 ; i<=n ; i++){
arr[i-1] = i;
}
vector <int> even , odd;
int i=0 ;
if(sort(arr , i)){
even.push_back(arr[i]);
sort(arr , i+1);
}else{
odd.push_back(arr[i]);
sort(arr,i+1);
}
cout << "the even numbers are : " << endl;
for(auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for(auto element:odd){
cout << element << " ";
}
}
As #TonyDelroy said, you have to make for loop around call to sort(arr, i). Also first loop should go up to i <= n instead of i < n.
Your fixed working code below (see also std::partition_copy variant afterwards):
Try it online!
#include <iostream>
#include <vector>
using namespace std;
bool sort(int arr[] , int i){
if(arr[i] %2 == 0){
return true;
}
return false;
}
int main(){
int n;
cin >> n;
int *arr = new int[n];
for(int i=1 ; i<=n ; i++){
arr[i-1] = i;
}
vector <int> even , odd;
for (int i = 0; i < n; ++i)
if (sort(arr, i))
even.push_back(arr[i]);
else
odd.push_back(arr[i]);
cout << "the even numbers are : " << endl;
for(auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for(auto element:odd){
cout << element << " ";
}
}
Input:
10
Output:
the even numbers are :
2 4 6 8 10
the odd numbers are :
1 3 5 7 9
As #chris said you can also use std::partition_copy to implement your algorithm:
Try it online!
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
int n = 0;
std::cin >> n;
std::vector<int> arr(n), odd, even;
for (int i = 1; i <= n; ++i)
arr[i - 1] = i;
std::partition_copy(arr.cbegin(), arr.cend(),
std::back_insert_iterator(odd), std::back_insert_iterator(even),
[](auto const & x){ return (x & 1) == 1; });
std::cout << "the even numbers are : " << std::endl;
for (auto element: even)
std::cout << element << " ";
std::cout << std::endl << "the odd numbers are : " << std::endl;
for (auto element: odd)
std::cout << element << " ";
}
Input:
10
Output:
the even numbers are :
2 4 6 8 10
the odd numbers are :
1 3 5 7 9
You only push one element - the first.
Your partitioning code is equivalent to
if(sort(arr , 0)){
even.push_back(arr[0]);
sort(arr , 1);
}else{
odd.push_back(arr[0]);
sort(arr,1);
}
You need to loop over all the input numbers.
You can also simplify matters with a more generally useful evenness function that doesn't depend on an array:
bool is_even(int x) { return x % 2 == 0; }
and then there is no need to store all the inputs before processing them:
int main(){
vector <int> even , odd;
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
if (is_even(x)) {
even.push_back(x);
}
else {
odd.push_back(x);
}
}
cout << "the even numbers are : " << endl;
for (auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for (auto element:odd){
cout << element << " ";
}
}

What should be the proper declaration of array while finding the largest number in array?

C++ This is my code in C++ for finding the largest number in array. When I was running in my IDE then there was no compilation error but it was not giving me output. I think the problem is in the declaration of array at line 8. I replaced the array declaration from line 8 to line 11 then it is working fine in my IDE. So I didn't get it that why the declaration of array was not working at line 8?
#include <bits/stdc++.h>
using namespace std;
int largest_in_array(int a[], int n);
int main() // main function
{
int n; // User will enter the size of array
int arr[n]; // Line 8
cout << "Enter the size of array: " << endl;
cin >> n;
// Line 11
cout << "\nEnter the elements of array: " << endl;
for (int i = 0; i < n; i++) // This loop will run for each element of array that user wants to enter
{
cout << "Enter the " << (i + 1) << " element:";
cin >> arr[i];
cout << endl;
}
cout << "Elements are: [";
for (int i = 0; i < n; i++) // Prints the elements of array
{
// cout << "Enter the " << (i + 1) << " element:";
cout << arr[i] << " ";
// cout << endl;
}
cout << "]";
int res = largest_in_array(arr, n); //Function call
cout << "\nLargest element in array is: " << arr[res] << endl;
return 0;
}
int largest_in_array(int a[], int n) // function that will return the index of largest element in array
{
int max = 0;
for (int i = 1; i < n; i++)
{
if (a[max] < a[i])
{
max = i;
}
}
return max;
}
You declare int arr[n]; before the user has entered a value into n. n has an indeterminate value when you read it and create arr.
You don't check that the user enters a positive value into n. Zero and negative sized arrays are not valid.
Other points:
bits/stdc++.h is not a standard header which makes your program not portable. Use the proper header files, like iostream etc.
arr[n] is a Variable Length Array (VLA) which is not part of standard C++. Make it a std::vector<int> arr(n); instead.
The use of std::endl is unnessesary. There is no need to flush the output streams here. Use \n instead.
Example:
#include <iostream>
#include <limits>
#include <vector>
int largest_in_array(const std::vector<int>& a) {
int max = 0;
for(int i = 1; i < a.size(); i++) {
if(a[max] < a[i]) {
max = i;
}
}
return max;
}
int main() // main function
{
int n; // User will enter the size of array
std::cout << "Enter the size of array:\n";
// check that input succeeds and that the value is valid
if(!(std::cin >> n) || n < 1) return 1;
std::vector<int> arr(n);
std::cout << "\nEnter the elements of array:\n";
for(int i = 0; i < n; i++)
{
std::cout << "Enter the " << (i + 1) << " element:";
if(!(std::cin >> arr[i])) {
std::cout << "invalid input, bye bye\n";
return 1;
}
}
std::cout << "Elements are: [";
for(int i = 0; i < n; i++)
{
std::cout << arr[i] << " ";
}
std::cout << "]";
int res = largest_in_array(arr); // Function call
std::cout << "\nLargest element in array is: " << arr[res] << '\n';
}
That said, you could however use the standard algorithm std::max_element instead of writing your own. It returns an iterator to the maximum element.
You could also make use of range-based for loop when you don't need to know the index in the array, as in your second loop.
Example:
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <limits>
#include <vector>
int main() {
int n; // User will enter the size of array
std::cout << "Enter the size of array:\n";
if(!(std::cin >> n) || n < 1) return 1;
std::vector<int> arr(n);
std::cout << "\nEnter the elements of array:\n";
for(int i = 0; i < n; i++) // This loop will run for each element of
// array that user wants to enter
{
std::cout << "Enter the " << (i + 1) << " element:";
if(!(std::cin >> arr[i])) {
std::cout << "invalid input, bye bye\n";
return 1;
}
}
std::cout << "Elements are: [";
for(auto value : arr) { // a range-based for loop
std::cout << value << ' ';
}
std::cout << "]\n";
auto res = std::max_element(arr.begin(), arr.end());
std::cout << "Largest element in array is: " << *res << '\n';
std::size_t index = std::distance(arr.begin(), res);
std::cout << "which has index " << index << '\n';
}
When you have int n on line 8 it is initialized when you use it to create the array. When n is initialized explicitly, it's value is undefined behavior. You may be creating an array larger than the n you inputted on line 10, resulting in the array having extra random junk, it may be smaller meaning your program read memory it really shouldn't, etc.

How to call a function to search an element an a 2D array?

I'm trying to get my homework done, but there is something is going wrong.
If a 2D array was in the main function, and I want to call a function, which its task is searching for an element in the 2D array, which the user enters the wanted element in the main function. If the wanted element was found, call a function to find its factorial then print the result in the main function, otherwise, call another function to show that the wanted element was not found.
I've tried the lines of code using Visual Studio 2019 as well as Dev C++.
My program does about 13 tasks which I organized them in a Switch Statement,
and the case of doing that task is Case number 9.
But once I enter the element I want to search in the console.
if the element existed in the array, the output always shows up like this:
"
Number 3 Found at position: 4
Factorial of 3 is: 6
3
"
whether the user entered 3 or else number.
Even if it was not found, the output is the same.
#include <iostream>
using namespace std;
// declaring a function to search within B1 array.
int search_B1(int[][3], int, int);
// declaring a function to find the fatorial of the found element.
int fact_num(int);
// declaring a function to print out a searching error.
void search_error();
// This is the main function. Program execution begins and ends here.
int main()
{
int B1[3][3], i, j;
cout << " - Please enter the elements of B1 array: \n";
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 3; j++)
{
cout << "B1[" << i << "]" << "[" << j << "] = ";
cin >> B1[i][j];
}
}
...
...
...
case 9:
{
int num;
cout << endl << " Enter the element to search in B1 array: ";
cin >> num;
cout << endl << search_B1(B1, 3, num) << endl;
break;
}
}
/**********************************************************************/
// This function is called when user inserts '9'
int search_B1(int B1[][3], int num , int)
{
int i, j, flag = 0;
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 3; j++)
{
if (num == B1[i][j])
{
flag = 1;
cout << " Number " << num << " Found at position: " << j + 1 << endl;
fact_num(num);
break;
}
}
}
if (flag == 0)
{
search_error();
}
return num;
}
/**********************************************************************/
// This function relates to ' search_B1 ' function.
int fact_num(int num)
{
int fact = 1, f;
for (f = 1; f <= num; f++)
{
fact *= f;
}
cout << " Factorial of " << num << " is: " << fact;
return fact;
}
/**********************************************************************/
// This function relates to ' search_B1 ' function.
void search_error()
{
cout << " The wanted number was not Found in the array!";
}
/**********************************************************************/
I expected the output of searching will be like this:
Example:
If the user entered the elements of the array as '1 2 3 4 5 6 7 8 9' and searched about the element '9'
IF THE WANTED ELEMENTS WAS FOUND:
the output will be :
"Number 9 Found at position: 4
Factorial of 9 is: 362880"
IF THE WANTED ELEMENTS WAS NOT FOUND:
the output will be :
"The wanted number was not Found in the array!"
You have undefined behaviour filling and searching the array
for (i = 1; i <= 3; i++) // B[3][j] is never an element
{
for (j = 1; j <= 3; j++) // B[i][3] is never an element
Array indices start from 0. If you want to display indices from 1, do arithmetic in the output
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
std::cout << "B1[" << (i + 1) << "]" << "[" << (j + 1) << "] = ";
std::cin >> B1[i][j];
}
}

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 !";
}

How To Change Multidimensional Array Size In Program?

Hey I was wondering how I could have settings in-game which would allow the user to set the size of the 'game-board' by changing the array values. Here is the code. I know the code is messy and over the place but it is my first program.
#include "stdafx.h"
#include "iostream"
#include "string"
#include "cstdlib"
#include "ctime"
int xRan;
int choicei = 17;
int choicej = 17;
const int row = 15;
const int col = 16;
int play = 0;
void fill(char Array[row][col]);
int main()
{
int play = 0;
char Array[row][col];
srand((unsigned int)time(0));
xRan = rand() % 15 + 1;
if (play == 0)
{
std::cout << "1. To Play Treasure Hunt!" << std::endl;
std::cout << "2. How To Play Treaure Hunt!" << std::endl;
std::cout << "3. Treaure Hunt Settings! (Comming Soon)\n" << std::endl;
std::cin >> play;
std::cout << "-----------------------------------------------------------------------" << std::endl;
}
if (play == 2)
{
std::cout << "1. Select a row number. Be sure to make it less than or equal to " << row << "!" << std::endl;
std::cout << "2. Select a column number. Be sure to make it less than or equal to " << col << "!" << std::endl;
std::cout << "3. If you see the 'X' you have won! If you see the 'O' you lose!" << std::endl;
std::cout << "-----------------------------------------------------------------------\n" << std::endl;
std::cin >> play;
}
if (play == 3)
{
std::cout << "\nComming Soon!" << std::endl;
std::cout << "-----------------------------------------------------------------------\n" << std::endl;
std::cin >> play;
}
while (choicei > row || choicej > col || choicei < 1 || choicej < 1)
{
std::cout << "\nEnter The Row Number Less Than Or Equal To " << row << "!" << std::endl;
std::cin >> choicei;
std::cout << std::endl;
std::cout << "Enter The Column Number Less Than Or Equal To " << col << "!" << std::endl;
std::cin >> choicej;
std::cout << "\n-----------------------------------------------------------------------" << std::endl;
if (choicei > row || choicej > row)
{
std::cout << "Make Sure The Row And Column Numbers Are Less Than Or Equal To " << row << "and" << col << "!\n" "---------------------------------------------------------------------- - " << std::endl;
}
if (choicei < 1 || choicej < 1)
{
std::cout << "Make Sure The Row And Column Numbers Are More Than Or Equal To 1" << "!\n" "-----------------------------------------------------------------------" << std::endl;
}
}
fill(Array);
std::cout << std::endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
std::cout << Array[i][j] << " ";
}
std::cout << std::endl;
}
if (xRan > 11)
{
std::cout << "\nCongratulations! You Won!\n" << std::endl;
}
else
{
std::cout << "\nBetter Luck Next Time!\n" << std::endl;
}
}
void fill(char Array[row][col])
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
Array[i][j] = '*';
}
}
if (xRan > 11)
{
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < col; j++)
{
Array[choicei - 1][choicej - 1] = 'X';
}
}
}
else
{
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < col; j++)
{
Array[choicei - 1][choicej - 1] = 'O';
}
}
}
}
Thank you in advance.
you can't do that with ordinary arrays. you should use dynamic arrays, for example std::vector http://www.cplusplus.com/reference/vector/vector/
Actually, what you want to do can be done in C, not in C++: C++ requires array dimensions to be compile time constants, C can use any runtime value.
If you stay in C++, you should take a look at vector<>. If, however, you choose to use C you can simply remove the const from the declaration of row and col.
You may find this answer useful. It lists several methods to create dynamic arrays.
Quoting the answer :
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard)
Based on the suggestions, here are some ways you could initialize it (ignoring how you take the input value) :-
vector<vector<char>> Array(row, vector<char>(col));
or
char **Array = new char*[row];
for(int i = 0; i < row; i++)
{
Array[i] = new char[col];
}
UPDATE
Based on the comments, I am adding how to use the vector method and use it with the function 'fill'. fill uses reference while fill_with_ptr makes use of pointer. Although I list both the methods, I strongly recommend the one using reference.
void fill(vector<vector<char> >& array);
void fill_with_ptr(vector<vector<char> >* array);
int main()
{
...
cin >> row;
cin >> col;
vector<vector<char> > Array(row, vector<char>(col));
...
fill (Array); // or fill_with_ptr(&Array);
}
void fill(vector<vector<char> >& array)
{
... // access elements as array[i][j]
}
void fill_with_ptr(vector<vector<char> >* array)
{
... // access elements as (*array)[i][j]
}