Check if a number appears in an array C++ - c++

I took a coding sample test and I think it's really easy. They ask to find if a number appears in the array (print out YES) or not (print out NO). At first, I want come up with binary search method. But when I see their given function, I think it's not suitable to use that method.
In the description, they mention arr[] and k as the number we need to check if k appears in arr[].
char* findNumber(int arr_count, int arr[], int k)
{
int n = sizeof(arr)/sizeof(arr[0]);
for(arr_count = 0; arr_count < n; arr_count++)
{
if(arr[arr_count]==k)
cout<<"YES";
else
cout<<"NO";
}
return 0;
}
But when I compiled, it showed the output is null. I don't know why? I solved many more difficult problems. So I feel so bad when I got error in an easy task like this. Please tell me the wrong part.

Here
char* (int arr_count, int arr[], int k) { }
Compiler changes int arr[] into int *arr that's because of array decaying. So when you do
int n = sizeof(arr)/sizeof(arr[0]);
sizeof(arr) will be size of int* and n is always 1.
Hence this
for(arr_count = 0; arr_count < n; arr_count++) {
/* some stuff */
}
iterates only once.

int n = sizeof(arr)/sizeof(arr[0]);
At least this is incorrect, as your array arr decays to a pointer when passing it to function.
So sizeof(arr)/sizeof(arr[0]) is actually sizeof(pointer)/sizeof(int). And so n is always 1. And your for loop always runs for one iteration only (when arr_count == 0).
for(arr_count = 0; arr_count < n; arr_count++)
This is also incorrect - as you are not supposed to modify arr_count which is the input array size. You should use a separate variable for the loop.
for( int i = 0; i < arr_count; ++i )

#include<iostream>
const char* findNumber(int arr_count, int arr[], int k)
{
for(int i = 0; i < arr_count ; i++)
{
if(arr[i]==k)
return "YES";
}
return "NO";
}
int main()
{
int array[] = { 2,36,42,8,85,35,225,100};
std::cout << findNumber(sizeof(array)/sizeof(array[0]),array,43) << std::endl;
std::cout << findNumber(sizeof(array)/sizeof(array[0]), array, 85) << std::endl;
return 0;
}
there you go. fixed and working fine. outputs NO and then YES.

Related

c++ Increase pointer size without return new pointer

My teacher has me complete this(the main is hidden) and i wonder why i got an infinite loop with this solution.
Task:
Complete this function:
void pad_left(char *a, int n) {
}
// if length of a greater than n, do nothing
// else insert '_' util a 's length is n
Some case i got an segmentfault
I try realloc but it return new ptr
My solution
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
void printChar(char *a) {
int i = 0;
while(a[i] != '\0') cout << a[i];
cout << endl;
}
void insert_begin(char *a, int n) {
for(int i = n; i > 0; i--) {
a[i] = a[i-1];
}
a[n+1] = '\0';
}
void pad_left(char *a, int n) {
int len = n - strlen(a);
for(int i = 0; i < len; i++) {
insert_begin(a, strlen(a));
}
}
Here is full code
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
void printChar(char *a) {
int i = 0;
while(a[i] != '\0') cout << a[i];
cout << endl;
}
void insert_begin(char *a, int n) {
for(int i = n; i > 0; i--) {
a[i] = a[i-1];
}
a[n+1] = '\0';
}
void pad_left(char *a, int n) {
int len = n - strlen(a);
for(int i = 0; i < len; i++) {
insert_begin(a, strlen(a));
}
}
int main() {
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
char a[5] = "test";
pad_left(a, 10);
printChar(a);
return 0;
}
Okay, you need some background information.
void pad_left(char *a, int n) {
}
char a[5] = "test";
pad_left(a, 10);
This is going to be a significant problem. First, you can't realloc for two reasons. First, char a[5] is a fixed array -- not an allocated array. When you pass it to pad_left, that doesn't change. realloc() does a free of the old pointer, but you can't do that, and it will cause problems. So you cannot use realloc in your solution unless you make sure the strings came from allocated memory. And you can't assume that.
So put realloc aside. You can't use that.
Next, char a[5] only allocates 5 bytes. If you start writing beyond that range (by passing in 10 to your method), you're going to step on other places. This is absolutely bad.
So... Without testing it, the rest of your code seems reasonable. You can probably get a good test if you do this:
char a[100] = "test";
pad_left(a, 10);
You'll have allocated plenty of space for padding. Try this and see if you get further.

