37.8k views
3 votes
Write three separate code which would use a while loop, for loop and do ..while loop to output integers 200 down to 50 with their squares listed besides the integers which increments by steps of -10

1 Answer

6 votes

Answer:

The c++ program using for loop is given below.

#include <iostream>

using namespace std;

int main() {

int sq, i;

cout<<"Integer"<<"\t"<<"Square"<<endl;

for(i=200;i>=50;i=i-10)

{

cout<<i<<"\t"<<"\t";

sq=i*i;

cout<<sq<<endl;

}

return 0;

}

The c++ program using do-while loop is given below.

#include <iostream>

using namespace std;

int main() {

int sq, i=200;

cout<<"Integer"<<"\t"<<"Square"<<endl;

do

{

cout<<i<<"\t"<<"\t";

sq=i*i;

cout<<sq<<endl;

i=i-10;

}while(i>=50);

return 0;

}

The c++ program using while loop is given below.

#include <iostream>

using namespace std;

int main() {

int sq, i=200;

cout<<"Integer"<<"\t"<<"Square"<<endl;

while(i>=50)

{

cout<<i<<"\t"<<"\t";

sq=i*i;

cout<<sq<<endl;

i=i-10;

}

return 0;

}

OUTPUT

Integer Square

200 40000

190 36100

180 32400

170 28900

160 25600

150 22500

140 19600

130 16900

120 14400

110 12100

100 10000

90 8100

80 6400

70 4900

60 3600

50 2500

Step-by-step explanation:

The integer variables sq and i are declared to hold the square and the integer respectively. The square of an integer is also a square hence, it is also declared as integer and not float.

The variable i is initialized to 200 as required by the question. All the three loops continue till value of i reaches 50. Once, the value goes below 50, loop is discontinued.

In for loop initialization, condition and decrement, all are done simultaneously.

for(i=200;i>=50;i=i-10)

In do-while and while loops, variable declaration and initialization are done simultaneously. The condition and decrement logic is contained within the loop.

This loop executes once irrespective whether the condition is satisfied or not. From the second execution onwards, the condition is taken into account.

do

{

cout<<i<<"\t"<<"\t";

sq=i*i;

cout<<sq<<endl;

i=i-10;

}while(i>=50);

The while loop is similar to do-while loop except that the while loop executes only if the condition is satisfied.

The output for all the three loops is the same hence, output is shown only once.

User Learning Curve
by
5.3k points