Sum of All Pos Integers from A to B

Write a program to print the sum of all positive integers from a up to (and including) b where a and b are entered by the user.

I can't seem to get this down. Help?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
	int num1, num2, sum;
	
	printf("Enter the first number: ");
	scanf_s("%d", &num1);
	printf("Enter the second number: ");
	scanf_s("%d", &num2);

	while (num1 < num2)
		{
		sum = sum + num1;
		num1++;
		}


	printf("The sum of the number between %d and %d is: %d", num1, num2, sum);
You haven't initialized sum before using it, so nobody can tell what you're gonna get out of this code. Set it to 0 somewhere before the loop.

Also. line 10 should be while( num1 <= num2 )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	int num1, num2, sum = 0;
	
	printf("Enter the first number: ");
	scanf_s("%d", &num1);
	printf("Enter the second number: ");
	scanf_s("%d", &num2);

	while (num1 <= num2)
		{
		sum = sum + num1;
		num1++;
		}


	printf("The sum of the numbers between %d and %d is: %d", num1, num2, sum);


Input is 2 and 8.
Why is my output?:

The sum of the numbers between 9 and 8 is: 35


The answer is correct, but it should show 2, not 9.
because you incremented num1 throughout the loop, it is no longer 2 when you get to the printf.
So do I set another variable equal to num1, then increment num1? And print the previously set variable?

Example:
1
2
3
4
5
stayNum1 = num1;

while loop....

printf("The sum of the numbers between %d and %d is: %d", stayNum1, num2, sum);

Last edited on
that's what I'd do.
Thanks Esslercuffi!
Topic archived. No new replies allowed.