Finding evens in an array - c++

I'm writing a program that is made of a function that takes in a 2d array, c0unts the evens in the array and returns the amount of evens in that array. The function isn't returning the value that i intend it to, which is 6. Sometimes I get 0, sometimes I get a number like 2147483646.
#include <iostream>
#include <array>
using namespace std;
const int MaxNumOfRows = 3;
const int MaxNumOfColumns = 2;
int Even(int A[MaxNumOfRows][MaxNumOfColumns], int length, int width)
{
int NumnberOfEvens = 0;
int i;
int j;
for (i = 0; i < length; length++)
{
for (j = 0; j < width; width++)
{
if (A[i][j] % 2 == 0)
{
NumnberOfEvens++;
}
}
}
return NumnberOfEvens;
}
int main()
{
//int output = 0;
int A[MaxNumOfRows][MaxNumOfColumns] =
{
{2,2},{2,4},{2,2}
};
Even(A, MaxNumOfRows, MaxNumOfColumns);
//output = Even(A, MaxNumOfRows, MaxNumOfColumns);
cout << Even(A, MaxNumOfRows, MaxNumOfColumns) << endl;
system("pause");
return 0;
}

Check those for loops, I imagine you want to be incrementing the variables ++i and ++j rather than width++ and length++.
With an example this trivial, I imagine stepping through the executing code and finding the problem in a debugger would be pretty straightforward...are you writing this using an IDE with a debugger?

You are not applying increment on loop variables ('i' and 'j') here. 'length' and 'width' are increasing (due to length++, width++) whereas 'i' and 'j' are not. So, loop won't stop and thus the garbage values.
for (i = 0; i < length; length++)
{
for (j = 0; j < width; width++)
{
if (A[i][j] % 2 == 0)
{
NumnberOfEvens++;
}
}
}
This must work.
for (i = 0; i < length; i++)
{
for (j = 0; j < width; j++)
{
if (A[i][j] % 2 == 0)
{
NumnberOfEvens++;
}
}
}

Related

error request for member .. in .. which is of non-class type - C++

I have got this error: "error: request for member 'nume' in 'tablou[j]', which is of non-class type ' [100]'", and I don't really know how to solve it.I tried searching on youtube and google but I found nothing .Does anyone have any ideas for how to solve this?
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct{
int counter;
char nume[20] = " ";
}tablou[10][100];
int main()
{
int n, counter = 0;
char second[10][100];
bool verify = true;
cout<<"Cate nume?";
cin>>n;
for(int i = 0; i <= n; i++)
{
cin.getline(second[i],20);
}
for(int i = 0; i <= n; i++)
{
verify = true;
for(int j = 0; j < i; j++)
{
if(strcmp(second[i], tablou[j].nume) == 0)
{
verify = false;
}
}
if(verify == true)
{
strcpy(tablou[i].nume, second[i]);
for(int k = 0; k < n; k++)
{
if(strcmp(tablou[i].nume, second[k]))
{
tablou[i].counter++;
}
}
}
}
for(int i = 0; i <= n; i++)
{
cout<<tablou[i].nume<<" "<<tablou[i].counter<<endl;
}
return 0;
}
tablou is a 2d array
struct{
int counter;
char nume[20] = " ";
}tablou[10][100];
its elements are tablou[x][y]
you try to access an element with only one index
if(strcmp(second[i], tablou[j].nume) == 0)
----------------------------^
I do not know what your code is trying to do , but thats why you get the error
The array tablou is a two-dimensopnal array
struct{
int counter;
char nume[20] = " ";
}tablou[10][100];
So for example the expression tablou[j] has the array type the_unnamed_structure[100].
So such an expression like this
tablou[j].nume
is incorrect and the compiler issues an error.
Maybe actually you mean the following declaration of the array
struct{
int counter;
char nume[20] = " ";
}tablou[10];
Also in these loops
for(int i = 0; i <= n; i++)
{
verify = true;
for(int j = 0; j < i; j++)
{
if(strcmp(second[i], tablou[j].nume) == 0)
{
verify = false;
}
}
if(verify == true)
{
strcpy(tablou[i].nume, second[i]);
for(int k = 0; k < n; k++)
{
if(strcmp(tablou[i].nume, second[k]))
{
tablou[i].counter++;
}
}
}
}
some elements of the array tablou can be skipped if verify is set to false because you are using the index i to assign elements of the array tablou. That is the number of actual elements of the array tablou can be less than n. In this case this for loop
for(int i = 0; i <= n; i++)
{
cout<<tablou[i].nume<<" "<<tablou[i].counter<<endl;
}
will invoke undefined behavior because the data member counter will be uninitialized for some outputted elements of the array.
You need to support a separate variable as an index in the array tablou.

