A program to display the sum of n numbers in C

In this program, I am adding ‘n’ numbers entered by the user using do…while loop.

Sum of n numbers in C

#include<stdio.h>
#include<conio.h>

void main()
{
int n,i=0,sum=0;
char choice;
clrscr();
do
{
printf("Enter any number to add:");
scanf("%d",&n);
i++;
sum=sum+n;
printf("Do you want to add more numbers- press 'y' for yer or 'n' for no:");
scanf("%c",&choice);
}while(choice!='n');
printf("Sum of %d numbers=%d",i,sum);
getch();
}

Output

Enter any number to add: 5
Do you want to add more numbers- press 'y' for yer or 'n' for no:y

Enter any number to add: 6
Do you want to add more numbers- press 'y' for yer or 'n' for no:y

Enter any number to add: 11
Do you want to add more numbers- press 'y' for yer or 'n' for no:n

Sum of 3 numbers=22

Program Code Execution(PCE)

Above, I make a program to display the sum of n numbers in C using a Do-While loop. It is an easy program if you know loops.

Other C programs

If you don’t know the syntax of a do-while loop. Below is the syntax of a do-while loop.

initilization;
do
{

expression;
expression;
increament/decrement;

}while(condition);

In the above syntax, we initialize variable above the do-while loop and perform all expression inside the do block even use increment or decrement option inside it.

In outside the do block we use condition as seen in the above syntax.

Okay, back to the program code. I took some variable (‘n’, ‘i’ and ‘sum’ as an integer and ‘choice’ as a character).

Implement a do-while loop and input values from the user. Then add that value into the ‘sum’ variable. Also ask to add more values, if user input’s choice=y then ask again for a new number until choice=’n’.

Finally, display the sum of n numbers in C. I used ‘i’ variable as a counter. It counts total numbers inputted by the user.

Hope that you understand the sum of n numbers in C program.

Please ask your queries in below comment section.

You can also visit my tech blog http://zerootech.com to read blogging and more.

Leave a Comment

error: Don\'t make piracy - Write your own content :)