This exercise is from the C++ primer 4th edition book from 2005. The
program works and runs fine. This is a solution to the exersice section
1.4.2 on page 17.
Exercise 1.10: Write a program that uses for loop to sum the numbers from 50 to 100. Now rewrite the program using a while loop.
In this part we rewrite the for loop to using a while loop
The For loop
#include <iostream> int main() { int sum = 0; int loopcount = 0; for (int i = 50; i < 100; i++)
{ loopcount++; sum += i; std::cout << "Sum of loop number " << loopcount << " is " << sum << std::endl;
} return 0; }
The While loop
#include <iostream> int main() { int sum = 0; int val = 50; int loopcount = 0; while (val < 100) { loopcount++; sum += val; val++; std::cout << "Sum of loop number " << loopcount << " is " << sum << std::endl;; } return 0; }
A while loop written in C++ |
The result in the windows command prompt look like this:
As you can see the loopcount variable is counting each loop |
Ingen kommentarer:
Send en kommentar