Program to find sum of positive numbers and exit when negative number is entered in C

In this example we use arrays(one dimensional array). Arrays are declared in the same as simple variables, but the difference is that each array name must be accompanied by a size(aa[20]) specification using subscript.

 

#include<stdio.h>

#include<conio.h>

void main()

   {

        //here aa is the integer array of size20

     int aa[20],lastNo,ii,summ=0;

     clrscr();

     printf("enter the number");

     scanf("%d",&lastNo);

     for(ii=0;ii<lastNo;ii++)

     {

         printf("\n Enter the elements%d:",ii+1);

       scanf("%d",&aa[ii]);

       if(aa[ii]<0)           //if we enter negative then

           {

             printf("Oh!The program is terminated");

             sleep(5);//function which suspend execution for 5 second

             exit(0); //close

           }

       else     // if we enter positive numbers then

             summ=summ+aa[ii];    //calculate(sum of all numbers which we enter in the program)

     }

printf("The sum is:%d",summ);    //print total(sum)

getch();

}

OUTPUT WITH POSITIVE VALUE(SUM)

sum of numbers

 

OUTPUT WITH NEGATIVE VALUE(EXIT)

Terminate the program

Explanation …

In above example first we enter the number((lastNo)which allows you to enter more than 0 and less than 20 elements as per your requirement).After that we input data into the individual elements of the array. It is recommended to use looping statements. The address of operator with aa[i] is used in the scanf() statement to store the value of the element of array. If we enter negative number then the if part will execute( program will terminate(stop) after 5 second) otherwise the else part will execute(sum=sum+aa[i])