Let’s write a program using for loop to find the sum of the squares of the integers from 1 to n. Where n is a positive value entered by the user (i.e. Sum = 12 + 22 + 32 + ……+ n2)
The code of the program is given below:
In the program we declared three variables i, n and sum. We prompted the user to enter a positive number. We stored this number in the variable n. Then we wrote a for loop. In the initialization part, we initialized variable i with value 1 to start the counting from 1. In the condition statement we set the condition i less than or equal to n (number entered by the user) as we want to execute the loop n times. In the increment statement, we incremented the counter variable by 1. In the body of the for loop we wrote a single statement sum += i * i ;. This statement takes the square of the counter variable ( i )and adds it to the variable sum. This statement is equivalent to the statement sum = sum + ( i * i ) ; Thus in each iteration the square of the counter variable (which is increased by 1 in each iteration ) is added to the sum. Thus loop runs n times and the squares of numbers from 1 to n are summed up. After completing the for loop the cout statement is executed which displays the sum of the squares of number from 1 to n.
Following is the output when the number 5 is entered.
Tips:
The code of the program is given below:
In the program we declared three variables i, n and sum. We prompted the user to enter a positive number. We stored this number in the variable n. Then we wrote a for loop. In the initialization part, we initialized variable i with value 1 to start the counting from 1. In the condition statement we set the condition i less than or equal to n (number entered by the user) as we want to execute the loop n times. In the increment statement, we incremented the counter variable by 1. In the body of the for loop we wrote a single statement sum += i * i ;. This statement takes the square of the counter variable ( i )and adds it to the variable sum. This statement is equivalent to the statement sum = sum + ( i * i ) ; Thus in each iteration the square of the counter variable (which is increased by 1 in each iteration ) is added to the sum. Thus loop runs n times and the squares of numbers from 1 to n are summed up. After completing the for loop the cout statement is executed which displays the sum of the squares of number from 1 to n.
Following is the output when the number 5 is entered.
Tips:
- Comments should be meaningful, explaining the task
- Don’t forget to affect the value of loop variable in while and do-while loops
- Make sure that the loop is not an infinite loop
- Don’t affect the value of loop variable in the body of for loop, the for loop does this by itself in the for statement
- Use pre and post increment/decrement operators cautiously in expressions