Skip to main content

Write a C C++ program to generate series of natural numbers and their sum


Flowchart
Write a C C++ program to generate series of natural numbers and their sum

Coding in C

#include<stdio.h>
int main()
{
    int num=1,n,sum=0;
    printf("Enter n: ");
    scanf("%d",&n);
    while(num<=n)
    {
        printf("%d\n",num);
        sum=sum+num;
        num++;
    }
    printf("Sum of series = %d",sum);
    return 0;
}

Coding in C++

#include<iostream>
using namespace std;
int main()
{
    int num=1,n,sum=0;
    cout<<"Enter n: ";
    cin>>n;
    while(num<=n)
    {
        cout<<num<<"\n";
        sum=sum+num;
        num++;
    }
    cout<<"Sum of series = "<<sum;
    return 0;
}

Output

C++ program to generate series of natural numbers and their sum