søndag den 26. juli 2020

C++ for loop sum number 50 to 100 - enhanced version

Write a program that uses a for loop to sum the numbers from 50 to 100

Simple version

int sum = 0;
    for (int i = 50; i <= 100; ++i) {
        sum += i;
    }
std::cout << "The sum is: " << sum << std::endl;
return 0;

Remember to insert the code inside of:

#include <iostream>
int main {
    insert code her
}

The Enhanced version:

int sum = 0;
int balance = 0;
for (int i = 50; i <= 100; ++i) {
    balance = sum; // balance variable befor sum+=i. Makes sense when you run the program
    sum += i;  
    std::cout << balance << " + " << i << " = " << sum << std::endl;
}
std::cout << "The sum is: " << sum << std::endl;
return 0;

Ingen kommentarer:

Send en kommentar