/*
david ballantyne
10/10/13
assesment lab 2
*/
//Libraries
#include <iostream>
//Global Constants
//Functioning Prototypes
using namespace std;
int main() {
int n, num, digit, rev = 0;
cout << "Enter a positive number"<<endl;
cin >> num;
num=n;
do{
digit = num%10;
rev = (rev*10) + digit;
num = num/10;
}
while (num!=0);
if (n == rev)
cout << " The number is a palindrome"<<endl;
else
cout << " The number is not a palindrome"<<endl;
return 0;
}
I enter a palindrome and it keeps telling me it's not a palindrome, also if you could help me understand what kind of loop I would use to ask a "would you like to try again y/n" I'd be grateful.
probably be easier to convert the number to a string. create a new string that is reverse order of the first string. And then compare to see if they are the same. Really no reason to do any real math, Palindromes are lexical, not mathematical.
cin >> num;
num=n;
assigns a user-specified integer to num then replaces it with the value of the uninitialised variable n
Did you mean to reverse the assignment
n=num;
instead?
also if you could help me understand what kind of loop I would use to
ask a "would you like to try again y/n"
You could use a do...while loop with the condition for the while being calculated after you report whether the number was a palindrome.
#include <iostream>
using namespace std;
int main()
{
int userNum, palindrome[100], rem, rem2, count=0, count2=0, compare,
compare2;
bool flag;
cout << "Enter number to test for Palindrome: ";
cin >> userNum;
compare = userNum;
compare2 = userNum;
// counting the digits in the number.
do {
rem = compare % 10;
count += 1;
compare /= 10;
} while (compare >= 1);
// inputing in an array.
for (int i=0; i<count; i++)
{
rem2 = compare2 % 10;
palindrome[i] = rem2;
compare2 /=10;
}
// Comparing array with palindrome.
for (int i=0; i < count; i++)
{
if (palindrome[i] != palindrome[count-i-1])
count2 = 1;
}
if (count2 == 1)
cout << "Not a palindrome.";
else
cout << "Palindrome\n";
return 0;
}
Related
#include<iostream>
using namespace std;
int main(){
int num,i,n,count=0;
cout<<"Enter the range";
cin>>num;
for(n=2;n<=num;n++){
for(i=1;i<=n;i++){
if(n%i==0)
count++;
}
if(count==2){
cout<<"The prime numbers are as follows "<<n;
}
}
return 0;
}
I am using this logic right now. Why doesn't it work?
Here is the fixed code. You were not resetting count to 0 as you are checking if number is arriving in its own and in and table of 1.
#include<iostream>
using namespace std;
int main(){
int num,i,n,count=0;
cout<<"Enter the range";
cin>>num;
for(n=2; n<= num;n++){
count = 0;
for(i=1; i <= n; i++){
if(n % i == 0)
count++;
}
if(count==2){
cout<<"The prime numbers are as follows "<< n << endl;
}
}
return 0;
}
You are not resetting count to 0. That is why, the below if block executes once.
if(count==2){
cout<<"The prime numbers are as follows "<<n;
}
Okay, so let us start with finding if a single given number is prime.
The number n is prime only if 2,3,4,...,n-1 do not divide n.
For example, 13 is prime because 2,3,4,...,11 do not divide 13.
So the snippet might look like this:
#include<iostream>
using namespace std;
int main() {
int num;
cout << "Enter the number: ";
cin >> num;
bool isPrime = true;
for(int i = 2; i < num; i++) {
if(num%i == 0){
// Not a prime number
isPrime = false;
}
}
if(isPrime) {
cout << num << " is a prime number\n";
}
return 0;
}
I looped through all the numbers from 2 to n-1, then I checked if they divide num.
I created a boolean called isPrime(which stores if the number is prime). The value of isPrime is initialized with true.
If at any point a number divides n, we change isPrime to false. This means if no number divides, the isPrime remains unchanged (i.e. true)
And then finally, we check if the number is prime, and cout accordingly.
Now let us gear up our code. What we just implemented is just going to go inside a loop, since we now do this to the given range. And at this point, you should be able to understand it yourself.
#include<iostream>
using namespace std;
int main(){
int range, count=0;
cout << "Enter the number: ";
cin >> range;
for(int num = 2; num < range; num++) {
bool isPrime = true;
for(int i = 2; i < num; i++) {
if(num%i == 0){
// Not a prime number
isPrime = false;
}
}
if(isPrime) {
cout << num << " is a prime number\n";
count++;
}
}
cout << "There were total " << count << " prime numbers";
return 0;
}
}
Note how I created the variable in the for loop itself, this is not just good practice because it reduces lines of code, but when you create the variable outside, it is accessible everywhere in that scope(everywhere in main() function here). But variables created in the above manner are only accessible inside the for loop.
Also, I saw you created way too many variables like count, I don't know what you used it for, I'm assuming you needed to count how many numbers are prime, so I implemented that as well.
I'm trying to build the Bulls & Cows game in C++. I've implemented most of the logic. The game runs continuously with the use of an infinite loop and generates a random value at each run.
What I'm trying to do now is to now is to take the user input and run the code if the input is valid (can ONLY be a 4 digit integer). This is my implementation:
#include ...
using namespace std;
vector<int> getDigits(int modelValue) {
vector<int> vectorValue;
int extractedDigit = 0;
int modulant = 10000;
int divisor = 1000;
for (int i = 0; i < 4; i++) {
extractedDigit = (modelValue % modulant) / divisor;
vectorValue.push_back(extractedDigit);
modulant /= 10;
divisor /= 10;
}return vectorValue;
}
int main() {
for (;;) {
int model = rand() % 9000 + 1000;
int guess = 0000;
int bulls = 0;
int cows = 0;
int counter = 1;
cout << "This is the random 4-digit integer: " << model << endl;
cout << "Enter a value to guess: ";
cin >> guess;
if ((guess >= 1000) && (guess <= 9999) && (cin)) {
vector<int> modelVector = getDigits(model);
vector<int> guessVector = getDigits(guess);
for (int i = 0; i < 4; i++) {
if (find(modelVector.begin(), modelVector.end(), guessVector[i]) != modelVector.end()) {
if (modelVector[i] == guessVector[i]) { bulls += 1; }
else { cows += 1; }
}
}cout << "There are " << bulls << " bulls and " << cows << " cows" << endl;
}
else {
cout << "Please enter a valid 4-digit integer between 0000 and 9999" << endl;
cin.clear();
}
}return 0;
}
But when I run and input something invalid, what I get is a continuously running .
There's nothing wrong with the way you read the user input, it just doesn't check for the input type before assigning the value into your 'guess' variable.
So, if an user put any value that isn't accepted by the integer type it would crash your application generating this infinite loop.
To protect your integer variable from wrong user inputs you must replace your direct input assignment:
cin >> guess;
By a protected one:
while(!(cin >> guess) || (guess < 1000)){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please, try again: ";
}
Into the while above you can see the "numeric_limits::max()" which is explained here:
Returns the maximum finite value representable by the numeric type T. Meaningful for all bounded types.
At the end you have a while holding the user into this reading loop while its input is under 1000 (as requested) or isn't a valid integer.
Try out cin.ignore(). It'll help you flush the cin buffer.
I'm trying to build the Bulls & Cows game in C++. I've implemented most of the logic. The game runs continuously with the use of an infinite loop and generates a random value at each run.
What I'm trying to do now is to now is to take the user input and run the code if the input is valid (can ONLY be a 4 digit integer). This is my implementation:
#include ...
using namespace std;
vector<int> getDigits(int modelValue) {
vector<int> vectorValue;
int extractedDigit = 0;
int modulant = 10000;
int divisor = 1000;
for (int i = 0; i < 4; i++) {
extractedDigit = (modelValue % modulant) / divisor;
vectorValue.push_back(extractedDigit);
modulant /= 10;
divisor /= 10;
}return vectorValue;
}
int main() {
for (;;) {
int model = rand() % 9000 + 1000;
int guess = 0000;
int bulls = 0;
int cows = 0;
int counter = 1;
cout << "This is the random 4-digit integer: " << model << endl;
cout << "Enter a value to guess: ";
cin >> guess;
if ((guess >= 1000) && (guess <= 9999) && (cin)) {
vector<int> modelVector = getDigits(model);
vector<int> guessVector = getDigits(guess);
for (int i = 0; i < 4; i++) {
if (find(modelVector.begin(), modelVector.end(), guessVector[i]) != modelVector.end()) {
if (modelVector[i] == guessVector[i]) { bulls += 1; }
else { cows += 1; }
}
}cout << "There are " << bulls << " bulls and " << cows << " cows" << endl;
}
else {
cout << "Please enter a valid 4-digit integer between 0000 and 9999" << endl;
cin.clear();
}
}return 0;
}
But when I run and input something invalid, what I get is a continuously running .
There's nothing wrong with the way you read the user input, it just doesn't check for the input type before assigning the value into your 'guess' variable.
So, if an user put any value that isn't accepted by the integer type it would crash your application generating this infinite loop.
To protect your integer variable from wrong user inputs you must replace your direct input assignment:
cin >> guess;
By a protected one:
while(!(cin >> guess) || (guess < 1000)){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please, try again: ";
}
Into the while above you can see the "numeric_limits::max()" which is explained here:
Returns the maximum finite value representable by the numeric type T. Meaningful for all bounded types.
At the end you have a while holding the user into this reading loop while its input is under 1000 (as requested) or isn't a valid integer.
Try out cin.ignore(). It'll help you flush the cin buffer.
I can get the sum every time the user inputs an integer until either a negative number or non-integer is inputted. Problem is my sum calculations are off. I.E user putting 1000; sum outputs 1111, then user inputs 2000, it adds up to 3333. Just any advice is appreciated. I'll still experiment around with my coding.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int j , i = 0, k = 0,number;
double sum = 0;
cout << "Enter Positive integer number: ";
while(cin >> number)
{
cout << endl;
if( number < 0)//test if the number is negative
{
cout << "Ending program since user has input a negative number" <<endl;
break;
}
int temp = number;
int p = 1;
while( temp > 0) //counting number of digits
{
sum = sum+temp; //Sum attempt.
temp /= 10;
p *= 10;
i++;
}
cout << sum << endl;
j = i % 3;
p /= 10;
while( i > 0 )//display integer number with 1000 seperator
{
//this is giving me error
cout << char ((number/p) +'0');
number %= p;
p /= 10;
i--;
k++;
j--;
if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2) )
{
cout <<",";
k = 0;
}
}
cout << endl << endl;
cout << "This program will exit if you input any non-integer characters\n";
cout << "Enter another integer number: ";
}
return 0;
}
It looks like you're trying to output an integer number with commas inserted at 1000 boundaries. ie: 1000000 would be displayed as 1,000,000.
This being the case, the easiest way to approach it might not be involving maths but simply to get a string representation of the int (atoi() for example) and count through that. From the back, count forward three chars, insert a comma, repeat until you run out of string.
The specifics of string handling are left as an exercise for the reader - looks like it's his homework after all. ;-)
My program is supposed to calculate the sum of all the squares of numbers up until the users input. For example if the user inputs 2, the function will perform : (1^2 + 2^2) However my program refuses to do anything when run. (Not sure if this is a function problem, or with the main body.)
#include <iostream>
#include <cmath>
using namespace std;
int sumofsquares (int num)
{
int i;
int answer;
for(int i=0; i <= num; i++){
answer = (num * num)+ num;
}
return (answer);
}
int main(){
int num;
cout<< "Enter a number" <<endl;
cin >> num;
while( num != -1){
sumofsquares(num);
}
cout<< "The sum of squares is "<< num <<endl;
return 0;
}
You have to assign the return value of the function to something - in your case, since you're printing num, to num itself:
num = sumofsquares(num);
After you do this, your function will enter an infinite loop if num isn't -1 because you never modify it. You probably meant:
while( num != -1){
cin << num;
}
sumofsquares(num);
After this, you're left with the bugs in the function:
int answer;
for(int i=0; i <= num; i++){
answer = (num * num)+ num;
}
should be
int answer = 0;
for(int i=0; i <= num; i++){
answer += i*i;
}
The real problem however is that you're missing basic C++/logic knowledge, to which the only solution is to learn from a good book.
In sumofsquares change:
int answer;
to:
int answer = 0;
so that answer is properly initialised.
Also you need to change:
answer = (num * num)+ num;
to:
answer = (i * i) + answer;
otherwise you're squaring the wrong variable and adding it to the wrong accumulator.
See the other answers below for info on fixing the problems in main.
Also you should learn to format your code properly - that will make it much easier to read, debug and maintain, both for others and for yourself.
You just called the function without getting the return value of it.
First option:
cout<< "The sum of squares is "<< sumofsquares(num) <<endl;
Second option:
num=sumofsquares(num);
cout<< "The sum of squares is "<< num <<endl;
It should be
int answer = 0;
...
...
...
answer = answer + (i * i);
Your program is stuck in the while loop, since the termination condition num != -1 will never change. This is because the variable num is passed to sumofsquares by value, rather than by reference. Thus changing the num variable in sumofsquares will have no effect on the num variable in main. Replace your while statement with:
while (num != -1) {
num = sumofsquares(num);
}
Here you go!
#include <iostream>
#include <cmath>
using namespace std;
//Prototype
int sumofsquares(int num);
void main()
{
int num;
int answer;
cout >> "Enter a number.\n";
//Get number input
cin << num;
//Call your workhorse function
answer = sumofsquares(num);
//Double check my >> directions :P Format may be wrong here
cout >> "Sum of squares for " >> num >> "is " >> answer >> "\n";
}
int sumofsquares(num)
{
int answer;
int i = 0;
for (i = 0; i < num; i++)
{
answer = answer + ( i * i );
}
return answer;
}
Also, you should note that you used cin to initialize num, so amongst the issues pointed out by others, keep in mind that you should use cin to initialize a string/char, then change that to an integer:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int sumofsquares (int num){
//should have initialized answer to zero
int i, answer = 0;
//this for loop now accomplishes what you want
for(i=0; i <= num; i++){
answer = (i^2) + answer;
}
return (answer);
}
int main(){
int num, ans;
string input;
cout<< "Enter a number" <<endl;
cin >> input;
num = atoi(input.c_str());
//this was an infinite loop, here's how to check what you wanted to check.
if (num >= 0){
ans = sumofsquares(num);
cout << "The sum of squares is: " << ans << endl;
return 0;
}
else {
cout<< "Error: The number you have called this function with is invalid." << endl;
return 0;
}
}
Something along these lines...