When debugging this code I noticed that the value of sum as mentioned in code tend to give wrong results. I cant understand why this is happening.
My program takes a string calculate its substrings and count the number of vowels present in all the substrings, the last sum value is the sum of all the vowel counts simultaneously
I've already tried debugging through the code and can't understand what's wrong with the code
#include <iostream>
using namespace std;
int main()
{
long long int t,j,n,l,count=0,sum=0;
cin>>t;
string s;
//char i;
while(t>0)
{
l=0;
sum=0;
count=0;
cin >> s;
n= s.length();
for(j=0;j<n;j++)
{
if(s[j]=='a' || s[j]=='e' || s[j]=='i' || s[j]=='o' || s[j]=='u' || s[j]=='A'|| s[j]=='E' || s[j]=='I' ||s[j]=='O' || s[j]=='U')
{
count++;
l=j;
cout<<"l="<<j<<endl;
cout<<"j="<<j<<endl;
cout<<"n="<<n<<endl;
cout<<"n-1="<<n-1<<endl;
cout<<"j+1="<<j+1<<endl;
sum=sum+((n-l)*(j+1));
cout<<"SUM is="<<sum << endl;
}
}
if(l==0)
{
sum=0;
}
cout<<"Second part Sum="<<endl;
cout<<sum<<endl;
t--;
}
}
Program compiles and runs with no error messages. However, there are logical errors because the calculations of sum are incorrect...
Why is that sum = 20 ?, It should be 25 or 35...
For clarification, this is the problem statement for this solution: https://www.hackerearth.com/practice/basic-programming/complexity-analysis/time-and-space-complexity/practice-problems/algorithm/vowel-game-f1a1047c/
The output given by your program is correct. why you think it should be 25/30?
You wrote
sum=sum+((n-l)*(j+1));
when j = 1 then l=j=1 So (n-l)(j+1)=(6-1)(1+1)=5*2=10
So sum = sum+(n-l)*(j+1)=0+10=10
when j=4 then l=j=4
So (n-l)(j+1)=(6-4)(4+1)=2*5=10
So sum = sum+(n-l)*(j+1)=10+10=20
I think you are messing with l(alphabet) and 1.
If you wrote (n-l)*(j+1)
then it would be = 5*5=25 results in final sum=10+25=35