Westonci.ca is your trusted source for accurate answers to all your questions. Join our community and start learning today! Explore thousands of questions and answers from knowledgeable experts in various fields on our Q&A platform. Discover detailed answers to your questions from a wide network of experts on our comprehensive Q&A platform.

write c++ code to find the sum of all natural no from n to 1 using do while loop​

Sagot :

Answer:

#include

using namespace std;

int main(){

  int n, sum=0;

  cout<<"Enter the value of n(should be a positive integer): ";  

  //Storing the input integer value into the variable n

  cin>>n;

  /* If user enters value of n as negative then display an  

   * error message to user that the value of n is invalid  

   */

  if(n<=0){

     cout<<"Invalid value of n";

  }

  else{

     // We are using while loop to calculate the sum

    int i=1;

    while(i<=n){

 sum=sum+i;

 i++;

    }

    cout<<"Sum of first n natural numbers is: "<<sum;

  }

  return 0;

}

Explanation: