139k views
0 votes
Write a program that reads in an integer value for n and then sums the integers from n to 2 * n if n is nonnegative, or from 2 * n to n if n is negative. Write the code in two versions: one using only for loops and the other using only while loops.

User Moodyjive
by
5.1k points

1 Answer

2 votes

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

Step-by-step 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 .

User Jvdub
by
4.5k points