EDIT
I've seen a few wondering what I am asking for. I haven't written the algorithm for it yet, but after the program runs and outputs the 2 arrays, I need to output how many numbers matched. There is an example of that below. My apologies, I really thought that I made it as clear as possible. Here is the example again.
If the randomly generated array comes up with the numbers 0,1,2,3,4 in that order, and the user inputs into the "player" array the numbers 0,1,4,3,2 in that order, then they matched 2 digits (0 and 1). Basically it's not enough to just have the same numbers anywhere in the array, they must be in the same spot or index. I need to write an algorithm for this, though I have not yet. I'm sure I need a function with a for loop. I'm looking for any tips on how to go about it.
I've seen many iterations of this program on StackOverflow but none have been able to help me out so here I am asking for help.
I have this program that has 2 arrays. In one array that generates 5 random numbers from 0-9, the name is winningDigits. The other array (player) is for 5 numbers the user inputs. The goal of the user is to input 5 numbers and hope they all match with the randomly generated numbers.
I am almost done with the program, my only issue is trying to output how many digits were matched. For digits to match, they must be in the same spot in the player array as the winningDigits array.
For example
If the randomly generated array comes up with the numbers 0,1,2,3,4 in that order, and the user inputs into the "player" array the numbers 0,1,4,3,2 in that order, then they matched 2 digits (0 and 1). Basically it's not enough to just have the same numbers anywhere in the array, they must be in the same spot or index.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <iomanip>
using namespace std;
int main() {
int player[5];
int size = 5;
int count = 0;
cout << "Welcome to Lottery Simulator." << endl << endl;
cout << "Enter 5 numbers ranging from 0-9 one at a time, enter -1 when finished." << endl;
// Loop for user input
cout << "Enter number: ";
cin >> player[count];
while (player[count] != -1)
{
count++;
cout << "Enter number: ";
cin >> player[count];
}
cout << endl;
cout << "Winning Numbers User Numbers" << endl;
cout << "--------------- ------------" << endl;
// Generating random winning numbers
srand(time(0));
int winningDigits[size];
for (int i = 0; i < size; i++) {
winningDigits[i]= rand() % 10;
cout << setw(8) << winningDigits[i] << setw(17) << player[i] << endl;
}
return 0;
}
Now I'm thinking I'll need to make a function with a for loop, but so far I'm stuck. Just in case it wasn't clear enough, I am looking to output how many digits were matched. I hope my example from above will help you all understand what I'm looking for. Sorry, this is only my second post here and I am trying to make everything as clear as possible. Please ask if you need any information or help in understanding what I wrote.
Related
I'm taking an elementary programming course where we use C++ and I'm stuck on a couple of assignments. Please excuse my potentially bad terminology going forward. Part of my basic program I'm writting asks "Write down 5 integers: " and then the user gets to pick the integers and a message "You wrote the integers: n1 n2 n3 n4 n5" is returned. There are several of these questions and I'm not allowed to use more then one variable of the same type. The problem is that the user could respond with n1 n2 n3 n4 n5 hello, and hello is supposed to be ignored. How do I accomplish this?
If we for a moment assume that we are only to write down one integer instead of 5, then perhaps something along the lines of the code below would work.
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Write down an integer: "
<< flush;
cin >> num;
cout << "You wrote the integer: "
<< num
<< endl;
}
But how do I do this with five integers. Further, how do I ignore that extra hello? I'm assming that cin.ignore is to be used here somehow.
If you want to repeat the procedure 5 times, you could just copy-paste it, but that's definitely not a good practice. What's much better is to use a loop/cycle, like for.
You'll also need to store all 5 integers into memory. You could use 5 variables (int n1, n2, n3...), but again, that's not a very good practice and as you state, that's not allowed in your case. Solution is to use an array, which can hold several values of the same type.
Here is a working example with explaining comments:
int nums[5]; // this array will hold 5 integers
int n;
cout << "Write down 5 integers:" << endl;
for (n = 0; n < 5; ++n) { // run code in the braces 5 times
cin >> nums[n]; // store typed integer into nth position of the array
}
cout << "You wrote: ";
for (n = 0; n < 5; ++n) { // run code in the braces 5 times
cout << nums[n] << " "; // print integer at nth position of the array
}
Note: One could say that both nums and n are of the same type, int. In that case, you could extend the array nums to the size of 6 items and use the last one (to which you can refer as nums[5]) as an indexing variable for the loops.
I'm new to the community and to coding as well. Right now I'm taking Intro to Computer Science at my CC and we're learning C++. Anyways, I have to create a program which asks the user for a number, which will be the size indicator of the array new_array. The program then asks the user to input the numbers one by one and afterwards, outputs them in reverse.
#include
using namespace std;
int main()
{
cout << "How many numbers?\n";
int numbers; // holds amount of numbers to be entered into array
cin >> numbers;
int new_array[numbers];
for(int counter = 0; counter < numbers; counter++)
{
cout << "Enter number " << counter << endl;
cin >> new_array[counter];
}
cout << "You entered: " << endl;
for(int i = numbers; i >= 0 ; i-- )
{
cout << new_array[i] << endl;
}
return 0;
}
I understand how to do this and for the most part, my program worked. It outputs the numbers entered in reverse just fine, but before it does so, it outputs large, strange numbers. For example, if the user enters 5 as the amount of numbers to be entered, and then enters 1, 2, 3, 4 and 6 as the 5 numbers respectively, the program outputs the number 4669476 first and then outputs the numbers in the array in reverse. Can anyone explain to me what I did wrong and how I could fix this? Thank you in advanced!
PS be gentle! I'm a newbie at this
This loop reads out of bounds:
for(int i = numbers; i >= 0 ; i-- )
{
If you follow i through in your head you will see that you output entries numbers through to 0, when in fact you should output entries numbers-1 through to 0.
An alternative patterns is:
for( int i = numbers; i--; )
Or you can use the fabled --> operator.
It would be possible to "simply" start from numbers - 1, however the loop pattern you have used would not work for an unsigned counter (because they are always >= 0). IMHO it is a good idea to use a pattern which works for all types; then you are less likely to make a mistake in future.
In your display for loop, you started from i = numbers which is out of the array's range. Since the array starts from 0 till size - 1, then you need to start from i = numbers - 1 all the way to >=0.
Because you start from array[numbers] which is not defined.
array[0], array[1], ... array[numbers-1] are defined.
In C arrays are stored from 0 instead of 1. So the last number is stored in array[4]
So when you're writing it out you should start an numbers - 1 instead of just numbers.
Because you are starting the index from out of range giving you garbage value.
your code should look some thing like this
for(int i = numbers-1; i >= 0 ; i-- )
{
cout << new_array[i] << endl;
}
It seems like I always come here to ask silly questions, but here it goes. As of right now I am in my first compsci course and we are learning c++. I've had an extremely basic introduction to c before, so I had thought I'd go above and beyond my current assignment. Now I was doing this just to showboat, I felt like if I didn't practice my previous concepts they would eventually fade. Anyways, on to the problem! I was supposed to write some code that allowed the user to input their initials, and a series of exams. Now this was supposed to accomplish three things: average the exams, print out the entered exams, and print out their initials. Well, what was a simple assignment, got turned into a huge mess by yours truly.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string uInitials;
float avgExam = 0, tExam = 0;
int aExams[10] = {'0'};
int i, nExam = 0, cExam;
cout << "Enter your three initials!";
cin >> uInitials;
do
{
cout << "Enter your exam(s) to be averaged. Enter 0 when complete!\n";
cin >> cExam;
aExams[nExam] = cExam; //I used this before nExam was incremented, in order to get nExam while it was '0' That way the first exam score would be properly saved in the first space
nExam++;
tExam += cExam; //This is just to add all the exams up to later calculate the average
}
while(cExam != 0);
avgExam = tExam/(nExam - 1); //subtracted '1' from nExams to remove the sentinel value from calculations.
cout << "The average for initials: " << uInitials << " is: " << avgExam << endl;
cout << "This average was obtained using the following scores that were entered: \n";
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
return 0;
}
The previous is my code, and the problem is that I'm getting output errors where it adds two '0's when I print out the list of entered exams. Also I feel like I made the whole do{}while() loop one huge clunky mess, so I'd like to refine that as well. If anyone could assist this poor, ignorant, beginner I would greatly appreciate it. Thank you for your time!
Some advice that i can give is for example in the 5th line there is no need
to put the 0 between ' ' and not even need to use the assign = operator.
You can initialize the array like this:
int aExams[10]{0};
Which will initialize all elements to 0,but can't be used for other value.
For example you won't have all the elements with value 1 if you write
int aExams[10]{1};
If your intention to initialize all elements in an array is with value other than 0 you can use fill_n(); function.
fill_n(aExams, 10, 1);
The first argument is the name of the array, the second is up-to which element you want to be initialized with the third argument, and the third is the value you want all elements to have.
Do not leave uninitialized variables like in line 6 with cExam and i variables. Initialize it like cExam=0; (copy-assign initialization) or cExam(0); (direct initialization). The latter calls the constructor for int built-in type.
A negative i see in your do-while loop is that you do not make sure that the user will enter under 10 exams,bad things will happen if the user tries to input 15 exams in an array that can hold only 10.
Just change the while to something more like this:
while( cExam != 0 && (nExam<10) );
You can also write the first two lines of the do-while loop outside the loop.
It is needed only once to tell the user that to stop the loop he/she needs to enter 0. There is no need to tell them this on every iteration plus that you will have a good performance benefit if you put those two lines outside the loop.
Look here how i would write the code and ask if you have any questions.
http://pastebin.com/3BFzrk5C
The problem where it prints out two 0's at the end of your code is a result of the way you wrote your for loop.
Instead of:
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
Use:
for (i = 1; i < (nExam); i++)
{
cout << aExams[i - 1] << endl; //Used a for loop to prevent redundancy
}
I'm new here and this forum has been a great help! Unfortunately, I'm not able to find the answer to my issue here or anywhere else on the web. I was hoping some of you can give me some help or tips on how to go about this.
The program will generate random numbers based on the max limit and the amount of random numbers that will generate.
I'm also required to find the smallest, largest number, as well as the average from all the numbers generated in the loop. The average I can find using the sum/MAX_COUNT_NUM. Unfortunately, I am stuck finding the smallest and largest number. Been at this for the past 6 hours. Please help anyway you can. Thank you.
#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <iomanip>
using namespace std;
int main(){
int UP_MAX, MAX_COUNT_NUM, RAND_NUM, MIN_COUNT_NUM;
cout << "This program creates random numbers" << "\n" << "\n";
cout << "Enter the upper limit of all generated random numbers: ";
cin >> UP_MAX;
cout << "\n" << "\n";
cout << "Enter the count of random numbers: ";
cin >> MAX_COUNT_NUM;
cout << "\n" << "\n";
cout << "Creating " << MAX_COUNT_NUM << " random numbers from 1 to " << UP_MAX << ": " << "\n" << "\n";
MIN_COUNT_NUM = 1;
int LARGE = 0;
int SMALL = 0;
for (; MAX_COUNT_NUM >= MIN_COUNT_NUM; MIN_COUNT_NUM++)
{
RAND_NUM = rand() % UP_MAX + 1;
cout << setw(8) << RAND_NUM;
if (RAND_NUM < SMALL)
{
SMALL = UP_MAX + 1;
}
if (RAND_NUM > LARGE)
{
LARGE = RAND_NUM;
}
}
Unfortunately, I need to do this without arrays and vectors. In my head, I'm thinking it should work as well but it doesn't. The largest number comes out fine, but the smallest comes out as 0 which makes me scratch my head.
I'm taking a beginners course and this got me stumped, so my way of thinking may be off beat. If there are any other tips you can provide, I definitely appreciate it.
The problem is with the initial values that you picked for LARGE and SMALL: you set both of them to 0, which is incorrect: you should set them both to the first random number that you generate.
Alternatively, you can set SMALL to the largest possible int, and LARGE to the smallest possible int. Use <limits> header and std::numeric_limits<int> class.
Note: SMALL = UP_MAX + 1; should be SMALL = RAND_NUM;
This is what I have to do:
A teacher has asked all her students to line up single file according to their first name. For example, in one class Amy will be at the front of the line and Yolanda will be at the end. Write a program that prompts the user to enter the number of students in the class, then loops to read in that many names. Once all the names have been read in it reports which student wourld be at the front of the line and which one would be at the end of the line. You may assume that no two students have the same name. Input Validation: Do not accept a number less than 1 or greater than 25 for the number of students.
This is what I have so far:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int StudentNum;
cout << "How many student are in the class?\n";
cin >> StudentNum;
char sname[StudentNum + 1][25];
if (StudentNum < 1 || StudentNum > 25)
{
cout << "Please enter a number between 1-25 and try again\n";
return 0;
}
for (int i = 1; i <= StudentNum; i++);
{
cout << "Please enter the name of student #" << i << endl;
cin >> sname[i];
}
for (int output = 0; output <=StudentNum; output++);
{
cout << endl << sname[output] << endl;
}
system ("pause");
return 0;
}
Am I missing something about arrays??
You cannot create such an array because its length has to be known at compile time (i.e., it cannot be the result of an expression such as StudentNum + 1).
You can solve this issue because by the problem definition you know an upper bound for the array size, so you can use that as a compile time constant.
However, this problem can be solved without using an array at all. Read the wording carefully.
Hint for the solution without arrays: Think of the array as a single piece of paper (variable) with all the names written one after another. Not using an array then means that you have to be able to solve the problem without looking at all the names at once. How would you come to the answer if I only allowed you to see the names one by one?
Another hint: The problem is still solvable if there were several trillion students in the class (with unique names no less), i.e. more than could possibly fit in the computer's memory at any one time.
C++ array dimensions must be known at compile time (ie not dependent on user-entered variables at run-time). Use strings instead:
string sname[25];
If you were using something besides char arrays, you could also use a vector.
Think about what the problem statement is actually asking for. Your program only needs to output the first and last names alphabetically. Do you actually need to store all the names to do that?
Just for fun, here's how I would do it. Don't turn this in unless are ready to explain to your teacher how it works.
struct MinMax {
std::string min;
std::string max;
MinMax& operator+(const std::string& kid) {
if( min.empty() || kid < min) min = kid;
if( max.empty() || kid > max) max = kid;
return *this;
}
};
int main() {
int nKids;
std::cout << "How many students? " << std::flush;
std::cin >> nKids;
std::cout << "Enter students' names, followed by EOF\n";
MinMax mm(std::accumulate(
std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
MinMax()));
std::cout << mm.min << ", " << mm.max << "\n";
}