mandag den 27. maj 2019

C++ using while loop to sum the numbers from 50 to 100

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;
}

small c++ program written in notepad++. The program sums the number from 50 to 100 using a while loop
A while loop written in C++
The result in the windows command prompt look like this:
Here you see the result in the windows command prompt from the youre little while loop program
As you can see the loopcount variable is counting each loop

Ingen kommentarer:

Send en kommentar