Loading...

C++ Random

The compiling page left g++ -std=c++17 box.cpp -o box, ./box, and the three fixed prints left=10, right=2, and 12 from box.cpp. This page stays in the Quality and Wrap-up module on purpose. The workshop file on disk stays box.cpp so you keep one familiar source path. The new work names random: a value the program picks in a small range instead of writing only fixed tens and twos. Keep the same names and the same plus. Keep the same build and run habit. Add #include <random>, build std::mt19937 rng(42);, build std::uniform_int_distribution<int> die(1, 6);, store int roll = die(rng);, and print roll=. With seed 42 the fourth line shows roll=3. Summary waits for the next page.
Random here means asking a generator for one integer inside a closed range. Reading #include <random> is reading the header that brings those tools. Reading std::mt19937 is reading the engine this course uses. Reading the seed 42 is reading the lock that makes the teaching screen repeat. Reading std::uniform_int_distribution<int> die(1, 6) is reading the die faces from 1 through 6. Reading die(rng) is reading one draw. Keep #include <iostream> so the labeled prints and the total still work. Do not invent a summary chapter on this page.
Programs use this tool when a demo needs a chance number that is not hardcoded as 10 and 2. You do not need a new workshop file name. The build command stays familiar: one source file box.cpp, one output name box, one run that still starts with left=10, right=2, and 12, then adds the roll line. You compile only box.cpp again for this workshop file on disk.
Think of random as a sealed jar of numbered chips where the seed decides which chip comes out first in a teaching demo. The previous page named the build press. This page names the jar. Do not expect summary in the checked file. The printed left=10, right=2, 12, and roll=3 after a fresh build is the whole lesson point.

Above main, keep both includes. Keep int left = 10;, int right = 2;, the labeled prints, int total = left + right;, the total print, then the seeded engine, the die, the roll, the roll print, and return 0; with tidy braces. Keep #include <iostream> and add #include <random> at the top. After the file is saved, build with g++ -std=c++17 box.cpp -o box. Then run ./box. Do not invent a summary demo on this page.
Walk the path carefully from save to screen. You save box.cpp. The compiler reads that file. A successful build writes the executable named box. Running ./box starts main. It stores ten in left and two in right. The first print shows left=10. The second print shows right=2. The total uses plus, so twelve is stored. The third print shows 12. Then the engine starts with seed 42. The die spans 1 through 6. The first draw stores three in roll. The fourth print shows roll=3. Then main returns and the program ends. There are four printed lines on the screen: left=10, then right=2, then 12, then roll=3. The checked file never skips the build step in the story.
Say the steps out loud once while you read the file. Save box.cpp. Compile with g++ to box. Run ./box. Read left=10, right=2, 12, and roll=3. Return. That short story is the whole workshop path. Nothing else belongs in the checked body. No summary keyword. No keyboard wait. When the screen shows left=10, right=2, 12, and roll=3 after a fresh build, the story matched the source.

If you change the seed but keep the quiz answer for 42, the roll line may disagree with the page. That failed experiment stays in the prose. The checked path always uses seed 42 so the teaching screen and the quiz share one answer.
If the build fails about a missing random header, add #include <random> before you chase other errors. Random does not invent a program from broken text. The checked file keeps a clean body so the build succeeds.
A common mistake is to treat rand() from older C headers as the required tool on this page. Another common mistake is to invent the word summary as a required keyword here. A third mistake is to drop the seed and wonder why the quiz cannot name one roll. A fourth mistake is to wait for cin. A fifth mistake is to change left or right while practicing the die line.
This page stops before the next wrap-up tool, where the course path looks back across many pages. The next page names that tool once at the end. The random habit you have just written only shows one seeded draw on the same sum. Keep the printed 12 and the printed roll=3 so the order stays clear for a first careful reading of the file.
Remember that random adds a fourth line; it does not replace plus. You still need a correct total before the roll print. After a successful build and run the screen shows left=10, right=2, 12, and roll=3. After you undo a bad experiment the checked file returns to that seeded path. Stability of the checked file matters as much as learning the random spelling itself.

Open box.cpp. Keep left, right, and total with tidy layout. Add the random include, the seeded engine, the die, and the roll print. Save the file. Build with g++ -std=c++17 box.cpp -o box. Run ./box. Do not add a summary lecture inside the file. The program file name on disk stays box.cpp. The checked file is below, and the new habit is random with a clear seed and die range.

box.cpp random mt19937 die roll left right total

cpp
#include <iostream>
#include <random>

int main()
{
    int left = 10;
    int right = 2;
    std::cout << "left=" << left << std::endl;
    std::cout << "right=" << right << std::endl;
    int total = left + right;
    std::cout << total << std::endl;
    std::mt19937 rng(42);
    std::uniform_int_distribution<int> die(1, 6);
    int roll = die(rng);
    std::cout << "roll=" << roll << std::endl;
    return 0;
}

Rebuild with g++ -std=c++17 box.cpp -o box, then run ./box. If g++ is missing and clang++ is the compiler you installed, swap only the tool name: clang++ -std=c++17 box.cpp -o box. The screen shows left=10, then right=2, then 12, then roll=3.
Check the four printed lines first. The table gives each row its piece, so compare your run with it line by line before you move on to experiments. If the build fails, read the compiler message and fix the source. If the last fixed sum line is 8, total still uses minus. If the roll line is not roll=3, check the seed and the die bounds. If you ran an old executable, rebuild before you trust the random path.

📊 random draw and what the screen shows

Piece What the screen shows
First left=10, because the first labeled print still runs
Last roll=3, because seed 42 and die(1, 6) draw three first
Rule mt19937 plus uniform_int_distribution pick the roll; total still uses plus
Screen left=10 then right=2 then 12 then roll=3

Try one change at a time. Temporarily change the seed to 7, rebuild with the same g++ line, run ./box, see a different roll line, then restore seed 42 and rebuild again. Next, temporarily print a second die(rng) only in a practice attempt you undo, then return to the checked single roll. Each experiment changes one thing on purpose, so you see either a different fourth line or a reminder that the generator advances. Undo each change before the next one starts, so the file and the build line always return to the checked workshop version with roll=3 once again after every single careful try back on disk again.
This page ends the random tool and stops before the next one. The next page is summary, which looks back across the Quality and Wrap-up path. The random habit you have just written only shows #include <random>, std::mt19937 rng(42), std::uniform_int_distribution<int> die(1, 6), and roll= on left and right from box.cpp while total still prints 12. You leave with left=10, right=2, 12, and roll=3 on the screen. Count the printed lines before you leave. There are exactly four printed lines on that final screen, and those lines are left=10 then right=2 then 12 then roll=3 alone right there now after the final successful build run on disk today now after the random check.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top