I want to print the first number that first counts to 4, for example, I have this random function, I want to see the first number that reaches 4 times. so it's the first number that prints himself 4 times. For example:
int n;
int count1 = 0;
int count2 = 0;
int count3 = 0;
while (true) {
cout << "Enter a number btween 1-3" << endl;
cin >> n;
if (n == 1) {
count1++;
}
if (n == 2) {
count2++;
}
if (n == 3) {
count3++;
}
if (count1 == 4) {
cout << "You printed the number 1 4 times!";
break;
}
if (count2 == 4) {
cout << "You printed the number 2 4 times!";
break;
}
if (count3 == 4) {
cout << "You printed the number 3 4 times!";
break;
}
But what would I do if it was 1-1000 numbers not just 1-3 what would I do then?
I want to do that but on a random function - the first number that the count of that number is 4 times print the number -
int fun() {
srand(time(NULL));
return rand() % 3;
}
Then I want to do in main that first number that reaches for example 4 times print this number.
I tried doing something like this:
for (int i = 0; i < 31; i++) {
arr[fun()]++;
cout << arr[fun()];
if (arr[fun()] == 4) {
cout << arr[fun()];
}
}
You would use an collection (such as a vector) for that, rather than a thousand separate variables :-)
For a start, if you want random numbers in the range 1..3, you would use (rand() % 3) + 1. However, you can use the range 0..n-1 rather than 1..n and just adjust the value after the loop.
First step is to create and initialise the counts of each number to zero:
const int SZ = 1000;
std::vector<int> count(SZ, 0);
Then your loop just generates random numbers and adjusts the relevant count, until one of them reaches the target value:
int num;
for (;;) { // infinite loop
num = rand() % SZ;
++count[num];
if (count[num] == 4)
break; // exit infinite loop when one of them reaches four.
}
Then you just simply output the one that reached four first. Note that, since we're doing 0..999, we map that to 1.1000:
std::cout << ++num << " reached a count of four first\n";
A complete program showing this can be seen below:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
int main() {
srand(time(nullptr));
const int SZ = 1000;
std::vector<int> count(SZ, 0);
int num;
for (;;) { // infinite loop
num = rand() % SZ;
++count[num];
if (count[num] == 4)
break; // exit loop when one of them reaches four.
}
std::cout << ++num << " reached a count of four first\n";
}
A sample run of that (ensuring a delay so random number generator gets different seed):
>> for i in {1..10} ; do sleep 1 ; ./testprog ; done )
296 reached a count of four first
520 reached a count of four first
205 reached a count of four first
239 reached a count of four first
822 reached a count of four first
260 reached a count of four first
421 reached a count of four first
444 reached a count of four first
21 reached a count of four first
92 reached a count of four first
The last answer was out of range. My answer is using only an array
while(1) {
int f = rand() % 3;
count[f]++;
cout << f << endl;
if (count[f] == 4) {
cout <<"4 times" <<f;
break;
}
}
Related
Newer to coding and im stuck, Need to make a array thats stores 5 numbers (1-9), then i need to check that array for duplicates if there is duplicates i need to replace that number either with a whole new random line no duplicates (seems like the easier option) or just replace that one number,
after that wants me to get users 5 numbers guess store that in a array, display that array at the bottom along with these under each of the numbers
// The * = means the number is in the exact location
// The - = means the array does not contain that number
// The + = means the array contains the number but its not in the right location
All the arrays want the digits to be entered one at a time
repeat steps till user gets all the numbers to * then end game with completion msg.
My true problem lies with step 4 and step 7;
Below is the code ive been working on today but any help would be truly appreciated
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void game_instructions(int n);
bool search_array(int a[], int n, int t);
int main()
{
//Step 1: Declare your variables and constants
const int SIZE = 5; //this constant stores the length/size of the code
int randcode[SIZE]; //this array stores the code generated randomly by the computer
int guess[SIZE]; //this array stores the code inputted by the player/user
//you may add more variables as needed
//Step 2: Output game instructions by calling function game_instructions
game_instructions(SIZE);
//Step 3: Generate a random code and store it in the array randcode one digit at a time.
//Each digit should be between 0 and 9 and should be stored as one array element
//Recall that rand() % 10 can be used to generate a number between 0 and 9
srand(time(0));
for(int i=0;i<SIZE;i++)
randcode[i]= (rand() % 10); //Computers random 5 numbers generated
cout<<"\nRandom C-numbers::"<<endl;
for(int i=0;i<SIZE;i++)
cout<<randcode[i] << " ";
//Step 4: Repeat step 3 if the array randcode contains duplicates
//You must use function contains_duplicates to implement this step
//Step 5: Ask the user for his guess and store it in the array guess.
//Read one digit at a time, validate it to make sure it is between 0 and 9, and store it as one array element
for (int i=0; i<SIZE; i++) {
cout<<"\nEnter Digit "<< i+1 << ": ";
cin >> guess[i];}
cout << endl;
//Step 6: Output the array guess on a single line with a space after each element (see the sample output provided)
for (int n=0; n < SIZE; ++n) {
cout << guess[n] << " ";
}
//Step 7: Compare the randomly generated code (randcode) with the user's guess (guess)
//and display feedback for each digit as: *, + or –, as explained below:
//For each digit in the user's guess do the following:
// If it matches the digit from the random code (both value and position), output *
// Otherwise, if it appears anywhere in the random code, output + (use function search_array here)
// Otherwise, output -
//Step 8: Repeat steps 5,6,7 until all digits have been guessed correctly
//Step 9: Output congratulations message
cout << endl << endl;
cout << "Good job! You guessed the code!";
return 0;
}
void game_instructions(int n)
//This function outputs the game instructions.
//Its parameter n represents the length of the code.
{
cout << "A random " << n << " digit code has been generated. You have to guess it. \n";
cout << "For every digit you will receive feedback in the form of *, + or - \n";
cout << " * means the digit is in the code and it is in the correct position.\n";
cout << " + means the digit is in the code but it is not in the correct position.\n";
cout << " - means the digit is not in the code.\n";
}
bool search_array(int a[], int n, int t)
//This function searches the array a (of size n) for a target value t.
//If t is found in the array the function returns true; otherwise it returns false.
{
for (int i = 0; i < n; i++)
{
if (a[i] == t) return true;
}
return false;
}
bool contains_duplicates(int a[], int n)
//This function searches the array a (of size n) and returns true if the array contains duplicates; otherwise, it returns false.
{
for (int i = 0; i < n; i++)
{
//compare element a[i] with all the remaining elements from index i+1 to n
for (int j = i+1; j < n; j++)
{
if (a[i] == a[j]) return true;
}
}
return false;
}
I got most the side code done but im just stumped on how to get this array to match any help would be nice
Here is how I would implement the program to generate the number without duplicate:
Step3 would look like this:
int tempNumber;
int i = 0;
while (i < SIZE) {
tempNumber = (rand() % 10);
if (contains_duplicates(randcode, tempNumber, i) == false) {
// every time there is no duplicate we push and add i by 1;
randcode[i] = tempNumber; // Computers random 5 numbers generated
i++;
}
}
contains_duplicates function would look like this:
bool contains_duplicates(int arr[], int tempNum, int currentArrSize)
// This function searches the array a (of size n) and returns true if the
//array
// contains duplicates; otherwise, it returns false.
{
for (int j = 0; j <= currentArrSize; j++) {
// if the array[index] not equal generated number the loop will
//iterate again without going to the line below
if (arr[j] != tempNum) {
continue;
}
// if the array[index] equal the function will return true and end
//the function
// uncomment this to check how many time it duplicate (not
//necessary tho)
//cout << "if return true, this will appear"<< endl;
return true;
}
// if the loop is done and no duplicate, function will return false
return false;
}
With this method it is not necessary to do step 4 because we already prevent duplicate array!
Here is the last problem from your question which is step 7:
cout << endl;
for (int i = 0; i < SIZE; i++) {
if (guess[i] == randcode[i]) {
cout << "* ";
} else if (search_array(randcode, SIZE, guess[i])) {
cout << "+ ";
} else {
cout << "- ";
}
}
Seems like the problem has been solved, now try to implement step 8 by yourself, good luck :)
This is my code that I have currently but it always outputs 0 I'm trying to get it to output the reverse of the input including the negative for example -123425 will be 524321-:
#include<iostream>
using namespace std;
int main() {
int number;
bool negative;
cout << "Enter an integer: ";
cin >> number;
while (number != 0) {
number % 10;
number /= 10;
}
if (number < 0) {
negative = true;
number = -number;
cout << number << "-";
}
else {
negative = false;
}
cout << number << endl;
return EXIT_SUCCESS;
}
You could convert the input to a std::string, then reverse its content with std::reverse.
#include <algorithm> // reverse
#include <cstdlib> // EXIT_SUCCESS
#include <iostream> // cin, cout, endl
#include <string> // string, to_string
using namespace std;
int main()
{
cout << "Enter an integer: ";
int number;
cin >> number;
auto str = to_string(number);
reverse(str.begin(), str.end());
cout << str << endl;
return EXIT_SUCCESS;
}
Reading to an int first - and not to a std::string - makes sure that we parse a valid integer from the input. Converting it to a std::string allow us to reverse it. This let us feed inputs like -042 and -0 to the program, and get 24- and 0 as a result, not 240- and 0-.
After the first loop
while (number != 0) {
number % 10;
number /= 10;
}
the variable number is equal to 0.
So the following if statement
if (number < 0) {
negative = true;
number = -number;
cout << number << "-";
}
else {
negative = false;
}
does not make sense.
Pay attention to that it can happen such a way that a reversed number can not fit in an object of the type int. So for the result number you should select a larger integer type.
Here is a demonstrative program that shows how the assignment can be done.
#include <iostream>
int main()
{
std::cout << "Enter an integer: ";
int n = 0;
std::cin >> n;
bool negative = n < 0;
const int Base = 10;
long long int result = 0;
do
{
int digit = n % Base;
if ( digit < 0 ) digit = -digit;
result = Base * result + digit;
} while ( n /= Base );
std::cout << result;
if ( negative ) std::cout << '-';
std::cout << '\n';
return 0;
}
Its output might look like
Enter an integer: 123456789
987654321-
I think trying to visualize the process of your program is a great way to see if your solution is doing what you expect it to. To this end, let's assume that our number is going to be 12345. The code says that while this is not equal to 0, we will do number % 10 and then number /= 10. So if we have 12345, then:
number % 10 --> 12345 % 10 --> 5 is not assigned to any value, so no change is made. This will be true during each iteration of the while loop, except for different values of number along the way.
number /= 10 --> 12345 /= 10 --> 1234
number /= 10 --> 1234 /= 10 --> 123
number /= 10 --> 123 /= 10 --> 12
number /= 10 --> 12 /= 10 --> 1
number /= 10 --> 1 /= 10 --> 0 (because of integer division)
Now that number == 0 is true, we proceed to the if/else block, and since number < 0 is false we will always proceed to the else block and then finish with the cout statement. Note that the while loop will require number == 0 be true to exit, so this program will always output 0.
To work around this, you will likely either need to create a separate number where you can store the final digits as you loop through, giving them the correct weight by multiplying them by powers of 10 (similar to what you are hoping to do), or cast your number to a string and print each index of the string in reverse using a loop.
Quite simple:
int reverse(int n){
int k = abs(n); //removes the negative signal
while(k > 0){
cout<<k % 10; //prints the last character of the number
k /= 10; //cuts off the last character of the number
}
if(n < 0) cout<<"-"; //prints the - in the end if the number is initially negative
cout<<endl;
}
int main(){
int n = -1030; //number you want to reverse
reverse(n);
}
If you don't want to use String or have to use int, here is the solution.
You want to check the negativity before you make changes to the number, otherwise the number would be 0 when it exit the while loop. Also, the modulus would be negative if your number is negative.
number % 10 only takes the modulus of the number, so you want to cout this instead of just leaving it there.
The last line you have cout << number << endl; will cout 0 since number has to be 0 to exit the while loop.
if(number < 0) {
number = -number;
negative = true;
}
while (number != 0) {
cout << number % 10;
number /= 10;
}
if (negative) {
cout << "-"<< endl;
}
EDIT: With a broader assumption of the input taking all int type values instead of the reversed integer being a valid int type. Here is a modified solution.
if(number < 0) {
negative = true;
}
while (number != 0) {
cout << abs(number % 10);
number /= 10;
}
if (negative) {
cout << "-"<< endl;
}
using namespace std;
int main()
{
int number,flag=1;
long long int revnum=0;
bool negative;
cout << "Enter an integer: ";
cin >> number;
if(number<0)
{ negative=true;
}
while (number > 0) {
revnum=revnum*10+number %10;
number /= 10;
}
if (negative)
{ revnum=(-revnum);
cout << revnum << '-'<<endl;
}
else
{ cout<<revnum<<endl;
}
return 0;
}
A few changes I did -
checking the number whether it's negative or positive
if negative converting it to positive
3.reversing the number with the help of a new variable revnum
4.and the printing it according to the requirement
To reverse the num-
revnum=revnum*10 + number%10
then num=num/10
like let's try to visualize
1.take a number for example like 342
2.for 1st step revnum=0 so revnum*10=0 and num%10=2 , so revnum will be 2
and the number now is num/10 so 34
4.next now rev = 2 the rev*10=20 and num%10=4 then rev*10 + num/10 =24
5.finally we get 243
Hope it helps :)
edit:-
just a small edit to solve the problem of the overflow of int , made revnum as long long int.
I am brand new to C++, and am trying to make a simple program to determine if a user-entered integer is four digits, and if so, to reverse the order of said digits and print that output.
I have a (mostly) working program, but when I try, one of two things happens:
a) if line 16 is commented out and line 17 is active, then the program prints out an infinite number of reversed numbers and the IDE (in this case, repl.it) crashes; or
b) if line 17 is commented out and line 16 is active, then the program prints out one correct line, but the next line is "Your number is too short...again" (look at code below)
#include <iostream>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main() {
int n, reversedNumber, remainder;
bool loopControl;
char userFinalResponse;
reversedNumber=0;
cout<<"Input a 4 digit integer and press Return\n"<<endl;
cin>>n;
while (loopControl=true){
//if ((n>9999)||(n<1000))
if ((n>9999)||((n<1000)&&(n>0)))
{
cout<<"Your number is too short or too long. Please try again.\n"<<endl;
cin>>n;
loopControl=false;
} else {
while(n != 0)
{
remainder = n%10;
reversedNumber=reversedNumber*10+remainder;
n /= 10;
loopControl=true;
}//closing brace for reversal loop
cout<<"Your reversed number is "<<reversedNumber<<"\n"<<endl;
}//closing brace for else
}//closing brace for "while (loopControl>0){"
return 0;
}//closing brace for "int main() {"
You can try this:
int number = 1874 //or whatever you need
auto str = std::to_string(number);
if (str.length() == 4) {
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
}
I suggest you to give a look at the algorithm header that contains a lot of useful methods that can help you while developing programs.
According to the cpp tutorials = is the assignment operator, not the comparison operator. Because of this your while loop will never terminate. You can simply initialize loopControl to true, and then set it to false when it's okay to exit:
int n, reversedNumber, remainder;
bool loopControl = true; //Initialize to true
char userFinalResponse;
reversedNumber = 0;
cout << "Input a 4 digit integer and press Return\n" << endl;
cin >> n;
while (loopControl) {
//if ((n>9999)||(n<1000))
if ((n>9999) || ((n<1000) && (n>0)))
{
cout << "Your number is too short or too long. Please try again.\n" << endl;
cin >> n;
loopControl = true; //need to keep on looping
}
else {
while (n > 0)
{
remainder = n % 10;
reversedNumber = reversedNumber * 10 + remainder;
n /= 10;
loopControl = false; //Ok to exit
}//closing brace for reversal loop
cout << "Your reversed number is " << reversedNumber << "\n" << endl;
}
}
This question already has answers here:
Elegant ways to count the frequency of words in a file
(8 answers)
Need a code that counts the same digit in a number
(2 answers)
Closed 5 years ago.
Was trying out a question that I saw online, the questions requires the user to input the number of time the random number will be generated and to count how many digit 1, digit 2, digit 3, are there int he generated number.
For example
Enter number of time to loop : 4
2241 1204 5532 8593
There are 8 digits 1, digit 2 and digit 3.
code:
int main()
{
int input;
int ranNum;
cout << "Enter the number of time to loop" << endl;
cin >> input;
srand(time(NULL));
int i = 0;
if (input < 0 || input > 50)
{
cout << "Invalid entry";
}
else
{
while(i++ < userInput)
{
ranNum = (rand() % 10000);
cout << ranNum<< " ";
}
}
return 0;
}
The questions stated that using a switch case will be easier to get it done. However, I am not too sure how can a switch case worked for this. Or, is there any other method that I can use?
I've completed the code for the first 2 part, which is requiring user to input number as well as generating the random number based on user input
To count the number of occurrences of 1, 2 and 3 in a single integer value it would be easiest IMO to convert the integer into a string and then count the digits you are interested in:
int countDigits(int number, std::string digitsOfInterest = "123") {
int ret = 0;
std::string numberAsString = std::to_string(number); // convert it to string
for (const char& digit : numberAsString) { // loop over every character
if (digitsOfInterest.find(digit) != std::string::npos) {
ret++;
}
}
return ret;
}
Simply pass a randomly generated number into the function and add up the results. As you can see, by changing digitsOfInterest to another string, you can alter the digits you want to count.
PS.: Since I'm assuming that you have access to C++11 I would recommend to change your number generation to <random>.
Here is a non C++11 solution which works the same way the above one does:
int countDigits(int number, std::string digitsOfInterest = "123") {
int ret = 0;
std::ostringstream oss;
oss << number;
std::string numberAsString = oss.str(); // convert it to string
for (size_t i = 0; i < numberAsString.size(); ++i) { // loop over every character
if (digitsOfInterest.find(numberAsString[i]) != std::string::npos) {
ret++;
}
}
return ret;
}
Here is an example:
std::cout << "This number: '1243' contains " << countDigits(1243) << " times a digit of 1,2 or 3\n";
Result: This number: '1243' contains 3 times a digit of 1,2 or 3
I divided it to functions so it will be easier to understand.
I used switch case because that what you asked, but there are other ways as well.
#include<time.h>
#include <iostream>
#include <stdlib.h>
// This function is the UI, i.e. asking the user how many numbers to generate
int HowManyNumbers()
{
int input;
std::cout << "Enter the number of time to loop" << std::endl;
std::cin >> input;
return input;
}
// This function counts 1,2,3 for individual number
int Count123InNum(int num)
{
int count = 0;
while(num)
{
int lastDig = num % 10;
// count only if lastDigit in number is 1,2 or 3
switch(lastDig)
{
case 1:
case 2:
case 3:
++count;
break;
default:
break;
}
num /= 10;
}
return count;
}
// This function receives number of random numbers to generate,
// and its output is a print of the numbers and the joint occurences of 1,2 and 3
void Get123FromRandomNums(int nRandNumbers)
{
srand(time(NULL));
std::cout << "In the numbers: ";
int count = 0;
while(nRandNumbers--)
{
int num = rand() % 10000;
std::cout << num << " ";
count += Count123InNum(num);
}
std::cout << "There are " << count << " digits 1, digit 2, digit 3." << std::endl;
}
int main()
{
// Get number of random numbers (i.e. iterations)
int nRandNumbers = HowManyNumbers();
// check validity
if (nRandNumbers < 0 || nRandNumbers > 50)
{
std::cout << "Invalid entry" << std::endl;
}
else
{
//if valid, count and print 1,2,3 occurences
Get123FromRandomNums(nRandNumbers);
}
return 0;
}
I'm beginning with C++. The question is: to write a program to input 20 natural numbers and output the total number of odd numbers inputted using while loop.
Although the logic behind this is quite simple, i.e. to check whether the number is divisible by 2 or not. If no, then it is an odd number.
But, what bothers me is, do I have to specifically assign 20 variables for the user to input 20 numbers?
So, instead of writing cin>>a>>b>>c>>d>>.. 20 variables, can something be done to reduce all this calling of 20 variables, and in cases like accepting 50 numbers?
Q. Count total no of odd integer.
A.
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n,odd=0;
cout<<"Number of input's\n";
cin>>n;
while(n-->0)
{
int y;
cin>>y;
if(y &1)
{
odd+=1;
}
}
cout<<"Odd numbers are "<<odd;
return 0;
}
You can process the input number one by one.
int i = 0; // variable for loop control
int num_of_odds = 0; // variable for output
while (i < 20) {
int a;
cin >> a;
if (a % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
If you do really want to save all the input numbers, you can use an array.
int i = 0; // variable for loop control
int a[20]; // array to store all the numbers
int num_of_odds = 0; // variable for output
while (i < 20) {
cin >> a[i];
i++;
}
i = 0;
while (i < 20) {
if (a[i] % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
Actually, you can also combine the two while-loop just like the first example.
Take one input and then process it and then after take another intput and so on.
int n= 20; // number of input
int oddnum= 0; //number of odd number
int input;
for (int i = 0; i < n; i ++){
cin >> input;
if (input % 2 == 1) oddnum++;
}
cout << "Number of odd numbers :"<<oddnum << "\n";