0

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;
}
2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by lAmoebal
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.

This topic has been dead for over six months. 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.