C Program to calculate sum of multiple positive numbers (Stop if user enters negative number)

Get positive integers from user till user enters a negative integer calculate sum of positive integers.

Sample Input 1:

5 6 7 2 1 8 -9

Sample Output 1:

29

Sample Input 2:

3 23 -76

Sample Output 2:

26

Try your Solution

Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

#include<stdio.h> int main() { //write your code here }

Program or Solution

				
			
					
#include<stdio.h>
int main()
{
	int num,sum=0;
	printf("Enter Postive numbers to sum:");
	while(1)
	{
		scanf("%d",&num);
		if(num<0)
		{
			break;
		}
		sum=sum+num;
	}
	printf("%d",sum);
	return 0;
}
			
				
			

Program Explanation

since 1 is always true, scanf statement gets input from user continously, if user enters a negative number it exit from while loop using break statement.

Comments


Related Programs