74.7k views
2 votes
Given int variables k and total that have already been declared, use a while loop to compute the sum of the squares of the first 50 counting numbers, and store this value in total. Thus your code should put 1*1 2*2 3*3 ... 49*49 50*50 into total. Use no variables other than k and total.

1 Answer

7 votes

Answer:

The c++ program for the given scenario is as follows.

#include <iostream>

using namespace std;

int main() {

int k, total;

k=1;

total=0;

while(k<=50)

{

// square of every counting number is added to total

total = total + (k*k);

// value of k is incremented to move on to the next counting number

k++;

}

cout<<"Sum of squares of first 50 counting numbers is " << total<<endl;

return 0;

}

OUTPUT

Sum of squares of first 50 counting numbers is 42925

Step-by-step explanation:

As mentioned, only two variables k and total are used in the program. These variables are declared with data type integer.

Variable k is initialized to 1 and variable total is initialized to 0.

k=1;

total=0;

Variable k is used to represent counting number whose square is added to the variable total. Hence, values are taken accordingly.

The while loop is also known as the pre-test loop. This loop first evaluates the given condition and executes if the condition is satisfied.

while(k<=50)

The above while loop will execute till the value of variable k is less than or equal to 50. Once the value of k exceeds 50, the loop gets terminated. The loop executes 50 times, beginning from the value of 1 till k reaches 50.

The value of k is squared and added to the variable total each time the loop executes.

total = total + (k*k);

After the square is added to total, value of variable k is incremented by 1. This new value represents the next counting number.

k++;

After 50 executions of the loop, total variable will hold the sum of the squares of all the numbers from 1 to 50. The sum is displayed at the end.

This program implements the simplest logic for calculation of sum using two variables. The other loops such as for loop and do-while loop only differ in the placement and/or evaluation of the test condition.

User Popester
by
5.6k points