-2

Currently working on a basic Number Generation program which finds the total odd and even numbers at the end of it whilst I learn C++. I currently have the issue where I cannot figure out how I can code the ability to find and display the total odd and even numbers into my current code.

Current Code:

#include<iostream>
#include<cstdlib>
using namespace std;

int main()
{

    // Providing a seed value
    srand((unsigned) time(NULL));

    // Loop to get 5 random numbers
    for(int i=1; i<=6; i++){
        
        // Generate random number between 10 and 20

        int random = 10 + (rand() % 11);

        // Print the random numbers
        cout<<random<<endl;
    return;
}

Have tried a few things but nothing seems to work with my current code.

mccreepyy
  • 21
  • 3
  • 1
    `if ((random % 2) == 0) { /* even */ } else { /* odd */ }` – Retired Ninja Apr 11 '23 at 03:01
  • @RetiredNinja where would I put this in code and how would I display it as I want my code to basically say: "Number of even numbers in the list #:" & "Number of odd numbers in the list: #" – mccreepyy Apr 11 '23 at 03:02
  • 1
    Sorry, I can't write your program for you. That should be enough for you to figure it out though. – Retired Ninja Apr 11 '23 at 03:05
  • Your loop generates 6 numbers, not 5 as the comment indicates. It's also missing a closing bracket and so your program won't compile anyway. The first comment literally gives you the construct to test if a value is even or odd. There are very few places it _can_ go, because it uses the variable named `random`. So where do _you_ think it should go? Should you test if your random value is even/odd _before_ you have generated it, or _after_? – paddy Apr 11 '23 at 03:06
  • How helpful. I have no clue what to do with this as it is literally the basics for an if statement which I know how to do but I don't know how to make it so it DISPLAYS the odd and even numbers – mccreepyy Apr 11 '23 at 03:07
  • @paddy yeah sorry that's a typo for the 5 in the comment and has been fixed in my code. I did not notice the still open bracket in the code and will get that fixed, I figured out right after I put the comment where to put the line of code so it is sitting there now. How does the line of code give me the construct to test it? All that I can see it actually does in the code is start a statements saying if variable random divided by 2 == 0 *comment* else *comment* – mccreepyy Apr 11 '23 at 03:10
  • You're already displaying values with `cout`. You're demonstrating that you know how to display a value. You then say you also know how if-statement works, so you'll then know that the if-else construct provides two different code paths depending on the result of the if-expression, and within those you can have absolutely whatever code you want. That includes the option for code that displays a value, which you already know how to do. The _comments_ are there as place-holders to show you where to put your actual code. I didn't think it could be much clearer. – paddy Apr 11 '23 at 03:11
  • @paddy I know how an if statement works because it seems the same as it is on python but my issue is, I don't know how to make it get the total number of odds and evens in the numbers it will generate. Like the if statement says if random/2 == 0, it doesn't seem like it will do anything to display a total number of evens in there. – mccreepyy Apr 11 '23 at 03:15
  • Okay, imagine how you would do this on paper, if you were given one number at a time. You'd probably keep a tally of how many odd and even values you've seen. You'd start at zero. In the computer, that would be `int oddCount = 0, evenCount = 0;` .. Now, in the loop, you determine _with the modulo operator_ (not division like you keep saying) if the value is odd or even, then increment the appropriate count. And _after_ the loop, you display the totals. – paddy Apr 11 '23 at 03:17
  • @paddy Alright so what I've done is under that comment for { Even } I put evenCount+1; and did the same for oddCount and then tried to print it. After doing this it has said that my identifier "random" is undefined on line 19 (cout << random << endl and when I try to run the code it says error :invalid operands of types 'long int() noexcept' {aka 'long int()'} and 'int' to binary 'operator%' – mccreepyy Apr 11 '23 at 03:30
  • 1
    C++ provides [Pseudo-random number generation](https://en.cppreference.com/w/cpp/numeric/random) which is quite good compared to the C `srand()`, `rand()` functions. You should really work with the language you have tagged. While you can call the C random-number routines in C++, why? – David C. Rankin Apr 11 '23 at 03:34
  • @DavidC.Rankin Because this is the only way we have been taught so far how to do it? We have literally only just started C++ and this is how they showed it to us for random number generation so I stuck to home base and didn't stroll on out to no mans land. – mccreepyy Apr 11 '23 at 03:38
  • @mccreepyy I can't even begin to guess what code you've written, based on that description. [Here](https://stackoverflow.com/search?q=%5Bc%2B%2B%5D+count+even+odd) are many questions and answers related to counting even and odd numbers. Check them out. And [Here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) is a list of C++ books that are recommended if you want to learn the language basics instead of guessing. If you are already familiar with Python, perhaps write this program in that language first, then translate it to C++. – paddy Apr 11 '23 at 03:45
  • @paddy Sweet as cheers, I'll give this a go in python and see if I can translate it to C++ – mccreepyy Apr 11 '23 at 03:46
  • No worries, just know there is a whole new wide-world of options available for random number generation in C++ (now more than a decade since its introduction). So it seems like a circumstance where your professor may be using a quite dated syllabus for teaching `:)`. Note the [cppreference.com](https://en.cppreference.com/) site it the best C++ reference on the net. Bookmark it and use it. (most all features have examples on how they are used as well) Good luck with your coding. – David C. Rankin Apr 11 '23 at 03:52
  • Danger: C++ has about as much in common with Python as English does with Japanese. If you do a line-by-line translation odds are good that[you'll get garbage](https://en.wikipedia.org/wiki/All_your_base_are_belong_to_us). In order to translate any language, you need to understand the intent of the writer and be able to present that intent in the new language. You need the context and the subtext. In order to do that you need sufficient knowledge of BOTH languages. – user4581301 Apr 11 '23 at 03:52
  • Side note: The way C++ is taught is a known problem that quite possibly produces more Python programmers than it does C++ programmers. In a way this is a good thing, It keeps the wages of competent C++ programmers high, but in every way that matters to a student it flat out sucks. The trend is to teach C++ based on lesson plans for C written in the 80s and 90s based on lesson plans for Pascal written in the 70s and 80s. Which were based on lesson plans for FORTRAN or COBAL back in the 60s and 70s. You may have to look outside the educational system to learn what you need to know. – user4581301 Apr 11 '23 at 03:57
  • How about adding two variables, `int even = 0, odd = 0;` Then in your loop after `int random = 10 + (rand() % 11);` add `if (random & 1) odd += 1; else even += 1;` Then after you exit your loop, `std::cout << "even : " << even << "\nodd : " << odd << '\n';`? Note: `random & 1` is equivalent to `random % 2 != 0` (but avoids the division inherently a part of the *modulo* operation). – David C. Rankin Apr 11 '23 at 03:58
  • I'll give that a go @DavidC.Rankin. The only issue I'm currently having is that it says the identifier even and odd is undefined on Line 18 and random is undefined on line 18 as well. My line 18 has ```if (random & 1) odd +=1; else even +=1;``` - Since I added in your suggestion, should I also removed my line of code for ``` if ((random % 2) == 0) even + 1; else odd + 1; ?? – mccreepyy Apr 11 '23 at 04:10
  • Above `srand()` in `main()`, you need `int even = 0, odd = 0;`. You only need `random & 1` (which just asks is the ones-bit set, e.g. `3` is `11` in binary -- the bit to the right is the ones-bit, for `4` the binary is `100` so the ones-bit is `0`) -- that how you can test even/odd. Another way to test even/odd is `random % 2` if that is equal `0`, it's even, otherwise it's odd. You just need one way to test, not both -- up to you which you use. – David C. Rankin Apr 11 '23 at 04:25
  • [std::uniform_int_distribution](https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution) – Jesper Juhl Apr 11 '23 at 05:37

1 Answers1

0

Alright, let's get your code compiling and work on the logic needed to count the even and odd numbers generated by calling rand().

Error Preventing Your Code From Compiling

  • unmatched brace following for loop declaration, e.g. for(int i=1; i<=6; i++){ (you have no closing '}'.

Logic Issues Preventing Your Code From Working

  • you have no variables to hold the number of even and number of odd values generated by rand().

Issue You Should Address

  • your loop iterates from i=1; i<=6 in order to loop five-times. While this captures the correct count, it shows a fundamental misunderstanding of indexing in C/C++ and it one of the most common errors when using the loop variable with an array. In C/C++ all arrays (or allocated collections of objects) are zero-indexed. That means valid indexes for a five-element array are 0-4 inclusive. In order to loop five-times and not index outside of your array bounds a proper for loop declaration would be for (int i = 0; i < 5; i++) { ... }. Being consistent with your loop limits will help you avoid problems later,
  • while fine for short example problems, see Why is “using namespace std;” considered bad practice?,
  • see also C++: “std::endl” vs “\n” and be aware of the differences.
  • avoid using MagicNumbers. If you need a constant, #define one or more, or since this is C++ use constexpr (coming soon to C in C23 in a limited manner). You have 5, 10, 11 -- huh? What are those? Give those constants names. (and in doing so, you provide one convenient location to make changes to the values at the top of your code...)

Putting it altogether, to find the number of even and odd values generated by rand(), you could do (adding the the comments above), something similar to:

#include <iostream>
#include <iomanip>
#include <cstdlib>

int main() {

  int odd = 0,   /* vars to track no. of odd / even numbers generated */
      even = 0;
  constexpr int nvals = 5,            /* number of values to generate */
                rngmin = 10,          /* range minimum for distribution */
                range = 11;           /* number of values in range */
  
  srand((unsigned)time(NULL));        /* seed random number generator */

  for (int i = 0; i < nvals; i++) {   /* loop 5 times, 0 <= i < 5 */
      
    /* get random number within range */
    int random = rngmin + (rand() % range);
  
    std::cout << std::setw(2) << random;  /* output value - 2-digts */
    if (random & 1) {                     /* if odd */
      odd += 1;                             /* increment odd */
      std::cout << "  :  odd\n";            /* output odd and newline */
    }
    else {                                /* otherwise */
      even += 1;                            /* increment even */
      std::cout << "  :  even\n";           /* output even and newline */
    }
  }
  
  /* output count of odd and even numbers generated */
  std::cout << "\nodd  : " << odd << "\neven : " << even << '\n';
}

(note: as discussed in the comments, random & 1 is the same as random % 2 != 0 -- use whichever you choose. The bitwise AND simply avoids a potential divide inherent in computing modulo. It's an academic difference)

Example Compile String

Always compile with full warnings enabled, and do not accept code until it compiles without warning.

Compiling with g++ you could do:

$ g++ -Wall -Wextra -pedantic -Wshadow -Werror -std=c++17 -Ofast -o rand-count-odd-even-c rand-count-odd-even-c.cpp

For the Microsoft compiler, using /W3 is sufficient to enable full warnings and /Wx will cause any warnings to be treated as errors.

Example Use/Output

$  ./rand-count-odd-even-c
13  :  odd
16  :  even
13  :  odd
13  :  odd
12  :  even

odd  : 3
even : 2

C++ Provides Pseudo-random number generation

See Pseudo-random number generation.

To do the same thing using the C++ psuedo random number generation library, simply choose which random-number generation engine you want to use (the std::mt19937 Mersenne Twister engine is a common choice) and use that engine to generate numbers within a std::uniform_int_distribution. The rest is the same except that 10 values are generated instead of 5, e.g.

#include <iostream>
#include <iomanip>
#include <random>

int main()
{
  int odd = 0,                /* variables to track no. of odd/even numbers */
      even = 0;
  constexpr int nvals = 10,   /* number of values to generate */
                rngmin = 10,  /* range minimum for distribution */
                rngmax = 20;  /* range maximum for distribution */
  
  /* create random device and mersenne twister engine */
  std::random_device rd;
  std::mt19937 mt (rd());

  /* create a uniform_int_distribution between rngmin and rngmax */
  std::uniform_int_distribution<int> uniform_dist(rngmin, rngmax);
  
  for (int i = 0; i < nvals; i++) {     /* loop nvals times */
    int rand = uniform_dist(mt);          /* get random in range */
    std::cout << std::setw(2) << rand;    /* output value 2-digts */
    if (rand & 1) {                       /* if odd */
      odd += 1;                             /* increment odd */
      std::cout << "  :  odd\n";            /* output odd and newline */
    }
    else {                                /* otherwise */
      even += 1;                            /* increment even */
      std::cout << "  :  even\n";           /* output even and newline */
    }
  }
  
  /* output count of odd and even numbers generated */
  std::cout << "\nodd  : " << odd << "\neven : " << even << '\n';
}

(compile the same)

Example Use/Output

$ ./rand-count-odd-even
20  :  even
11  :  odd
14  :  even
14  :  even
14  :  even
16  :  even
19  :  odd
16  :  even
13  :  odd
19  :  odd

odd  : 4
even : 6

Look both examples over and hopefully they will get you started. Bookmark cppreference.com and use it as your reference. See: The Definitive C++ Book Guide and List to pick up a good C++ book that will be needed given the C approach to the language you are starting off with.

Let me know if you have questions.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85