sum of the numbers

#include<iostream>
using namespace std;
int main()
{ //1+2+3+4+<=10
// 1+2+3+4+5+6<=21

int sum=0,num,a;
cout<<"enter a number: ";
cin>>num;
for(a=1;a<=num;a++)

{
sum=sum+a;
if(sum>num) break;

}
cout<<(a-1);

return 0;

}

May i know why is the meaning for'if(sum>num)break;?
And why the cout<<(a-1) need to be 'a-1'? What is the concept about it ?>
First, please use the code tags and indentation, when posting code.
See http://www.cplusplus.com/articles/jEywvCM9/
The nice formatting really improves readability and line numbering makes commenting the code simpler.

Your code (with couple style changes):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>

int main()
{
  std::cout << "enter a number: ";
  int num;
  std::cin >> num;
  int sum = 0
  int a;
  for ( a=1; a <= num; ++a )
  {
    sum = sum + a;
    if ( num < sum )
    {
      break;
    }
  }
  std::cout << (a-1);
  return 0;
}

The essential question is: What does this program do?

Can you explain the "what"? Your "why"s are merely details on how to achieve the what.
I also didnt undestand what is the program you want.
Tell about the input and what the output look like?

besides,
std::cout << "enter a number: "; without using namespace
is same as
cout << "enter a number: "; with using namespace.

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
// #include<string>
using namespace std;
int main()
{ 									//1+2+3+4+<=10 or  1+2+3+4+5+6<=21
	int sum=0,num1 = 0, num2 = 0, num3 = 0, num4 = 0;  
	cout << "Please enter first value: " << "\t"; 
		cin>>num1;
	cout << "Please enter second value: " << "\t";
		cin >> num2;
	cout << "Please enter third value: " << "\t";
		cin >> num3; 
	cout << "Please enter fourth value: " << "\t";
		cin >> num4; 
			for(int x = 0; x == 0; ++x)
	{
			sum=num1 + num2 + num3 + num4;
		
				cout << sum ; 
	}

return 0;

}


I kind of feel bad for just giving you the answer; however, like everyone else said...What exactly were you trying to do. I saw you had comments out on 1+2+3+4 < 10 (10 isnt greater than or less than 10, it's ==)TRUE....vice versa for your other comment..It seems to me like it was asking you for four integer values. Im not exactly sure why you wanted to use a for loop or even an if statement. Unless you are trying to say if the answer of the sum from the four numbers isnt 10 then cout >> "what ever code you wanted to put in here"....

PS... In your for loops I believe Ive seen quite a few people mention that it's good practice to do ++x when doing increments of instead of x++. Just a suggestion....
Last edited on
Topic archived. No new replies allowed.