{"id":7446,"date":"2024-09-07T03:00:00","date_gmt":"2024-09-07T07:00:00","guid":{"rendered":"https:\/\/www.both.org\/?p=7446"},"modified":"2024-09-05T12:34:28","modified_gmt":"2024-09-05T16:34:28","slug":"learn-c-by-writing-a-number-guessing-game","status":"publish","type":"post","link":"https:\/\/www.both.org\/?p=7446","title":{"rendered":"Learn C by writing a number guessing game"},"content":{"rendered":"<div class=\"pld-like-dislike-wrap pld-template-1\">\r\n    <div class=\"pld-like-wrap  pld-common-wrap\">\r\n    <a href=\"javascript:void(0)\" class=\"pld-like-trigger pld-like-dislike-trigger  \" title=\"\" data-post-id=\"7446\" data-trigger-type=\"like\" data-restriction=\"cookie\" data-already-liked=\"0\">\r\n                        <i class=\"fas fa-thumbs-up\"><\/i>\r\n                <\/a>\r\n    <span class=\"pld-like-count-wrap pld-count-wrap\">    <\/span>\r\n<\/div><\/div>\n<p>I taught myself about programming on an Apple II+ computer, but eventually learned other programming languages like C and <a href=\"https:\/\/www.both.org\/?p=7047\">FORTRAN 77<\/a> when I entered university. Every time I\u2019ve learned about a new programming language, I practice by writing a simple game, like a number guessing game. This exercises several things in programming, including <em>how to store values in variables<\/em> and <em>how to compare values<\/em> and <em>how to print messages<\/em>.<\/p>\n\n\n\n<p>If you\u2019re new to the C programming language, or just want to learn more about it, try writing this number-guessing game.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"pseudo-random-numbers\">Pseudo-random numbers<\/h2>\n\n\n\n<p>In the standard C library, you can use the <code>rand<\/code> function to generate a <em>pseudo-random<\/em> number between zero and some very large number. The term \u201cpseudo-random\u201d is important, because the <code>rand<\/code> function uses an algorithm to simulate a random number generator. This isn\u2019t very secure if you want to do encryption, but it\u2019s good enough to write a \u201cGuess the number\u201d game.<\/p>\n\n\n\n<p>To use <code>rand<\/code>, you first need to <em>seed<\/em> the random number generator using the <code>srand<\/code> function. By seeding the random number with some other number that changes all the time, you can get a pretty good distribution of pseudo-random numbers. Most programmers seed the random number generator with the <code>time<\/code> function, which converts a time into <em>seconds<\/em>; if you use <code>NULL<\/code> as the time to convert, <code>time<\/code> gives you the <em>current<\/em> time in seconds.<\/p>\n\n\n\n<p>If you want to see this for yourself, you can write a short program to print the value of <code>time<\/code> every time you run the program:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdio.h&gt;\n#include &lt;time.h&gt;\n\nint main()\n{\n    printf(\"the time is %ld\\n\", time(NULL));\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>The <code>time<\/code> function returns a very large integer. You can use this to seed the random number generator like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    srand(time(NULL));<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"picking-a-random-number\">Picking a random number<\/h2>\n\n\n\n<p>Having seeded the random number generator, we can now select a random number to use as the <em>secret<\/em> number. The <code>rand<\/code> function will generate a random integer between zero and some very large value, but you can \u201cfold\u201d this number into a specific range using the <em>modulo<\/em> operator. Modulo (<code>%<\/code>) gives the <em>remainder<\/em> after dividing two numbers. So 4 divided by 2 is 2 <em>with a remainder of 0<\/em>, so <code>4 % 2<\/code> is 0. And 5 divided by 2 is 2 <em>with a remainder of 1<\/em>, so <code>5 % 2<\/code> is 1.<\/p>\n\n\n\n<p>To pick a random value from 1 to 100, we can use <code>rand() % 100<\/code>, which will return a number from 0 to 99. Add 1 to this number to get a random number from 1 to 100:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    secret = (rand() % 100) + 1;<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"reading-input\">Reading input<\/h2>\n\n\n\n<p>The user needs to guess the secret number, so the program must be able to read input from the user. In C, the standard way to do this is with the <code>scanf<\/code> function, which will <em>scan<\/em> the input using a <em>format<\/em> to locate one or more values.<\/p>\n\n\n\n<p>We can write these statements to prompt the user to make a guess, and then read that guess from the user:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    int guess;\n.\n.\n.\n    puts(\"Your guess:\");\n    scanf(\"%d\", &amp;guess);<\/code><\/pre>\n\n\n\n<p>The <code>scanf<\/code> function uses the format string to tell it what to look for; this is the same kind of format string that you would use for the <code>printf<\/code> function. In this case, <code>%d<\/code> says to read an integer (<code>%d<\/code>) value. The <code>scanf<\/code> function stores the value in the <code>guess<\/code> variable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"comparing-values\">Comparing values<\/h2>\n\n\n\n<p>The last step in the program is to compare what the user guessed with the secret number. If the guess is less than the secret number, we should print \u201cToo low\u201d like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    if (guess &lt; secret) {\n        puts(\"Too low\");\n    }<\/code><\/pre>\n\n\n\n<p>We can use an <code>else if<\/code> clause to do another test. If the guess is not <em>less than<\/em> the secret number, we should also check if the guess is <em>greater than<\/em> the secret value:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    if (guess &lt; secret) {\n        puts(\"Too low\");\n    }\n    else if (guess &gt; secret) {\n        puts(\"Too high\");\n    }<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"putting-it-all-together\">Putting it all together<\/h2>\n\n\n\n<p>We have all the key components to create a simple \u201cGuess the number\u201d game in C. The program starts the random number generator with a <em>seed value<\/em>, then picks a random secret number between 1 and 100. After that, it enters a <code>do<\/code> loop to read a guess from the user and print \u201cToo low\u201d or \u201cToo high\u201d depending on the guess. The loop will continue as long as the guess is <em>not equal to<\/em> the secret number. After the loop is done (when the guess is <em>equal to<\/em> the secret) the program prints \u201cThat\u2019s right!\u201d<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n\nint main()\n{\n    int guess, secret;\n\n    srand(time(NULL));\n\n    secret = (rand() % 100) + 1;\n\n    puts(\"Guess a random number from 1 to 100\");\n\n    do {\n        puts(\"Your guess:\");\n        scanf(\"%d\", &amp;guess);\n\n        if (guess &lt; secret) {\n            puts(\"Too low\");\n        }\n        else if (guess &gt; secret) {\n            puts(\"Too high\");\n        }\n    } while (guess != secret);\n\n    puts(\"That's right!\");\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Save this program as <code>guess.c<\/code> and compile it like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ gcc -o guess guess.c<\/code><\/pre>\n\n\n\n<p>Now we can run the program to play a simple number-guessing game! The secret number changes every time you run the program, so it will always be different:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ .\/guess\nGuess a random number from 1 to 100\nYour guess:\n1\nToo low\nYour guess:\n100\nToo high\nYour guess:\n50\nToo low\nYour guess:\n75\nToo low\nYour guess:\n88\nToo high\nYour guess:\n80\nToo high\nYour guess:\n78\nToo low\nYour guess:\n79\nThat's right!<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"guess-the-number\">Guess the number<\/h2>\n\n\n\n<p>This \u201cguess the number\u201d game is a great introductory program when learning a new programming language because it exercises several common programming concepts in a pretty straightforward way. By implementing this simple game in different programming languages, you can demonstrate some core concepts and compare details in each language.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The \u201cGuess the number\u201d game is a fun way to learn a new programming language.<\/p>\n","protected":false},"author":33,"featured_media":2725,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","footnotes":""},"categories":[69,150],"tags":[147,152],"class_list":["post-7446","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-fun","category-programming","tag-fun","tag-programming"],"modified_by":"Jim Hall","_links":{"self":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/7446","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/users\/33"}],"replies":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=7446"}],"version-history":[{"count":1,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/7446\/revisions"}],"predecessor-version":[{"id":7447,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/7446\/revisions\/7447"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/media\/2725"}],"wp:attachment":[{"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=7446"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=7446"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=7446"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}