@Minionmin, A couple of suggestions:
1. When using C library functions in C++ code use the C++ version of the header, if there is one available. <cstdio> instead of <stdio.h>
2. Prefer using C++ functionality instead of C functions, when available. C++20 now has output formatting that is similar to C printf. <format> is the header.
I see you are using a version of Visual Studio, the
#define _CRT_SECURE_NO_WARNINGS
is a dead giveaway for that. If you use VS 2019 or 2022 std::format is available, currently the only compiler suite that is compliant.
https://en.cppreference.com/w/cpp/utility/format
<format> is largely based on the 3rd party {fmt} library so if you use another compiler you can still get that formatting capability.
https://fmt.dev/latest/index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
#include <format>
int main()
{
unsigned int limit {};
std::cout << "This program calculates n! and the sum of the integers\n"
<< "up to n for values 1 to limit.\n";
std::cout << "What upper limit for n would you like? ";
std::cin >> limit;
std::cout << '\n';
// The format string for all rows of the table
const auto table_format { "{:>8} {:>8} {:>20}\n" };
// output column headings
std::cout << std::format(table_format, "integer", "sum", "factorial");
for ( unsigned long long n { 1 }, sum {}, factorial { 1 }; n <= limit; ++n )
{
sum += n; // accumulate sum to current n
factorial *= n; // calculate n! for current n
std::cout << std::format(table_format, n, sum, factorial);
}
}
| |
This program calculates n! and the sum of the integers
up to n for values 1 to limit.
What upper limit for n would you like? 15
integer sum factorial
1 1 1
2 3 2
3 6 6
4 10 24
5 15 120
6 21 720
7 28 5040
8 36 40320
9 45 362880
10 55 3628800
11 66 39916800
12 78 479001600
13 91 6227020800
14 105 87178291200
15 120 1307674368000 |
Since std::format requires C++20 to work, let's use modules instead of headers. Change the 2 #includes to:
1 2
|
import <iostream>;
import <format>;
| |
The program output is the same.