Why isnt printing?

My screen isn't printing please help me with this.I'm a beginner and i'm trying to make snake game.
void myScreen()
{
char screen[30][50];
int x = 30, y = 50;
for (int i = 1; i <= x; i++)
{
if (i == 1 || i == x)
for (int j = 1; j <= y; j++)
screen[i][j] = '#';
else
for (int j = 1; j <= y; j++)
if (j == 1 || j == y)
screen[i][j] = '#';
else
screen[i][j] = ' ';
}
for (int i = 1; i <= x; i++)
{
for (int j = 1; j <= y; j++)
cout << screen[i][j];
cout << endl;
}
}
the screen isn't printing
C++ arrays are zero-based. That means that the "first" element has actually the index 0. So your code like that:
for(int i=1;i<=x;i++)
shall be reworked like that:
for (int i = 0; i < x; i++)
Now back to your question: why it isn't printing? The fact is that you are accessing the memory outside of the array, and that is an Undefined Behavior in C++. That may be observed as the program that never gets to the code that prints the array.
The reason it becose you don't call the funtion in main()
here how to do it:
int main(){
myScreen();
}
the int main() is when the program is starting.after you can call other functions
They have other reason like you don't import any libraries
#include <iostream>
using namespace std;
add this in the start of your code
You are missing a main function in your code. In C++ (and C), the main function gets called when you start the program. All other functions that you want to be executed you have to call from this function. Additionally, you start counting your array indexes from 1 - but the first element of an array has 0 as index in most programming languages (including C, C++, Python, JavaScript, bash, …, …). This code should work:
#inclue <iostream>
using namespace std;
void myScreen()
{
int x = 30, y = 50;
char screen[x][y];
for (int i = 0; i < x; i++)
{
if (i == 0 || i == x - 1)
{
for (int j = 0; j < y; j++)
{
screen[i][j] = '#';
}
} else
{
for (int j = 0; j < y; j++)
{
if (j == 1 || j == y)
{
screen[i][j] = '#';
} else
{
screen[i][j] = ' ';
}
}
}
}
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
cout << screen[i][j];
}
cout << endl;
}
}
int main(int argc, char* argv[]) {
myScreen();
}

Permutations Program Unable to Write to Array - Runtime Error

