C++ Program to calculate the sum of a series up to N terms.This program calculates the sum of the series 1 + 2 + 3 +. . . . . . . .
.+n and prints the result on the compiler screen. The last number n is
input by the user. Sum of this series is calculated by the formula :
sum=(n*(n+1))/2. For loop is used to print the whole series upto n and
the sum is printed on compiler screen.
Source Code:-
#include<iostream.h>
#include<conio.h>
void main()
{
int n,i;
int sum=0;
clrscr();
cout<<"Program to calculatesum 1+2+3+...n by-Tarun Rawat\n";
cout<<"\nEnter the value of n : ";
cin>>n;
sum=(n*(n+1))/2;
cout<<"\nSum of the series: ";
for(i=1;i<=n;i++)
{
if (i!=n)
{
cout<<i<<" + ";
}
else
{
cout<<i<<" = "<<sum;
}
}
getch();
}
Source Code:-
#include<iostream.h>
#include<conio.h>
void main()
{
int n,i;
int sum=0;
clrscr();
cout<<"Program to calculatesum 1+2+3+...n by-Tarun Rawat\n";
cout<<"\nEnter the value of n : ";
cin>>n;
sum=(n*(n+1))/2;
cout<<"\nSum of the series: ";
for(i=1;i<=n;i++)
{
if (i!=n)
{
cout<<i<<" + ";
}
else
{
cout<<i<<" = "<<sum;
}
}
getch();
}
No comments:
Post a Comment