IN C++ AS SIMPLE AS POSSIBLE ______
Re-write the given function, printSeriesSquareFifth, to use a while loop (instead of for).
• The function takes a single integer n as a parameter
• The function prints a series between 1 and that parameter, and also prints its result
• The result is calculated by summing the numbers between 1 and n (inclusive). If a number is divisible by 5, its square gets added to the result instead.
• The function does not return a value.
The series is: 1 + 2 + 3 + 4 + 5*5 +6 + 7 + 8 + 9 + 10*10 + 11 + 12 + 13 + 14 + 15*15 + 16 + ....
Example 1:
Calling the function with the integer 6 should print the
following:
1 + 2 + 3 + 4 + 25 + 6
Result of the series is 41
Example 2:
Calling the function with the integer 15 should print the
following:
1 + 2 + 3 + 4 + 25 + 6 + 7 + 8 + 9 + 100 + 11 + 12 + 13 + 14 +
225
Result of the series is 440
void printSeriesSquareFifth(int n) { int sum = 0; for (int i = 1;i <= n;i++) { if (i%5 == 0) { //If the number is divisible by 5, print its square and add the square to the sum cout << i*i; sum = sum + i*i; } else { //If the number is not divisible by 5, print the number and add the number to the sum cout << i ; sum = sum + i; } if(i != n){ //This check is added to not print the last '+' cout<<" + "; } } cout << endl << "Result of the series is " << sum << endl; }
void printSeriesSquareFifth(int n) { int sum = 0; int i = 1; while(i <= n) { if (i%5 == 0) { //If the number is divisible by 5, print its square and add the square to the sum cout << i*i; sum = sum + i*i; } else { //If the number is not divisible by 5, print the number and add the number to the sum cout << i ; sum = sum + i; } if(i != n){ //This check is added to not print the last '+' cout<<" + "; } i++; } cout << endl << "Result of the series is " << sum << endl; }
Get Answers For Free
Most questions answered within 1 hours.