0

Hi all :)

Recently i got a an assignment to be done which need to deal with c++ pointer..

This is the question :

Write a function that accepts a pointer to a C-string as its argument. The function should return the character that appears most frequently in the string. Demonstrate the function in a complete program.

So i've tried written my codes this way :

#include <iostream>
using namespace std;

char large(char *p,int a)
{
int large=0,x=1,b;
char r;

for (int i=0;i<a;i++)
{
for(int j=0;j<a;j++)
{
if(*p+j==*p+i && i!=j)
{
x++;
}
if (x>large)
{
large=x;
b=i;
}
x=0;
}


r=*(p+b);
return r;
}
}


int main()
{

char test[100];
cout<<" Enter a word :";
cin.get(test,100);
cout<<endl;

char *p;
p=test;
int a=strlen(test);

char ans= large(p,a);
cout<<ans<<endl;

system ("pause");

return 0;
}

I dont know where i got it wrong, but the output is not correct..
Help me please..this need to be passed by this sunday..

Thank You :)

2
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by samsons17
1

There are just a few mistakes (proper indentation helps to see these mistakes):

char large(char *p,int a)
{
  int large=0,x=0,b; //x should start at zero.
  char r;

  for (int i=0;i<a;i++)
  {
    for(int j=0;j<a;j++)
    {
      if(*(p+j)==*(p+i)) //notice the difference here *(p+i) instead of *p+i, and the i != j is not necessary.
      {
        x++;
      }
    } //end the inner loop here
    if (x>large)
    {
      large=x;
      b=i;
    }
    x=0;
  }


  r=*(p+b);
  return r;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.