Hello guys, I just join your site to get help about my coding programme class c++. I do have to modify my programme that the out put will show the form sum=1+3+5+7=16. Can you please help me out thxx .

Programme is adding odd integer :

# include <iostream>
using namespace std;
int main ()
{
	int n=0;
	int counter=0;
	int sum=0;

	cout<<"Please enter the value of n"<<endl;
	cin>>n;

	counter=1;
	while(counter<=n)
	{
		sum=sum+(2*counter-1);
		counter++;
	}
	
	 cout<<"the sum is"<<sum<<endl;

	 return 0;
}

I'm not sure I completely understand your question. Are you trying to add just the odd numbers up until a certain value? If that's the case, in your while loop change

sum=sum+(2*counter-1);

to

if (counter%2 != 0)
{
  sum = sum + counter;
}

If you need to output each number at the same time, before your loop, put

cout << "sum = ";

And make the if statement I just posted look like..

if (counter%2 != 0)
{
  sum = sum + counter;
  if (counter != n)
  {
     cout << counter << " + ";
  }
  
  else
  {
     cout << counter << " = ";
  }
}

And then after your loop, simply output the sum variable.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.