1. 程式人生 > >C 求兩個整數之間所有整數和問題

C 求兩個整數之間所有整數和問題

問題:

Write a program that

(1) inputs two integers (integer1 and integer 2)

(2) prints sum of all integers between integer1 and integer2

(3) Use while() statement

Ex) input : 10, 15 -> Sum : 10 + 11+ 12+ 13 +14 + 15 = 75

#include<stdio.h>
#include<stdlib.h>

int main(void) {
	int a, b;
	int start, end;
	int sum=0;
	printf("Enter two integers:");
	scanf_s("%d %d", &a, &b);

	if (a < b) {
		start = a;
		end = b;
	}
	else {
		start = b;
		end = a;
	}
	
	while (start <= end) {
		sum = sum + start;
		start = start + 1;

	}

	printf("The sum of all integers between %d and %d is %d\n", a, b, sum);
	system("pause");
	return 0;
}