Hello programmers,
The code below is a function to find the first '1' in an array. i think the ptr in firstOne() does not pass to main() and it says p in main() is not initialized. what should I change in void function when letting main remain the same?
void firstOne(int arr[], int n, int* ptr)
{
ptr = nullptr;
for (int k = 0; k < n; k++)
{
if (arr[k] == 1)
{
ptr = arr + k;
break;
}
}
}
int main()
{
int arr[6] = { 5, 11, 4, 0, 0, 7 };
int* a;
firstOne(arr, 6, a);
if (a == nullptr)
{
cout << "no 1's in the array" << endl;
}
else
{
cout << "the address of the first 1 is " << a << endl;
cout << "at index " << a - arr << " of the array" <<endl;
}
return( 0 );
}
#include <iostream>
int main()
{
int arr[] = { 5, 11, 4, 0, 1, 7 };
bool match = false;
for (size_t i = 0; i < sizeof(arr)/sizeof(arr[0]); ++i)
{
if (arr[i] == 1)
{
std::cout << "First 1 in the array is at location " << i + 1 << "\n";
match = true;
break;
}
}
if(match == false)
{
std::cout << "No 1 in the array \n";
}
}
I assume you already know to use #include <iostream> and using namespace std; if you do not want to use std::cout during your code.
An easier way is having a for / while loop to go through the indexes and have if (arr[i] = 1){...} .
I think someone else has already wrote this in their code.
Another tip that might help, you can get the size of an array without knowing the number of elements in the set.