New to programming and I was just practicing this Question. Return the longest sequence of characters in an array. My answer came out to be
public void rLong()
{
string sequence = "aabcccddeeee";
char mac='\'';
char[] sArray = new char[8];
sArray = sequence.ToCharArray();
int k;
int tmp=0;
int i;
for(i=0; i < sArray.Length-1; i++)
{
int count=0;
for(k=0; k < sArray.Length-1; k++)
{
if(sArray[i]==sArray[k])
count++;
if(count>=tmp)
{
tmp=count;
mac=sArray[i];
}
}
}
Console.WriteLine("highest letter is {0} and count is {1}", mac,tmp);
}
Answer: highest letter is e and count is 3
This answer gave me the right char(e) but the wrong count(3) it should be 4. But through trial and error I figured if i take the -1 out on the sArray.Length in the inner for loop I get the right count(4).
Can someone explain why? I thought always to put -1 on array.length when looping through its index. Is it different when using a nested for loop? Any help would be appreciated. Thank You