If statement is not accessing the value of an array (using the index) when evaluating the expression

I am supposed to be creating a program that asks a user to populate an array of size 10. There are three functions which by their name are self-explanatory; one fills up the array with elements, the second one displays the array horizontally, and the third function checks to see if a number entered by the user is an element in the array.
#include<iostream>
#include<iomanip>
void fillUpArray(int array[], int size);
void displayArray(int array[], int size);
bool isNumberPresent(int array[], int size, int SearchNum);
int main(){
int s = 10; //size of array
int A[s]; //array A with size s
int num; //search number
fillUpArray(A, s);
std::cout <<"\n";
displayArray(A, s);
std::cout << "\n";
std::cout << "Enter a number to check if it is in the array:\n";
std::cin >> num;
std::cout << std::boolalpha << isNumberPresent(A, s, num) << std::endl;
return 0;
}
void fillUpArray(int array[], int size)
{
std::cout << "Enter 10 integers to fill up an array, press enter after every number:\n";
for(int i = 0; i < size; i++){
std::cin >> array[i];
}
}
void displayArray(int array[], int size)
{
for(int j = 0; j < size; j++){
std::cout << array[j] << "\t";
}
}
bool isNumberPresent(int array[], int size, int SearchNum)
{
bool isPresent;
for(int k = 0; k < size; k++){
if(array[k] == SearchNum)
isPresent = true;
else
isPresent = false;
}
return isPresent;
}
That last function, which is a bool function, is not performing the way I thought it would. I thought by doing array[k] whatever index k is then it should spit out the element in the array and then with the expression if(array[k] == SearchNum) it should then work as if(element == SearchNum) but that doesn't seem to be the case and the output is always false.
The for loop in your isNumberPresent function will run to the end of the array (until k equals size) unconditionally; in each run of that loop, you set the value of the isPresent variable according to whether or not the current element is a match for searchNum, overwriting the previous value. So, the function, as it stands, will simply return whether or not the last element in the array is the same as the given test number.
You can simplify that function and remove the need for the local variable: if you find a match, then return true immediately; if the loop ends without finding a match, then return false:
bool isNumberPresent(int array[], int size, int SearchNum)
{
for(int k = 0; k < size; k++){
if(array[k] == SearchNum) return true; // Found a match - we can return immediately
}
return false; // We didn't find a match
}
Note, also, that Variable Length Arrays (VLAs) are not part of Standard C++, though some compilers (like GNU g++) support them (they are part of the C language according to the C99 Standard). In your program, as you only use one (fixed) value for the array size, you can conform to Standard C++ simply by qualifying that s is a const:
int main()
{
const int s = 10; //size of array - make this a "const" be 'proper' C++
int A[s]; //array A with size s
//...

Function and Array in C++: Unexpected output

I need some help here please.
I just started learning C++ (coming from Python background).
I'm trying to familiarize myself with arrays and functions. Wrote a bunch of functions to do as stated, above each one.
However, the function which is supposed to sum elements in an array and return their sum, seem to be adding 10 to the result, no matter the argument supplied as input. What am I doing wrong please, as I can't seem to find this out. Any help on general layout of my code also would be appreciated.
// WORKING WITH ARRAYS AND FUNCTIONS
#include<iostream>
using namespace std;
// FUNCTION TO INSTANTIATE ARRAY INT OF LENGTH N.
int* array_creator(int n)
{
static int ary_of_ten[10]; //declare array
for (int i=0; i<n; i++) //use loop to fill it up
{
ary_of_ten[i] = i+1;
}
return ary_of_ten;
}
//FUNCTION TO PRINT ARRAY ELEMENTS
void* array_printer(int arr[], int array_lenght)
{
for (int i=0; i<array_lenght-1; i++)
{
cout << arr[i] << " ";
}
cout << arr[array_lenght-1] << endl;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS ARRAY OF SQUARE OF EACH ELEMENT
int* square_array(int *p, int array_length)
{
const int ary_sz(array_length);
static int sqd_values[10];
for (int i=0; i<ary_sz; i++)
{
*(sqd_values + i) = *(p+i) * *(p+i);
}
return sqd_values;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS SUM OF ITS ELEMENTS
int sum_array(int *arry, int array_length)
{
int summation;
for(int i=0; i<array_length; i++)
{
summation += *(arry + i);
}
return summation;
}
int main()
{
cout << sum_array(array_creator(10), 3) << endl;
array_printer(array_creator(10), 10); //print array of 1-10 elements
array_printer(square_array(array_creator(10), 10), 10); //prt arry of sqrd values
return 0;
}
summation shuld be initialized to 0.
int summation=0;

Variables being affected by 'bad' instructions

Below is my code, for solving problem 7 of PE ("find the 10001th prime"):
#include <iostream>
using namespace std;
bool isPrime(int n, int primes[], int l){
int i=0;
for (int i=0; i < l; i++){
if (primes[i] != 0 && n%primes[i] == 0){
return false;
}
}
return true;
}
int main()
{
int k=3;
int primes[10001] = {0};
primes[0]=2;
const int l=sizeof(primes)/sizeof(primes[0]);
int N=0;
while (N < l){
if(isPrime(k, primes, l)==true){
primes[++N]=k;
}
k+=2;
}
cout << primes[l-1] << endl;
return 0;
}
This code solves the problem, but there is a mistake in it: on the final iteration of the while loop, the instruction is to set primes[10001]=k;, which attempts to change a value of an element of an array that doesn't exist. If I don't declare it to be constant, and (as a means of troubleshooting) replace l by 10001 in the while loop, the value of l becomes equal to the 10002th prime at the end of the loop.
Here is the main function part of this happening:
int main()
{
int k=3;
int primes[10001] = {0};
primes[0]=2;
int l=sizeof(primes)/sizeof(primes[0]);
int N=0;
while (N < l){
if(isPrime(k, primes, 10001)==true){
primes[++N]=k;
}
k+=2;
}
cout << l << endl;
return 0;
}
My question is, why does this happen? I do know that a simple fix is to stop the loop at l-1 (or better, initialize with N=1 instead and increment N after), but I'm more interested in how this code can affect a variable that isn't being explicitly (directly?) involved in the bad part of the code.
Thank you!
The [] Operator does no bounds checking. some_array[102], will simple go 102 * sizeof(type) if thats outside your array, thats outside your array. C++ won't care.
These are some of the nastiest bugs that can generated if you are lucky you program will crash, sometimes you can just end up changing somebody else's variable.
Which is why I harp on at work about using std::array and std::vector alot because they come with .at(i) functions which have bounds checking.

Modifying a dynamic 2D array in a function

I've got a function that accepts a dynamic multidimensional array (which is initialized to 0) as a parameter, and I'm trying to modify certain values within the array in my function.
The function that accepts the array as a parameter is supposed to simulate the roll of two dice and output the frequency distribution to the array I made that's initialized to zero.
The code for it is as follows:
#include <iostream>
#include <cstdlib>
using namespace std;
int** rollDie(int numRolls, unsigned short seed, int** &rollarray)
{
srand(seed);
int side1, side2;
while (numRolls > 0)
{
side1 = 1 + rand() % 6;
side2 = 1 + rand() % 6;
rollarray[side1][side2]++;
numRolls--;
}
return rollarray;
}
int** initializeArray(void)
{
int i, j;
int** m = new int*[6];
for (i = 0; i < 6; i++)
m[i] = new int[6];
for (i = 0; i < 6; i++)
for (j = 0; j < 6; j++)
m[i][j] = 0;
return m;
}
int main()
{
int numRolls;
unsigned short seed;
int ** a = initializeArray();
cout << "rolls?\n";
cin >> numRolls;
cout << "seed?\n";
cin >> seed;
int ** b = rollDie(numRolls, seed, a);
int i,j;
for (i = 0; i < 6; i++) {
for (j = 0; j < 6; j++) {
cout << b[i][j];
}
cout << "\n";
}
}
Code works for me with just a few issues (I had to guess how you defined a. Next time add that too):
In the printing you should print a space after every number (minor)
In the random, you choose index as 1+rand()%6, so from 1 to 6, but when you print you take indexes from 0 to 5! So your first row and first column will be 0.
Other than that it seems to work.
Only when one goes and does something else does the answer come to mind. I suspect you declared a as:
int a[6][6];
which is an array of 36 integers. In your function, though, you're declaring rollarray to be a pointer to an array of pointers to integers. All you need to do is change the function signature to:
int* rollDie(int numRolls, unsigned short seed, int* rollarray)
As cluracan said, you also want to use array indices in the range 0 to 5.
This is a good case for either the judicious use of print statements or stepping through with a debugger to see what's really going on.