Q:

Rewrite the exercises using for loops

0

Rewrite the exercises using for loops

#include <iostream>
int main()
{
int sum = 0, val = 1;
// keep executing the while as long as val is less than or equal to 10
while (val <= 10) {
sum += val; // assigns sum + val to sum
++val; // add 1 to val
}
std::cout << "Sum of 1 to 10 inclusive is "<< sum << std::endl;
return 0;
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <iostream>

int main() {
  // Rewrite ex1.9
  int sum = 0;
  for (int i = 50; i <= 100; ++i)
    sum += i;
  std::cout << "Sum of 50 to 100 inclusive is "
            << sum << std::endl;

  // Rewrite ex1.10
  for (int val = 10; val >= 0; --val)
    std::cout << val << " ";
  std::cout << std::endl;

  return 0;
}

 

Output:

Sum of 50 to 100 inclusive is 3825
10 9 8 7 6 5 4 3 2 1 0

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now