218k views
3 votes
Write aprogram to calculate the square of 20 by using a loop that adds 20to the accumulator 20 times.

1 Answer

3 votes

Answer:

#include<iostream>

using namespace std;

//main function

int main(){

//initialization of variable

int temp_sum=0;

//for loop which run 20 times

for(int i=1;i<=20;i++){

temp_sum = temp_sum + 20; //adding

}

//display the output

cout<<"The square of 20 is: "<<temp_sum<<endl;

return 0;

}

Step-by-step explanation:

Include the library iostream for using the input/output instruction in the program.

Then, create the main function and declare the variable which used to store the output.

take a for loop that runs again and again for 20 times and each cycle it adds the 20 to the previous output.

The addition process continues for 20 times.

Let dry run the code:

initially, temp_sum=0, i=1

for loop check the condition, i <= 20 condition is true.

then, temp_sum = 0 + 20 which is 20 assign to temp_sum.

then, for loop increase the value of i and becomes 2.

again loop run and check condition 2 <= 20, condition true.

Then, temp_sum = 20 + 20 which is 400 assign to temp_sum.

then, for loop increase the value of i and becomes 3.

The above process continues for 20 times and finally the result of 400 stores in the temp_sum.

and finally, display the result on the screen.

User Emmanuel Demey
by
8.0k points