I am trying to make when user types number, program should repeat that many times chosing random if
Here is my code
cin >> d;
c = 0;
while (c < d) {
c = c++;
num = (rand() % 3) + 1;
if (num == 1) {
system("start C:\\viewver\\vw");
Sleep(2000);
}
else if (num == 2) {
system("start C:\\viewver\\vw2");
Sleep(2300);
}
else if (num == 3) {
system("start C:\\viewver\\vw3");
Sleep(1800);
}
It always chooses to open first one and then stops.
Use == not =
if (num == 1) {
system("start C:\\test\\vw");
Sleep(2000);
}
else if (num == 2) {
system("start C:\\test\\vw2");
Sleep(2300);
}
else if (num == 3) {
system("start C:\\test\\vw3");
Sleep(1800);
}
== is for comparison, = is for assignment
The reason why it always chooses the first option is because C++ (and C) has the notion of truthy values. So any value that is not 0 is considered truthy, whereas values that evaluate to 0 are considered falsy.
In your original code, when you assign num to 1, the value of num is truthy, therefore that branch is always taken
Related
I have this homework to do and I dont really understand why my program doesnt really work(prints 1 constantly).
I am supposed create a program that receives a number and a digit from the user(we can assume that the input is ok)
and it prints 1 in case the digit appears inside the number even times. In case it appears odd amount of times it will print 0.
I have to use a boolean recursion function.
can someone please tell me whats wrong with it?
#include <iostream>
using namespace std;
bool isEven(int num, int dig);
void main()
{
bool res;
int num, dig;
cout << "Please enter a number and a digit" << endl;
cin >> num >> dig;
cout << isEven(num, dig);
}
bool isEven(int num, int dig)
{
bool res;
int counter = 0;
if (num < 10)
{
if (counter % 2 != 0)
res=false;
else
res=true;
return res;
}
else
{
res=isEven(num / 10, dig);
if (num % 10 == dig)
counter++;
return res;
}
}
You're not passing the value of your counter down through your recursive calls - it's effectively unused in your current implementation.
You're also missing one check if dig % 10 == num - in your code, you never check the last digit of the number.
bool isEven(int num, int dig, int counter)
{
bool res;
if (num % 10 == dig)
counter++;
if (num < 10)
{
if (counter % 2 != 0)
res=false;
else
res=true;
return res;
}
else
{
res=isEven(num / 10, dig, counter);
return res;
}
}
And you can just call it with isEven(num, dig, 0) or create a wrapper function that takes just num and dig and calls this version with 0.
Note that there's a (imo) more elegant recursive expression of this function without using counters, although it's got some slightly unintuitive bits to it:
bool isEven(int num, int dig)
{
// Base case, single digit
// If num % 10 == dig on this last digit, we've got 1 match (odd, so return false)
if (num < 10)
return num % 10 != dig;
bool result = isEven(num / 10, dig);
if (num % 10 == dig) // This digit matches, count one more/flip the result
result = !result;
return result;
}
How can I check recursively if all the digits of an integer are different numbers in C++
void Check(int n)
{
if (n < 10)
return;
else
{
bool eq = !(n % 10 == ((n / 10) % 10));
if (eq == true)
{
Check(n / 10);
}
}
}
You can remember, which digits you have already seen. For instance by using a bool-array of length 10. At the first call of your function all entries are false. In each recursive call you set array[n%10] to true. If it was already true, then you have found a duplicate digit, otherwise not.
If you want to only use recursion, you can define a second recursive function:
bool checkIfDigitApearsInNumber(int n, int digit) {
if (n == 0) {
return false;
} else {
if (n % 10 == digit) {
return true;
} else {
return checkIfDigitApearsInNumber(n/10, digit);
}
}
}
In you function Check, you have to call this function in each step with n/10, n%10.
When I Build and run my code it instantly returns 0 saying programing was successful, however i want it to display all the numbers from 100 to 200 that are divisible by 4.
Here's my code...
#include <iostream>
using namespace std;
int main()
{
int num = 200;
int snum;
cout<<"The following numbers are all divisble by 4 and are inbetween 100 and 200\n";
while(num<99)
{
snum = (num % 4) ;
cout<<snum<<endl;
cout<<num<<endl;
if(snum = 0)
{
cout<< num << endl;
}
else
{
}
num--;
}
return 0;
}
The while condition should be while (num > 99) instead of while(num<99)(false at the beginning)
The if condition should be if (snum == 0) instead of if(snum = 0)(= is assignment, not equal operator)
The else part has nothing, you may delete it. I added some other notes in the comments below.
while (num > 99)
{
snum = num % 4 ; // no need for the parenthesizes
if (snum == 0)
{
std::cout<< num << std::endl;
}
--num; //pre-increment is preferred, although doesn't matter in this case
}
Your loop never executes because the condition
(num<99)
is already false from the start. You probably meant
(num>99)
Also, the if statement condition
(snum = 0)
sets snum to zero, always returning zero, so you probably meant
(snum == 0)
You set num to be 200:
int num = 200;
Then you only run the loop if and when the number is less than 99:
while(num<99)
What do you expect will happen?
This is not how you do an equals-test in C:
if(snum = 0)
In C, equality is checked with ==:
if(snum == 0)
In fact, what you have (if (snum = 0)) will NEVER be true, so your if-statement will NEVER be executed.
I'm having trouble with this C++ code. The integer num is a number that I want to check if it is prime. However this program is always returning false. It's probably something simple but I can't find anything.
for(int i=2;i<num;i++){ //primes are allowed to be divided by 1 so we start at 2
if(num % i == 0){ //can be divided by a number other than itself or 1 so we trip out
return false;
} else if(i == num){ //if we've already done checks as high as possible and not tripped out yet then report success
return true;
}
}
i == num will never occur, since your loop condition is i<num. Try:
for(int i=2;i<num;i++){ //primes are allowed to be divided by 1 so we start at 2
if(num % i == 0){ //can be divided by a number other than itself or 1 so we trip out
return false;
} else if(i == num-1){ //if we've already done checks as high as possible and not tripped out yet then report success
return true;
}
}
As pointed out below, the else condition here is redundant, and you only need to check from 2 to sqrt(num) - since the remaining factors have already been checked.
There are more improvements that can be made depending on how complex you want to make the problem. Most methods in reality use probabilistic algorithms.
You don't have to check every number, as a lot of them can easily be ruled out. For example, after checking that num is not divisible by 2, you can skip all other even numbers. That saves you half the tests.
We also definitely know that any other factor must be less than num/2 (or really sqrt(num), but that is harder to compute). That knowledge can save us another half of the tests.
So now we have:
if (num % 2 == 0)
return false;
for(int i = 3; i < num / 2; i += 2){
if(num % i == 0){ //can be divided by a number other than itself or 1 so we trip out
return false;
}
}
// arriving here we have found no factors, so it must be a prime
return true;
A small optimization for Will Ness's code, just calculate the sqrt of the number outside the for. The condition check executes many times and has no sense to calculate sqrt each time.
if( num == 2 ) return true;
if( num < 2 || num % 2 == 0 ) return false;
int sqrt = sqrt(num);
for( int i=3; i<=sqrt; i+=2 ){
if(num % i == 0){
return false;
}
}
return true;
So far I think that this is the most efficient way!
bool CheckPrime(int num) {
bool yayornay = true;
for(int i = 2; i < num; i++) {
if(num % i == 0) {
yayornay = false;
break;
}
}
return yayornay;
}
bool isprime(int n)
{
if(n<2) return false;
if(n==2)return true;
for(int i=2;i<=sqrt(n);i++)
if(n%i==0) return false;
return true;
}
Here's the proper way to write what you meant:
int i=2; // move declaration out
for(/*int i=2*/;i<num;i++){
if(num % i == 0){
return false;
} // else // and the final test too
}
if(i == num){
return true;
}
But that's not efficient. You only have to check for i's not exceeding of sqrt(num). Plus, if you check num%2, there's no more need to check any other even numbers, so you can use an increment of 2. Or you can even count by 6:
if( num == 2 || num == 3 ) return true;
if( num < 2 || num % 2 == 0 || num % 3 == 0 ) return false;
for( int i=5, j=7, lim=sqrt(num); i<=lim; i+=6, j+=6 ){
if( num % i == 0 || num % j == 0 ){
return false;
}
}
return true;
(notice: this is more efficient than another answer here, which says it's an "optimization" of an initial version of this answer).
I have a for loop in which I placed several if statements. The objective of these conditionals is to check divisibility of a number and then output a string if the number is divisible by 3. If the number is divisible by 5, another string will be outputted. However, if the number is divisible by both 3 and 5, an entirely different string will be outputted in its place instead of the other strings.
Here is my code:
for (i = 1; i <= file_int; i++){
if (i % 3 == 0) {
printf("Hoppity \n");
}
if (i % 5 == 0) {
printf("Hophop \n");
}
if (i % 5 == 0 && i % 3 == 0) {
printf("Hop \n");
}
}
As you can see, the last conditional doesn't quite work. What type of control construct should I use? else?
Thanks alot.
for (i = 1; i <= file_int; i++){
if (i % 5 == 0 && i % 3 == 0) {
printf("Five and three\n");
} else if (i % 3 == 0) {
printf("Three\n");
} else if (i % 5 == 0) {
printf("Five\n");
} else {
printf("None of the conditions passed\n");
}
}
I would use else-ifs and make us of the fact that
(i % 5 == 0 && i % 3 == 0) <=> (i % 15 == 0):
for (i = 1; i <= file_int; i++){
if (i % 15 == 0)
printf("Hop \n");
else if (i % 3 == 0)
printf("Hoppity \n");
else if (i % 5 == 0)
printf("Hophop \n");
}
Of course you can also get away without using any control structures except the for-loop at all:
const char* values[15] = {"Hop \n", "", "", "Hoppity \n", "",
"Hophop \n", "Hoppity \n", "", "", "Hoppity \n",
"Hophop \n", "", "Hoppity \n", "", ""};
for (int i = 1; i <= 100; i++)
printf(values[i % 15]);
That solution is slightly insane for this example, but it shows how you can do things differently (and it's not so farfetched when writing code where you shall never ever have more then a certain number of branch paths in one function (overzealous coding conventions...)).
Just for the sake of it, and not recommending it, as it can be harder to read as it abuses conversions from bool to int:
int msg = (i % 3 == 0) + 2*(i % 5 == 0);
switch ( msg ) {
case 3:
cout << "Multiple of 3 and 5";
case 2:
cout << "Multiple of 5";
case 1:
cout << "Multiple of 3";
}
which can be further condensed into:
const char* msgs[] = { "", "Multiple 3", "Multiple 5", "Multiple 3 and 5" };
cout << msgs[ (i%3==0) + 2*(i%5==0) ];
Of course, both solutions are against the question itself, as they are not if constructs, but rather avoid the use of if in the first case, and branches in general in the second case.
An alternative solution, keeping closer to your original code. Although the else solution is indeed more efficient (and elegant).
for (i = 1; i <= file_int; i++){
if (i % 3 == 0 && i % 5 != 0) {
printf("Hoppity \n");
}
if (i % 5 == 0 && i % 3 != 0) {
printf("Hophop \n");
}
if (i % 5 == 0 && i % 3 == 0) {
printf("Hop \n");
}
}