I have to write a program that runs a loop for a coin toss. I am supported to enter a number into the console and have it run a loop of the coin toss for that many times. I need to use nested loops. I have been working on this for hours and cannot make it work.
The console i/o is supposed to look like below:
Enter the number of tosses to perform [0=exit]: 3
Heads
Tails
Heads
Enter the number of tosses to perform [0=exit]: 2
Tails
Tails
Enter the number of tosses to perform [0=exit]: 0
This is the code i have so far:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main ()
{
srand(time(0));rand();
int result = rand() % 2;
while (true)
{
int n; // this many tosses
cout << "How many tosses";
cin >> n;
cin.ignore (1000, 10);
if (n == 0)
break;
for (int i = 0; i < n; i++)
//random number generator
{
if (result == 0)
cout<< "Heads"<<endl;
else if (result == 1)
cout << "Tails"<<endl;
else if (result != 0 || result !=1)
return 0;
} //for
}//while
}//main
Your for loop doesn't have the part that you are actually trying to execute inside of {}. Try adding the braces around the part you want to loop and see if that fixes it for you.
I edited the indentation in your code to show you the only line that will actually be looping (the srand(time(0)))
You need brackets around the loop block, i.e.
for( int i = 0; i < n; i++ )
{
// Code goes here
}
As shown above, you need to initialize i.
Put the seeding of rand() before the while(...) loop.
You need to move int result = rand() % 2; inside your for loop! Otherwise you will get the same result every single time until you restart the application.
for (int i = 0; i < n; i++)
//random number generator
{
int result = rand() % 2;
if (result == 0)
cout<< "Heads"<<endl; /* to make your output look like your example you should removed the <<endl from here */
else if (result == 1)
cout << "Tails"<<endl; /* and here */
else if (result != 0 || result !=1)
return 0;
} //for
/* and put it here */
cout << endl;
Related
#include <iostream>
#include<ctime>
#include<cstdlib>
#include<string>
#include<cmath>
using namespace std;
int main()
{
bool cont = false;
string str;
int num, num2;
cin >> str >> num;
int arr[10];
int a = pow(10, num);
int b = pow(10, (num - 1));
srand(static_cast<int>(time(NULL)));
do {
num2 = rand() % (a - b) + b;
int r;
int i = 0;
int cpy = num2;
while (cpy != 0) {
r = cpy % 10;
arr[i] = r;
i++;
cpy = cpy / 10;
}
for (int m = 0; m < num; m++)
{
for (int j = 0; j < m; j++) {
if (m != j) {
if (arr[m] == arr[j]) {
break;
}
else {
cont = true;
}
}
}
}
cout << num2 << endl;
} while (!cont);
return 0;
}
I want to take a number from the user and produce such a random number.
For example, if the user entered 8, an 8-digit random number.This number must be unique, so each number must be different from each other,for example:
user enter 5
random number=11225(invalid so take new number)
random number =12345(valid so output)
To do this, I divided the number into its digits and threw it into the array and checked whether it was unique. The Program takes random numbers from the user and throws them into the array.It's all right until this part.But my function to check if this number is unique using the for loop does not work.
Because you need your digits to be unique, it's easier to guarantee the uniqueness up front and then mix it around. The problem-solving principle at play here is to start where you are the most constrained. For you, it's repeating digits, so we ensure that will never happen. It's a lot easier than verifying if we did or not.
This code example will print the unique number to the screen. If you need to actually store it in an int, then there's extra work to be done.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
#include <vector>
int main() {
std::vector<int> digits(10);
std::iota(digits.begin(), digits.end(), 0);
std::shuffle(digits.begin(), digits.end(), std::mt19937(std::random_device{}()));
int x;
std::cout << "Number: ";
std::cin >> x;
for (auto it = digits.begin(); it != digits.begin() + x; ++it) {
std::cout << *it;
}
std::cout << '\n';
}
A few sample runs:
Number: 7
6253079
Number: 3
893
Number: 6
170352
The vector digits holds the digits 0-9, each only appearing once. I then shuffle them around. And based on the number that's input by the user, I then print the first x single digits.
The one downside to this code is that it's possible for 0 to be the first digit, and that may or may not fit in with your rules. If it doesn't, you'd be restricted to a 9-digit number, and the starting value in std::iota would be 1.
First I'm going to recommend you make better choices in naming your variables. You do this:
bool cont = false;
string str;
int num, num2;
cin >> str >> num;
What are num and num2? Give them better names. Why are you cin >> str? I can't even see how you're using it later. But I presume that num is the number of digits you want.
It's also not at all clear what you're using a and b for. Now, I presume this next bit of code is an attempt to create a number. If you're going to blindly try and then when done, see if it's okay, why are you making this so complicated. Instead of this:
num2 = rand() % (a - b) + b;
int r;
int i = 0;
int cpy = num2;
while (cpy != 0) {
r = cpy % 10;
arr[i] = r;
i++;
cpy = cpy / 10;
}
You can do this:
for(int index = 0; index < numberOfDesiredDigits; ++index) {
arr[index] = rand() % 10;
}
I'm not sure why you went for so much more complicated.
I think this is your code where you validate:
// So you iterate the entire array
for (int m = 0; m < num; m++)
{
// And then you check all the values less than the current spot.
for (int j = 0; j < m; j++) {
// This if not needed as j is always less than m.
if (m != j) {
// This if-else is flawed
if (arr[m] == arr[j]) {
break;
}
else {
cont = true;
}
}
}
}
You're trying to make sure you have no duplicates. You're setting cont == true if the first and second digit are different, and you're breaking as soon as you find a dup. I think you need to rethink that.
bool areAllUnique = true;
for (int m = 1; allAreUnique && m < num; m++) {
for (int j = 0; allAreUnique && j < m; ++j) {
allAreUnique = arr[m] != arr[j];
}
}
As soon as we encounter a duplicate, allAreUnique becomes false and we break out of both for-loops.
Then you can check it.
Note that I also start the first loop at 1 instead of 0. There's no reason to start the outer loop at 0, because then the inner loop becomes a no-op.
A better way is to keep a set of valid digits -- initialized with 1 to 10. Then grab a random number within the size of the set and grabbing the n'th digit from the set and remove it from the set. You'll get a valid result the first time.
I think my code has an infinite loop. Can someone tell me where I went wrong?
The code is supposed to find the number of valid numbers, with a valid number being a number without a digit repeating. For example, 1212 would be a non-valid number because 1 and 2 repeated.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int a; int b; int count_validNums = 1; int digit; int last_digit; bool is_valid = true;
vector <int> num_list;
cout << "Enter numbers 0 < a <= b < = 10000: ";
cin >> a >> b;
// Checks for invalid input
if (a < 0 || b < 0 || a > 10000 || b > 10000) {
cout << "Invalid input";
return 1;
}
// Checks every number from the range [a,b]
for (int i = a; i <= b; i++){
last_digit = i % 10;
num_list.push_back(last_digit);
i = i / 10;
while (i != 0){
digit = i % 10;
if (find(num_list.begin(), num_list.end(), digit) != num_list.end()){
is_valid = false;
}
num_list.push_back(digit);
i = i / 10;
}
if (is_valid) count_validNums++;
}
cout << "They are " << count_validNums << " valid numbers between" << a << " and " << b << endl;
}
The inner while loop terminates when i == 0. Then the outer for loop increments it (so i == 1), then the inner loop reduces it to zero again. Then the other loop increments it, then ...
What is happening to cause the infinite loop is that you are constantly reducing the int i back down to 0. Consider these highlights:
`for(int i = a; i <= b; i++){
//stuff
while(i != 0){ //<--this forces i down to 0
//more stuff
i = i / 10;
}
//final stuff
}`
i here is all one variable, so any changes you make to it anywhere will affect it everywhere else it exists! Instead, you can try saying something like int temp = i; and then perform your operations on temp so that i remains independent, but because your for-loop terminates when i <= b and you are constantly resetting i to 0, it will never reach b.
Also, I noticed that in your check for valid numbers you verify that 0 < a,b < 10000, but later in your for-loop you seem to make the assumption that a <= b will be true. Unfortunately, your test does not ensure this, so the for-loop will immediately terminate for inputs where b < a is true (which your program currently allows) and your program will report answers that are likely incorrect. The same is true when I enter letters as input instead of numbers. You might want to revisit that portion of code.
I'm doing question 4.11 in Bjarne Stroustrup Programming-Principles and Practice Using C++.
Create a program to find all prime numbers in the range from 1 to max using a vector of primes in order(prime[2,3,5,...]). Here is my solution:
#include <iostream>
#include <string>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
bool check_prime(vector<int> &prime, int n) {
int count = 0;
for (int i = 0; prime[i] <= n || i <= prime.size() - 1; ++i) {
if (n % prime[i] == 0) {
count++;
break;
}
}
bool result = 0;
if (count == 0)
result = 1;
else
result = 0;
return result;
}
int main() {
vector<int> prime{2};
int max;
cout << "Please enter a max value:";
cin >> max;
for (int i = 2; i <= max; ++i) {
if (check_prime(prime, i))
prime.push_back(i);
}
for (int i = 0; i <= prime.size() - 1; ++i) {
cout << prime[i];
if (i <= prime.size() - 2)
cout << ',';
}
}
My code is working for numbers smaller than 23 but fail to work for anything bigger. If I open the program in Windows 10 the largest working number increase to 47, anything bigger than that fail to work.
This condition
prime[i]<=n||i<=prime.size()-1
makes the loop continue as long as at least one of them is true, and you're accessing prime[i] without checking the value of i.
This will cause undefined behaviour as soon as i == prime.size().
This means that anything can happen, and that you're experiencing that any specific values are working is just an unfortunate coincidence.
You need to check the boundary first, and you should only continue for as long as both conditions are true:
i <= prime.size() - 1 && prime[i] <= n
which is more idiomatically written
i < prime.size() && prime[i] <= n
(It's never too soon to get comfortable with the conventional half-open intervals.)
You check prime[i]<=n before i<=prime.size()-1. Then, if it's true (even if i>prime.size()-1, which is random behaviour), you work on it, generating wrong results.
I wrote a C++ program that prints all prime numbers lower than n, but the program keeps crashing while executing.
#include <iostream>
using namespace std;
bool premier(int x) {
int i = 2;
while (i < x) {
if (x % i == 0)
return false;
i++;
}
return true;
}
int main() {
int n;
int i = 0;
cout << "entrer un entier n : ";
cin >> n;
while (i < n) {
if (n % i == 0 && premier(i))
cout << i;
i++;
}
;
}
As Igor pointed out, i is zero the first time when n%i is done. Since you want only prime numbers and the smallest prime number is 2, I suggest you initialise i to 2 instead of 0.
You want to print all prime numbers less than n and has a function to check primality already.
Just
while (i < n){
if ( premier(i) == true )
cout<<i;
i++;
}
And while printing, add a some character to separate the numbers inorder to be able to distinguish them like
cout<<i<<endl;
P.S: I think you call this a C++ program. Not a script.
Edit: This might interest you.
I am not sure whether I should ask here or programmers but I have been trying to work out why this program wont work and although I have found some bugs, it still returns "x is not a prime number", even when it is.
#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i < b; i++) {
//If the user input has no remainder then it cannot be a prime and the loop can stop (break)
if (a % i == 0) {
return(0);
break;
}
//Other wise if the user input does have a remainder and is the last of the loop, return true (it is a prime)
else if ((a % i != 0) && (i == a -1)) {
return (1);
break;
}
}
}
int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
cout << user << " is a prime number.";
}
else {
cout << user<< " is not a prime number.";
}
cout << "\n\nPress enter to exit...";
getchar();
getchar();
return 0;
}
Sorry if this is too localised (in which case could you suggest where I should ask such specific questions?)
I should add that I am VERY new to C++ (and programming in general)
This was simply intended to be a test of functions and controls.
i can never be equal to a - 1 - you're only going up to b - 1. b being a/2, that's never going to cause a match.
That means your loop ending condition that would return 1 is never true.
In the case of a prime number, you run off the end of the loop. That causes undefined behaviour, since you don't have a return statement there. Clang gave a warning, without any special flags:
example.cpp:22:1: warning: control may reach end of non-void function
[-Wreturn-type]
}
^
1 warning generated.
If your compiler didn't warn you, you need to turn on some more warning flags. For example, adding -Wall gives a warning when using GCC:
example.cpp: In function ‘bool primetest(int)’:
example.cpp:22: warning: control reaches end of non-void function
Overall, your prime-checking loop is much more complicated than it needs to be. Assuming you only care about values of a greater than or equal to 2:
bool primetest(int a)
{
int b = sqrt(a); // only need to test up to the square root of the input
for (int i = 2; i <= b; i++)
{
if (a % i == 0)
return false;
}
// if the loop completed, a is prime
return true;
}
If you want to handle all int values, you can just add an if (a < 2) return false; at the beginning.
Your logic is incorrect. You are using this expression (i == a -1)) which can never be true as Carl said.
For example:-
If a = 11
b = a/2 = 5 (Fractional part truncated)
So you are running loop till i<5. So i can never be equal to a-1 as max value of i in this case will be 4 and value of a-1 will be 10
You can do this by just checking till square root. But below is some modification to your code to make it work.
#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i <= b; i++) {
//If the user input has no remainder then it cannot be a prime and the loop can stop (break)
if (a % i == 0) {
return(0);
}
}
//this return invokes only when it doesn't has factor
return 1;
}
int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
cout << user << " is a prime number.";
}
else {
cout << user<< " is not a prime number.";
}
return 0;
}
check this out:
//Prime Numbers generation in C++
//Using for loops and conditional structures
#include <iostream>
using namespace std;
int main()
{
int a = 2; //start from 2
long long int b = 1000; //ends at 1000
for (int i = a; i <= b; i++)
{
for (int j = 2; j <= i; j++)
{
if (!(i%j)&&(i!=j)) //Condition for not prime
{
break;
}
if (j==i) //condition for Prime Numbers
{
cout << i << endl;
}
}
}
}
main()
{
int i,j,x,box;
for (i=10;i<=99;i++)
{
box=0;
x=i/2;
for (j=2;j<=x;j++)
if (i%j==0) box++;
if (box==0) cout<<i<<" is a prime number";
else cout<<i<<" is a composite number";
cout<<"\n";
getch();
}
}
Here is the complete solution for the Finding Prime numbers till any user entered number.
#include <iostream.h>
#include <conio.h>
using namespace std;
main()
{
int num, i, countFactors;
int a;
cout << "Enter number " << endl;
cin >> a;
for (num = 1; num <= a; num++)
{
countFactors = 0;
for (i = 2; i <= num; i++)
{
//if a factor exists from 2 up to the number, count Factors
if (num % i == 0)
{
countFactors++;
}
}
//a prime number has only itself as a factor
if (countFactors == 1)
{
cout << num << ", ";
}
}
getch();
}
One way is to use a Sieving algorithm, such as the sieve of Eratosthenes. This is a very fast method that works exceptionally well.
bool isPrime(int number){
if(number == 2 || number == 3 | number == 5 || number == 7) return true;
return ((number % 2) && (number % 3) && (number % 5) && (number % 7));
}