Answer:
Following are the program in c++
First code when using for loop
#include<iostream> // header file
using namespace std; // namespace
int main() // main method
{
int n, i, sum1 = 0; // variable declaration
cout<<"Enter the number: "; // taking the value of n
cin>>n;
if(n > 0) // check if n is nonnegative
{
for(i=n; i<=(2*n); i++)
{
sum1+= i;
}
}
else // check if n is negative
{
for(i=(2*n); i<=n; i++)
{
sum1+= i;
}
}
cout<<"The sum is:"<<sum1;
return 0;
Output
Enter the number: 1
The sum is:3
second code when using while loop
#include<iostream> // header file
using namespace std; // namespace
int main() // main method
{
int n, i, sum1 = 0; // variable declaration
cout<<"Enter the number: "; // taking the value of n
cin>>n;
if(n > 0) // check if n is nonnegative
{
int i=n;
while(i<=(2*n))
{
sum1+= i;
i++;
}
}
else // check if n is negative
{
int i=n;
while(i<=(2*n))
{
sum1+= i;
i++;
}
}
cout<<"The sum is:"<<sum1;
return 0;
}
Output
Enter the number: 1
The sum is:3
Explanation:
Here we making 2 program by using different loops but using same logic
Taking a user input in "n" variable.
if n is nonnegative then we iterate the loops n to 2 * n and storing the sum in "sum1" variable.
Otherwise iterate a loop 2 * n to n and storing the sum in "sum1" variable. Finally display sum1 variable .