I'm working on a program that will display all possible permutations for an array, and then store the unique permutations in another array, however I am having issues with storing the unique permutations. I was going through my code and was getting a few errors because I had created the uniquePermutations variable and hadn't initialized. After trying to access the variable the program would crash so then I tried setting it equal to nullptr which helped.
So now when I use my copyUniquePermutations function (which is called in the permute function, it checks to see if the array is empty with nullptr and then if it is, we declare 3 new arrays, and set each spot equal to NULL so that we won't get any undefined behavior. Then next, I check to see if any spots are NULL so that we won't get to the equalArrays function which may cause issues and then we get to the assignment part which causes issues. Since we assigned newArray[i] to be NULL why does the computer say that it is having issues writing to this spot?
#include <iostream>
using namespace std;
int permutations[] = { 2, 1, 2 };
void swap(int &x, int &y)
{
int temp;
temp = x;
x = y;
y = temp;
}
bool equalArrays(int array1[], int array2[], int size)
{
for (int i = 0; i < size; i++)
if (array1[i] != array2[i]) return false;
return true;
}
void copyUniquePermutations(int oldArray[], int *newArray[])//This is the function that is causing issues
{
for (int i = 0; i < 3; i++)
{
if (newArray == nullptr)
{
newArray = new int*[3];
for (int j = 0; j<3; j++)
newArray[i] == NULL;
}
if (newArray[i] == NULL || !equalArrays(oldArray, newArray[i], 3))
{
for (int j = 0; j < 3; j++)
newArray[i][j] == oldArray[j];
}
}
}
void permute(int permutations[], int *uniquePermutations[], int l, int r)
{
int i;
if (l == r)
copyUniquePermutations(permutations, uniquePermutations);
else
{
for (i = l; i <= r; i++)
{
swap((permutations[l]), (permutations[i]));
permute(permutations, uniquePermutations, l + 1, r);
swap((permutations[l]), (permutations[i]));
}
}
}
int main()
{
int **uniquePermutations = nullptr;
permute(permutations, uniquePermutations, 0, 2);
for (int i = 0; i < 3 ; i++)
delete[] uniquePermutations[i];
delete[] uniquePermutations;
return 0;
}
I think here you need to have j in newArray[j]
for (int j = 0; j<3; j++)
newArray[i] == NULL;

The following Code does not give any response on Stdout

This code is supposed to calculate the frequency of maximum number in an array I.E the number of times the highest number in the array has occured unfortunately this code does not display any output:-
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int birthdayCakeCandles(int n, int a[]){
int j=0,max,count=0;
max = a[j];
while(j<n){
if(a[j+1]> max){
max = a[j+1];
j++;
}
}
int seen[n];
for(int i = 0; i < n; i++)
seen[i] = 0;
for(int i = 0; i < n;i++) {
if(seen[i] == 0) {
int count = 0;
for(int j = i; j < n;j++)
if(a[j] == a[i] && a[i] == max)
count += 1;
seen[j] = 1;
}
}
return count;
}
int main() {
int i,n;
cin >> n;
int a[n];
for(i = 0; i < n; i++){
cin >> a[i];
}
int result = birthdayCakeCandles(n, a);
cout << result << endl;
return 0;
}
Your program never stops, because your maximum finding loop is for n > 0 endless. Your loop in birthdayCakeCandles should be changed to:
while (j < n)
{
if (a[j + 1] > max)
{
max = a[j + 1];
}
j++;
}
Also consider using more readable coding style and please read this.
In addition to the bug found by vasek, you made at least another mistake in the (overcomplicated) following loops, where you are trying to count the occurences of the maximum value.
// I've kept OP's indentation on purpose...
int seen[n]; // <-- Variable Length Arrays are not standard in C++
for(int i = 0; i < n; i++)
seen[i] = 0;
for(int i = 0; i < n;i++) {
if(seen[i] == 0) {
int count = 0;
for(int j = i; j < n;j++)
if(a[j] == a[i] && a[i] == max)
count += 1;
seen[j] = 1; // <-- misleading indentation, this is always executed
// no matter what the condition is
}
}
While all you need to do, once you have found the maximum value, is:
int count = 0;
for( int i = 0; i < n; ++i ) {
if( a[i] == max )
++count;
}
As a matter of fact (unless you want to create a function operating on an array for other reasons), you don't need any array (or std::vector) at all to complete your assignment. This code will perform the same task:
#include <iostream>
#include <limits>
int main()
{
int n;
std::cin >> n;
int x,
max = std::numeric_limits<int>::min();
int count = 0;
for ( int i = 0;
i < n && std::cin >> x;
++i )
{
if ( x >= max )
{
if ( x > max )
{
max = x;
count = 1;
}
else
{
++count;
}
}
}
std::cout << count << '\n';
}

SIGABRT (signal 6) error in finding majority element in array using divide and conquer

I checked SO and saw two issues dealing with the same problem statement. However, neither of them contained what I'm looking for. The task is to output 1 if an array with n elements contains an element that occurs more than n/2 times, using a divide and conquer strategy.
I developed what I think is a working solution based on the fact that the base case is a sub array with one element that is (obviously) the majority element in the subarray. I then proceed to compare these majority elements across subarrays, asking if ultimately they happen more than n/2 times.
For more details, see https://classes.soe.ucsc.edu/cmps102/Fall01/solutions4.pdf (Problem 4)
I wrote two different solutions to this problem, one using a very naive O(n^2) algorithm to check if my solution was correct for all cases, and one attempting to implement the algorithm described in the link above.
Inside main, I stress test my solution against the obviously correct but naive one. However, upon running this I'm getting a SIGABRT (signal 6) error. My debugger tells me to check for malloc, object was probably modified after being freed.
Now I can't tell whether or not my solution is correct. I really don't know what's going on with bad allocation, I'm relatively new to C++.
Code goes below:
#include <algorithm>
#include <iostream>
#include <vector>
using std::vector;
int get_majority_element(vector<int> &a, int left, int right) {
int m;
int majority_left, majority_right; // majority element in either sub array
int count_right = 0, count_left = 0; // count for above
int leftt, rightt; // endpoints
if (a.size() == 1) {
return a[0];
}
else {
m = (left + right)/2; // calculate mid point
vector<int> b_left(m);
vector<int> b_right(right - m);
// get left sub array
for (int i = 0; i < m; i++) {
b_left[i] = a[i];
}
// set new endpoints
leftt = 0;
rightt = m;
majority_left = get_majority_element(b_left, leftt, rightt);
for (int i = 0; i < right - m + 1; i++) {
b_right[i] = a[m+i];
}
leftt = m;
rightt = right - m + 1;
majority_right = get_majority_element(b_right, leftt, rightt);
// if there is a majority element, count its frequency
if (majority_left != -1) {
for (int i = 0; i < a.size(); i++) {
if (a[i] == majority_left)
count_left++;
}
}
if (majority_right != -1) {
for (int i = 0; i < a.size(); i++) {
if (a[i] == majority_right)
count_right++;
}
}
// if both elements in sub arrays are majority and they're different, there is no majority element
if (count_left == count_right && majority_left != majority_right) {
return -1;
}
// check if either sub array has a majority element that occurs more than n/2 times
else if (count_right > count_left && count_right > a.size()/2) {
return majority_right;
}
else if (count_left > count_right && count_left > a.size()/2){
return majority_left;
}
}
return -1;
}
int get_majority_fast(vector<int> &a, int left, int right){
std::reverse(a.begin(),a.end());
int current = 0;
int count;
for (int i = 0; i < a.size(); i++) {
current = a[i];
count = 0;
for (int j = 0; j < a.size(); j++) {
if (a[j] == current)
count ++;
}
if (count > a.size()/2)
return 1;
}
return -1;
}
int main() {
// std::cin >> n;
// vector<int> a(n);
// for (size_t i = 0; i < a.size(); ++i) {
// std::cin >> a[i];
// }
// std::cout << (get_majority_fast(a, 0, a.size()) != -1) << '\n';
while(true){
int one, two;
int n = rand() % 100 ;
std::cout << n << "\n";
vector<int> a;
for (int i = 0; i < n; ++i) {
a.push_back(rand() % 100);
}
one = get_majority_element(a, 0, a.size());
two = get_majority_fast(a, 0, a.size() != -1);
if (one != two) {
std::cout << "Wrong answer: " << one << ' ' << two << "\n";
break;
}
else {
std::cout << "OK\n";
}
}
}
There was effectively an out of bounds error in one of the loops. Corrected loop is below:
for (int i = m; i < right - m ; i++) {
b_right.at(m-i) = a.at(m + i);
}
I thought the weird SIGABRT error was due to something arcane. Guess I learned to use x.at()
Also, I had a couple other mistakes. Full corrected code is below:
#include <algorithm>
#include <iostream>
#include <vector>
using std::vector;
int get_majority_element(vector<int> &a, int left, int right) {
int m;
int majority_left = -1, majority_right = -1; // majority element in either sub array
int count_right = 0, count_left = 0; // count for above
int new_left, new_right; // endpoints
if (a.size() == 1) {
return a[0];
}
else {
m = (a.size())/2; // calculate mid point
vector<int> b_left(m);
vector<int> b_right(right - m);
// get left sub array
for (int i = 0; i < m; i++) {
b_left.at(i) = a.at(i);
}
for (int i = 0; i < a.size() - m ; i++) {
b_right.at(i) = a.at(i + m);
}
// set new endpoints
new_left = 0;
new_right = m;
majority_left = get_majority_element(b_left, new_left, new_right);
new_left = m;
new_right = right - m;
majority_right = get_majority_element(b_right, new_left, new_right);
// if there is a majority element, count its frequency
if (majority_left != -1) {
for (int i = 0; i < a.size(); i++) {
if (a[i] == majority_left)
count_left++;
}
}
if (majority_right != -1) {
for (int i = 0; i < a.size(); i++) {
if (a[i] == majority_right)
count_right++;
}
}
// if both elements in sub arrays are majority and they're different, there is no majority element
if (count_left == count_right && majority_left != majority_right) {
return 0;
}
else if (count_left == count_right)
return majority_left;
// check if either sub array has a majority element that occurs more than n/2 times
else if (count_right > count_left && count_right > a.size()/2) {
return majority_right;
}
else if (count_left > count_right && count_left > a.size()/2){
return majority_left;
}
// majority element in sub arrays isn't majority in array
else
return 0;
}
}
int get_majority_fast(vector<int> &a, int left, int right){
std::reverse(a.begin(),a.end());
int current = 0;
int count;
for (int i = 0; i < a.size(); i++) {
current = a[i];
count = 0;
for (int j = 0; j < a.size(); j++) {
if (a[j] == current)
count ++;
}
if (count > a.size()/2)
return 1;
}
return -1;
}
int main() {
int n;
std::cin >> n;
vector<int> a(n);
for (size_t i = 0; i < a.size(); ++i) {
std::cin >> a[i];
}
int result;
int out;
result = get_majority_element(a, 0, a.size());
if (result != 0)
out = 1;
else
out = 0;
std::cout << out << '\n';
}
I'm sure I could make it a lot prettier but right now I don't want to hear about this for a while.