on 2 comments

C++ Program to Find Sum of Square of n Natural Numbers

Let us write a c++ program to find sum of square of n natural numbers

/*C++ Program to Find Sum of Square of n Natural Numbers*/
#include<iostream>
using namespace std;
int main()
{
    int n,i,t;
    int s=0;
    cout<<"Enter the value of n : ";
    cin>>n;
    for(i=1;i<=n;i++)
    {
        t=i*i;
        s=s+t;
    }
    cout<<endl;
    cout<<"Sum of square of  first "<<n<<" natural numbers is "<<s;
    return 0;
}

OUTPUT:

Enter the value of n : 5

Sum of square of first 5 natural numbers is 55

Let us see another c++ program to find sum of square of n natural numbers.

/*C++ Program to Find Sum of Square of n Natural Numbers Using Function*/
#include<iostream>
using namespace std;
void sumofsq(int n);
int main()
{
    int n;
    cout<<"Enter the value of n : ";
    cin>>n;
    sumofsq(n);
    return 0;
}
void sumofsq(int n)
{
    int t,i,s=0;
    for(i=1;i<=n;i++)
    {
        t=i*i;
        s=s+t;
    }
    cout<<endl;
    cout<<"Sum of square of first "<<n<<" natural numbers is "<<s;
}

OUTPUT:

Enter the value of n : 5

Sum of square of first 5 natural numbers is 55



2 comments: