r/programminghelp • u/vaslui-berceni • Mar 02 '21
C++ A simple fill() algorithm.
Hello. I am a newbie programmer and I need help. This algorithm is supposed to give a number of the 0s next to "a[l][c]". My teacher taught me this and I added the a[l][c]=1 because without that it called the function indefinitly and basically gave no answer. It still does not work. Can somebody help me? (suma means sum)
#include <iostream>
int suma, a[20][20], n, l, c;
using namespace std;
void fill()
{
suma++;
cout << "Suma has increased" << endl;
l--;
if (l > 0 && a[l][c] == 0)
{
a[l][c] = 1;
fill();
cout << "a[" << l << "][" << c<<"] has become 1" << endl;
}
l = l + 2;
if (l < n - 1 && a[l][c] == 0)
{
a[l][c] = 1;
fill();
cout << "a["<<l<<"]["<<c<<"] has become 1"<<endl;
}
l--;
c--;
if (c > 0 && a[l][c] == 0)
{
a[l][c] = 1;
fill();
cout << "a[" << l << "][" << c<<"] has become 1" << endl;
}
c = c + 2;
if (c < n + 1 && a[l][c] == 0)
{
a[l][c] = 1;
fill();
cout << "a[" << l << "][" << c<<"] has become 1" << endl;
}
c--;
}
int main()
{
int i, j;
cin >> n;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
cout << "a[" << i << "][" << j << "]= ";
cin >> a[i][j];
}
cout << endl;
}
cin >> l >> c;
suma = 0;
if (a[l][c] == 0)
fill();
cout << suma;
}
1
u/jedwardsol Mar 02 '21
array indices start at 0, not 1.
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
cout << "a[" << i << "][" << j << "]= ";
cin >> a[i][j];1
u/vaslui-berceni Mar 02 '21
Why would they? At class it always started at 1.
1
u/jedwardsol Mar 02 '21
Why would they?
Because they do.
If you have an array
int array[20];Then the indices are numbered 0 to 19
And the correct way to loop is
for(int i=0; i < 20; i++) { array[i] = 0;1
u/vaslui-berceni Mar 02 '21
I mean is it not the same thing if I write "for(i=0;i<=n-1;i++)"?
1
u/jedwardsol Mar 02 '21
Not it is not the same.
The loop in your post will access elements 1 to 20
The loop in the comment will access elements 0 to 19
The array has no element 20, so the loop in the post is wrong.
1
u/BanishDank Mar 02 '21
Is this beginner stuff? What language is this? As someone who has a little experience in Java only, this looks completely crazy haha. The if statements and array part, I can get behind, but there seems to be a lot of syntax and different ways to do stuff, that looks alien to me..
2
u/[deleted] Mar 02 '21
I believe /u/jedwardsol found your issue, and please, the next time you post, follow the rules. Specifically Rule #2 in this case.