Dawid Irzyk - 9 months ago 41

C++ Question

I have big problem.

The task is:

Write a function in C ++ that takes a array of ints

`tab`

`n`

`k`

`true`

`tab`

`false`

For calls (record [] is an array):

`f ([123,4425,2224,222,55553], 5, 3)`

The function should return true. Since each of the numbers 123,4425,2224,222,55553 at least three digital

Calls for:

`f ([123,4425,2,222,5], 5, 2)`

The function should return false

Because there are a number, for example 2 which is a digital one and is less than 1 k = 2

My code :

`#include <iostream>`

int ile_cyfr(int a)

{

int temp=0;

do

{

a = a/10;

temp++;

} while(a>0);

return temp;

}

bool funkcja(int *tab, int n, int k)

{

bool stan = false;

for (int i=0; i<n; i++)

{

if (ile_cyfr(tab[i])<k)

{

stan = false;

if (stan == false)

{

return stan;

return 0;

}

}

else

{

stan = true;

return stan;

}

}

}

int main() {

using namespace std;

int n=0, k=0;

int *tab = new int[n];

cout << "Podaj ilosc liczb: " << endl;

cin >> n;

cout << "\nPodaj liczby: " << endl;

for (int i=0; i<n; i++) {

cin >> tab[i];

}

cout << "\nPodaj minimalna ilosc liczb: " << endl;

cin >> k;

cout << funkcja([444,856,671,321], n, k);

return 0;

}

The problem is that the line:

`cout << funkcja([444,856,671,321], n, k);`

Answer Source

For starters the function `funkcja`

is invalid. It returns true in case when the first element of the array has the number of digits greater than or equal to k. As I have understood you have to check that all elements of the array satisfy the condition.

The function can be written the following way

```
bool funkcja( const int *tab, int n, int k )
{
int i = 0;
while ( i < n && !( ile_cyfr( tab[i] ) < k ) ) i++;
return n != 0 && i = n;
}
```

As for this statement

```
cout << funkcja([444,856,671,321], n, k);
```

then it has an incorrect syntax.

You have to pass the variable `tab`

as the first argument of the function call. These values 444,856,671,321 should be assigned to elements of the array pointed to by the pointer `tab`

.

Thus write

```
cout << funkcja( tab, n, k );
```