Hi. I have another BAC problem that left me with no ideas, the last one on the paper.
So there is this subprogram sub which has 3 parameters:
-an array, int v[100]
-int n<=100 (number of elements from the array)
-int a
sub returns the number of elements in the array that are equal with a
I had to write sub, and then a program in which you cin>>n and also cin>>(n numbers) and using sub, it must display "YES" if any two consecutive numbers entered are equal, or display "NO" in the other case. Here is what I did:
#include <iostream>
usingnamespace std;
int sub (int v[],int n, int a)
{ int i, c=0;
for(i=1;i<=n;i++)
if(v[i]==a)
c++; //c is the counter, any time the program finds an element from the array equal to a, one unit is added to the counter
return c;
}
main ()
{
int v[100],n,i;
cin>>n;
for(i=1;i<=n;i++)
cin>>v[i];
if(sub(v[i],n,v[i+1])>0) //HERE IS THE PROBLEM!!!
cout<<"\n NO";
else
cout<<"\n YES";
}
I marked the spot where I get the error. I know what's wrong in sub(v[i],n,v[i+1]), but I wrote that anyway to show you the idea that would work for doing what the exercise asks, it's just not the right form.
I'm using codeblocks (mingw). As for subprograms, I've translated directly from my native language, I'll use functions from now on.
Using sub function is necessary.
@vlad It doesn't work. The problem with your version is that a=v[0] always. I must compare each two consecutive numbers: v[0] with v[1], v[1] with v[2], ... , v[n-1] with v[n]. If all 2 consecutive numbers are distinct then I must cout<<"YES". Your program couts<<"NO" no matter what I enter.
@FlashDrive I can't do that, in the text it is specified that sub function must be constructed so that it returns how many elements from the array are equal to a. If I'd do it your way, the initial purpose would be lost.
I'm sorry, I really can't do these little tricks. In the end, this is just a paper exam, so my program would only be on paper, and if my program isn't exactly as the exercise requests (only use sub function written on point a) and a main function) I won't get any points for it (even if it would run correctly). I'll ask my teacher tomorrow, she should have experience solving these kind of exam problems. Thank you for your efforts.
#include <iostream>
usingnamespace std;
int sub (int v[],int n, int a)
{ int i, c=0;
for(i=1;i<=n;i++)
if(v[i]==a)
c++; //c is the counter, any time the program finds an element from the array equal to a, one unit is added to the counter
return c;
}
main ()
{
int v[100],n,i,ok=0;
cin>>n;
for(i=1;i<=n;i++)
cin>>v[i];
for(i=2;i<=n;i++)
if(sub(v,i-1,v[i]))
ok=1;
if(ok==0)
cout<<"\n DA";
else
cout<<"\n NO";
}