#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <stdlib.h>
using namespace std;
int main()
{
int x,y,z;
cout<<"welcome to guessing game\nplayer one pick your number: ";
cin>>x;
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
Sleep(2000);
system("cls");
cout<<"ok player 2 pick the guess";
cin>>y;
if (x == y){
cout<<"congrats you got it right";
}
else{
if (x < y){
cout<<"Go lower";}
else {
if (x > y){
cout<<"higher";}}
}
system("pause>nul");
return 0;
}
i cant see the get the initial if statement to work no matter what number i type in it would auto display the out of number range. also am i allowed to place the conditions like that soo close like if (x < 0)(x > 100);. also how do i make it soo it returns to the start of the program?
There is an error:
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
Should be:
if (x < 0 || x > 100)
{
cout<<"out of number range";
}
You also need to work on your indentation; those if/else statements towards the bottom look dodgy (I cannot really tell due to the indentation).
Aside from writing if (x < 0 || x > 100) (and dropping the semicolon), you should be wary of comparing equality on floating point. I would red flag your line if (x == y){ if reviewing your code.
See Floating point comparison
nobody else is actually answering your second question: how to loop it, here you go:
int x;
cout << "Welcome to the guessing game\n";
do {
cout << "Please enter a number from 0 to 100: ";
cin >> x;
} while (x < 0 || x > 100);
You have written
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
First remove the semi colon.
Second did you mean
if ((x < 0) || (x > 100))
{
cout<<"out of number range";
}
try this:
/*
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
*/
if (x < 0 || x > 100)
{
cout<<"out of number range";
}
There are a few notable syntax errors:
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
First of all, you can't just put two conditions side by side like that in C++ that I know of. You'd have to separate them with || for OR, or && for AND (in most cases - there are some others).
Also, you had a ; at the end of your if statement. I believe that doing this in C++ will result in some problems too.
Your final code should look like:
if ((x < 0) || (x > 100))
{
cout << "out of number range" << endl;
}
The << endl; part is optional. This adds a new line to your output, for more readability next time you write something.
Also, to loop your entire game repeatedly, I would use a do-while loop. You can learn about them here.
Related
I am making a C++ code where you will create an array using a do while loop.
Here is the full code:
const int size = 10;
double *pt1;
//executable
pt1=new double[size];
int i = 0;
do{
cout <<"mile" << "[" << i << "]" << setw(3);
if(*(pt1+i) >= 100 && *(pt1+i) <= 250)
{
cin >> *(pt1+i);
i++;
}
else if( *(pt1+i) > 100 && *(pt1+i) < 250)
{
cout << "100-250 only";
continue;
}
}while(i < 10);
There is an input validation where the numbers that will be accepted are only numbers from 100 to 250 but it keeps on looping. I can't find where the problem is. Any help would be greatly appreciated!
The first error is that you are testing the value of the input before you actually get the input. That makes no sense, you need to switch the order around. So this
if(*(pt1+i) >= 100 && *(pt1+i) <= 250)
{
cin >> *(pt1+i);
...
}
else if( *(pt1+i) > 100 && *(pt1+i) < 250)
{
...
}
should be this
cin >> *(pt1+i);
if(*(pt1+i) >= 100 && *(pt1+i) <= 250)
{
...
}
else if( *(pt1+i) > 100 && *(pt1+i) < 250)
{
...
}
Secondly I think you meant
else if( *(pt1+i) < 100 || *(pt1+i) > 250)
Or better you could have just said
else
Then there is no chance of getting the logic wrong. When you have only two choices, you just need to test for the first choice and use else for the second choice. There's no need to test for the opposite of the first choice, using a plain else will do that automatically.
Also continue at the end of a loop is not necessary, loops continue automatically.
Finally pt1[i] is much easier to read than *(pt1+i).
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 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));
}
I'm trying to print all the prime numbers in series, the code I ended up with is below, instead of printing all primes it prints random numbers, Some are prime and some are not :/
Why is that so?
#include <iostream>
using namespace std;
long int x,y=3;
int a=3;
bool isprime;
int main()
{
while(a<=100)
{
for(x=2;x<=y;x++)
{
if(y%x==0 && x!=y)
{
isprime=false;
break;
}
else if(y%x!=0 && x!=y)
{
isprime = true;
}
}
if(isprime==true && y%x!=0 && x!=y)
{
cout<<a<<" is a prime number."<<"\n";
isprime=false;
}
a++;
y++;
}
}
This
if(isprime=true && a%x!=0 && a!=y)
should be this
if(isprime==true && a%x!=0 && a!=y)
That's a common mistake. But even better is to realise that you don't need to compare bools against true of false, because they are true or false. So just
if (isprime && a%x!=0 && a!=y)
The logic just looks all wrong (and way too complicated), try this
isprime = true;
for(x=2;x<a;x++)
{
if(a%x==0)
{
isprime = false;
break;
}
}
if (isprime)
{
cout<<a<<"\n";
}
No need for y.
Well what jumps into my eyes is that you never increment y.
y is 3 in the beginning, so you only try if 2 is a possible divisor of a and then go to the next a.
Anyway, I am not sure what you wanted to achieve with y.
Let x run from 2 to a/2, as there is no need to try numbers bigger than a/2.
This is simply because there never will be a divisor bigger than a/2.
Example: a = 30. It would not make sense to try to divide by 16 or bigger, as the result can never be a integer (besides a itself of course)
However, this should do what you want:
int x = 0;
int a = 0;
bool isPrime = false;
for(a=3; a < 100; a+=2)
{
isPrime = true;
for(x = 2; x <= a/2; x++) {
if(a%x == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
cout << a << "\n";
}
}
there are of course other algorithms that can find primes, but I wanted to use your approach basically.
Cheers
Chris
EDIT:
Someone was faster :)
anyway: there is no need to run higher than a/2, this is a important optimization...!
EDIT2:
another optimization is of course skipping all even numbers, so start with a = 3 and increment by 2 for each loop iteration...
I see your code is ok now.
Nevertheless I made small changes, cleaning the code and making it a little bit faster.
#include <iostream>
using namespace std;
long int x, y = 2;
int a = 3;
bool isprime;
int main() {
while (a <= 100) {
while ((y + 1) * (y + 1) <= a) {
y++;
}
isprime = true;
for (x = 3; x <= y; x += 2) {
if (a % x == 0) {
isprime = false;
break;
}
}
if (isprime) {
cout << a << " is a prime number." << "\n";
}
a+=2;
}
}
Heres my code im trying to get tidied up for school, in the embedded if and else if statements it show errors when I try to compile.
errors : expect primary-expression before "else"
expected ';' before else
both of these come up for each line.
// This is a program to Calculate the volume of the sphere using the radius (a03.cpp)
// Written by: Jimmy Scott
// Date: 2/1/12
// Sources: Stackoverflow.com (else and if statements)
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char vehicle;
float total;
char over20;
char old;
int adults;
int oldpass;
char height;
int youngpass;
int bicycles;
float length;
cout<<"Fare Calculator by Jimmy Scott";
cout<<"\n\n\n Are You Bringing a vehicle on The Ferry ?";
cin>>vehicle;
if (vehicle == 'y')
{
cout<<"\n\n"<<"Is the Driver over 65 Years of age or disabled?";
cin>>old;
cout<<"\n\n"<<"Passengers going along with the driver"<<"\n\n";
cout<<"Adults (19-64 Years old):";
cin>>adults;
cout<<"\n\n"<<"Senior Citizens or disabled:";
cin>>oldpass;
cout<<"\n\n"<<"Young passengers 5-18 years old: ";
cin>>youngpass;
cout<<"\n\n"<<"Is your Vehicle over 7ft, 6in in height? ";
cin>>height;
cout<<"Vehicle length in feet: ";
cin>>length;
if (old == 'y')
{
total= 44.60;
}
else if (old == 'n');
{
total= 51.20;
}
else if (length < 20) and (height == 'y');
{
total= 102.4;
}
else if (length > 20) and (length < 30);
{
total= 76.80;
}
else if (length > 20) and (length < 30) and (height = 'y');
{
total= 153.60;
}
else if (length > 30) and (length < 40);
{
total= 204.80;
}
}
else
{
cout<<"\n\n"<<"How many Senior Citizens or disabled are in your group?";
cin>>oldpass;
cout<<"\n\n"<<"How many adults are in your group?:";
cin>>adults;
cout<<"\n\n"<<"How many in your group are youths (5-18):";
cin>>youngpass;
cout<<"\n\n"<<"How many in your group have Bicycles:";
cin>>bicycles;
total=oldpass * 6.55;
total= total + (adults * 13.15);
total= total + (youngpass * 10.55);
total= total + (bicycles * 4.00);
}
cout<<"\n\n"<<"your total fare cost is : $"<<total;
cout<<"\n\n\n"<<"Press <Enter> to Exit";
cin.ignore();
cin.get();
return 0;
}
Several things:
When you do a conditional, don't follow the test directly with a semicolon, as this stops the conditional statement and will do something different from what you want. Furthermore, since it terminates the if-else group, you will generate an error on the next 'else' statement.
You also need to enclose your conditional tests with parenthesis.
Here is an example of a correct else if statement:
else if ((length > 30) and (length < 40))
{
total= 204.80;
}
Update: I initially said to use && instead of 'and'. As honk says 'and' is a valid operator in c++ that does the same thing as &&. I prefer to use && for portability with c though.
eliminate all the ';' after the if else() statements. Also add '( )' if you make many conditions.