using functions to write the code in C++ [closed]

You have a ways to go, your code does not do any of the things you want yet. However, you mentioned that you are a beginner so I fixed your code and set up a basic structure of how to get going. I left comments on what I changed and what you need to do. That being said, I don’t know what you mean by “Do a binary search on the 15th element”

#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

int ra()
{
    // You wanted a number between 0 and 999 inclusive so do not add 1
    // Instead do a modulus of 1000
    int r = rand() % 1000;
    return r;
}

int main ()
{
    // Do this to get different random numbers each time you run your program
    srand(time(NULL));

    // You have to call ra as a function. Do this by writing: ra()
    // Here I am storing 20 random numbers in an array
    int nums[20];
    for (unsigned int i = 0; i < 20; ++i)
    {
        nums[i] = ra();
        cout << "Index: " << i << ", random number: " <<  nums[i] << endl;
    }

    // Iterate to find the minimum number
    int minimum = nums[0];
    for (unsigned int i = 1; i < 20; ++i)
        if (nums[i] < minimum)
            minimum = nums[i];
    cout << "Minimum value: " << minimum << endl;

    // TODO: Find the maximum in basically the same way

    // TODO: Find the average by summing all numbers then dividing by 20

    // TODO: Find the median by sorting nums and taking the average of the two center elements

    // TODO: etc.

    return 0;
}

Leave a Comment