Loop Programs
C++ for and while: tables, GCD, primes. Off-by-one prints one row too few.
14 programs · open one, then the next
Start with Multiplication Table- 01Multiplication TableBeginnerPrint a multiplication table in C++ with a for loop. Use <= 10, not < 10.Open example →cpp#include <iostream> using namespace std; int main() {
- 02Sum of n Natural NumbersBeginnerSum 1..n in C++. n=10 is 55. Initialize sum to 0. Or use n*(n+1)/2.Open example →cpp#include <iostream> using namespace std; int main() {
- 03Factorial of a NumberBeginnerFactorial in C++: 5! is 120. Use long long — 13! overflows int. 0! is 1.Open example →cpp#include <iostream> using namespace std; int main() {
- 04Reverse a NumberBeginnerReverse digits in C++ with % 10 and / 10. 1234 becomes 4321. 100 becomes 1.Open example →cpp#include <iostream> using namespace std; int main() {
- 05GCD of Two NumbersIntermediateGCD in C++ with Euclid: (a, b) → (b, a % b) until b is 0. GCD(48, 18) is 6.Open example →cpp#include <iostream> using namespace std; int main() {
- 06LCM of Two NumbersIntermediateLCM in C++ is (a × b) / GCD. LCM(12, 18) is 36. Save a and b before Euclid.Open example →cpp#include <iostream> using namespace std; int main() {
- 07Palindrome CheckBeginnerPalindrome in C++: reverse the digits and compare. 121 is. 10 is not (reverse is 1).Open example →cpp#include <iostream> using namespace std; int main() {
- 08Prime CheckBeginnerPrime check in C++: test divisors up to sqrt(n). 1 is not prime. 2 is.Open example →cpp#include <iostream> #include <cmath> using namespace std;
- 09Primes in RangeIntermediateList primes in a range in C++. 10 to 30: 11 13 17 19 23 29. Reuses the sqrt test.Open example →cpp#include <iostream> #include <cmath> using namespace std;
- 10Armstrong NumberIntermediateArmstrong number in C++: 153 = 1³+5³+3³. Count digits, then sum powers.Open example →cpp#include <iostream> #include <cmath> using namespace std;
- 11nth Fibonacci NumberBeginnernth Fibonacci in C++. This program: position 1 is 0, position 10 is 34.Open example →cpp#include <iostream> using namespace std; int main() {
- 12Calculate the Power of a NumberBeginnerbase^exponent in C++ with pow. 2^8 is 256. ^ is XOR, not power.Open example →cpp#include <iostream> #include <cmath> using namespace std;
- 13Factors of a Natural NumberBeginnerFactors of n in C++: every i from 1 to n where n % i == 0. 24 → 1 2 3 4 6 8 12 24.Open example →cpp#include <iostream> using namespace std; int main() {
- 14Basic CalculatorBeginnerC++ switch calculator: + - * /. Forget break and + falls into -. Guard / 0.Open example →cpp#include <iostream> using namespace std; int main() {