Decode School

Decode School - The School for Problem Solvers

Welcome to my blog. Subscribe and get my latest blog post in your inbox.

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

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.