user7253265
user7253265

Reputation:

C++ While loop questions

I have some problems on how to set while and do/while cycles.

For example, i have a problem, where in input i have 2 int numbers ( let's call them a,b ) and i need to calculate a sum. The sum is particolar: a + (b) + (b – 1) + (b – 2) + … + 0. The while cicle is a must. But i don't know how to set it. I have tried, but I don't know if it is right. Can somebody let me know this?

Here there is my code

#include <iostream>
#include <stdlib.h>

using namespace std;

int main(int argc, char *argv[])
{
 // Variables
 int a,b;
 int sum;

 cout<<"Insert a:";
 cin>>a;
 cout<<"Insert b:";
 cin>>b;

 // Show a,b
 cout<<"variables:"<<" "<<a<<" e "<<b<<endl;

// Condition: a>0 & b>0
while(a>0 && b>0)
{
 sum=a+b;
 b--;  
} cout<<"Sum:"<<sum;
system("PAUSE");    
return 0;
}

For example if i put a=5 and b=9 the sum is 6. Is it right?

Upvotes: 1

Views: 409

Answers (2)

Naseef Chowdhury
Naseef Chowdhury

Reputation: 2464

You might think of rewriting the while portion. I would suggest you to check only b in while condition. Because, you are changing the b value only. Please see the following code -

sum = a; // as you want to add a only once, you should add a to sum before the loop
while(b)
{
 sum += b;
 b--;  
}

Please feel free to ask if you have any confusions.

Upvotes: 2

Seeker
Seeker

Reputation: 126

You must set sum = a; before entering the while loop and update it in each iteration as sum += b;. Hopefully these will solve your issue.

Upvotes: 0

Related Questions