Checking Palindrome numbers function recursively in C++ - c++

I don't how to get it work recursively.
I'm trying to code the Palindrome function recursively. I understand what should i do like that:
1 => single digit, therefore yes
--------
12 => 1 != 2, therefore no
--------
121 => 1 == 1, therefore yes
2 => single digit, therefore yes
--------
1234421 => 1 == 1, therefore yes
23442 => 2 == 2, therefore yes
344 => 3 != 4, therefore no
However, i got a question. It doesn't work recursively. I need help.
Do i miss something?
// Check if a positive integer is a Palindrome
#include <iostream>
using namespace std;
bool isPalindrome(int number, int factor);
int main()
{
int number; // a positive integer
cout << "Enter a positive integer: ";
cin >> number;
// puts 10^(numDigits-1) (i.e., the smallest numDigits-digit positive integer) into factor
int temp = number;
int factor = 1; // power of ten
while (temp > 9)
{
temp /= 10;
factor *= 10;
}
// print whether the number is a palindrome
if (isPalindrome(number, factor))
cout << endl << number << " is a palindrome." << endl << endl;
else
cout << endl << number << " is not a palindrome." << endl << endl;
system("pause");
}
bool isPalindrome(int number, int factor){
int checkFirst, checkSecond, temp;
if (number / 10 > 0){
checkFirst = number / factor;
checkSecond = number % 10;
if (checkFirst == checkSecond){
temp = number%factor;
number = temp;
isPalindrome(number / 10, factor / 10);
}
else
{
return false;
}
}
else
{
return true;
}
}

Two things.
The return value of isPalindrome() is not used when called recursively. Add it as a return statement.
return isPalindrome(number / 10, factor / 10);
Also the factor reduces by 100 every time you check two digits. So divide factor by 100.
return isPalindrome(number / 10, factor / 100);

Thanks a lot!!
// Check if a positive integer is a Palindrome
#include <iostream>
using namespace std;
bool isPalindrome(int number, int factor);
int main()
{
int number; // a positive integer
cout << "Enter a positive integer: ";
cin >> number;
// puts 10^(numDigits-1) (i.e., the smallest numDigits-digit positive integer) into factor
int temp = number;
int factor = 1; // power of ten
while (temp > 9)
{
temp /= 10;
factor *= 10;
}
// print whether the number is a palindrome
if (isPalindrome(number, factor))
cout << endl << number << " is a palindrome." << endl << endl;
else
cout << endl << number << " is not a palindrome." << endl << endl;
system("pause");
}
bool isPalindrome(int number, int factor){
int checkFirst, checkSecond, temp;
if (number / 10 > 0){
checkFirst = number / factor;
checkSecond = number % 10;
if (checkFirst == checkSecond){
temp = number%factor;
number = temp;
return isPalindrome(number / 10, factor / 100);
}
else
{
return false;
}
}
else
{
return true;
}
}

Related

Beginner to C++ - How to sum up only positive or only negative integers the user inputs and how to calculate the avg

Total Noob here, I am having a hard time with an assignment. I am taking a beginner course in C++ and have to figure out how to calculate the sum of negative integers and their avg. Sum of positive integers and the avg. And the sum of all numbers and the avg. I have gotten the last part already but how do I calculate the sum of negative integers and avg, and positive integers and avg using a while loop?
I provided my code below.
#include <iostream>
using namespace std;
#include <iomanip>
int main(int argc, const char * argv[]) {
int x;
double avg = 0.0;
int count = 0;
int sum = 0;
// ask users for input
cout << ("Welcome to the greatest calculator!\n");
cout << ("Please enter 10 integers seperated by spaces \n");
do {
std::cin >> x;
sum = sum + x;
count = count + 1;
}
while (count < 10);
// calculate average
avg = sum/10.0;
// output average
cout << fixed;
cout << "For all 10 numbers the sum is " << sum << "." "The average is " << setprecision (2) << sum/10.0 <<".\n";
return 0;
}
The output should look something like this.
Please enter 10 integers separated by spaces:
1 -1 45 17 28 -2 0 9 -14 11
Upon our intelligent calculations, here is the result:
+ There are 7 positive numbers, sum = 111.00 and average = 15.86
+ There are 3 negative numbers, sum = -17.00 and average = -5.67
+ For all 10 numbers, sum = 94.00 and average = 9.40 */
Use two variable int negativeVar=0 , PositiveVar=0 . In the loop try a condition if(GivenNumber<0) to detect the given number is negative or positive. Then add all positive and negative value separately and make avarage.
(Sorry for bad english)
You can do like this (notice comments):
#include <iostream>
int main(void) {
// Declaration and initialization of the required variables
float cPositive = 0.0f;
float cNegative = 0.0f;
int it = 0;
std::cout << "Enter 10 numbers (floating point assignable): \n";
// Looping till 10 iterations
do {
float temp;
std::cin >> temp;
// If the number is greater than zero, i.e. (+ve) then cPositive sums up
// otherwise, cNegative
if (temp > 0) cPositive += temp;
else if (temp <= 0.0f) cNegative -= temp;
} while (++it < 10); // Increment and comparison together
// Final results
std::cout \
<< "Sum of positive: " << cPositive << std::endl
<< "Sum of negative: -" << cNegative << std::endl;
return 0;
}
A simple test case:
Enter 10 numbers (floating point assignable):
10.5
-1.5
2.2
5.5
-3.8
-99.3
10
4.5
-1.0
0
Sum of positive: 32.7
Sum of negative: -105.6
Moreover, if you want to see average, then declare two variables, pos and neg where both are initially zero. After that, when a positive number or negative number occurs, just increment pos or neg and divide with them by cPositive or cNegative respectively.
#include <iostream>
#include <string>
using namespace std;
int main()
{
// lets declare some variable first.
int positiveSum =0; //this will hold sum of positive nums
int negativeSum =0; // this will hold sum of negative nums
int totalSum =0; // this will hold sum of all the nums
int number=0; // user input for number
for (int i = 1; i <=10; i++) // loop from 1 to 10 times
{
cout << " Enter a number: ";
cin >> number;
// now check if number is positive or negative
if (number >=0)
{
positiveSum += number; // adds this number to positiveSum
}
else if (number < 0)
{
negativeSum += number; // adds this number to negativeSum
}
}
// So finally add the positiveSum and negativeSum to get the totalSum
totalSum = positiveSum + negativeSum;
cout << endl;
cout << " Total of Positive numbers is: " << positiveSum << endl;
cout << " Total of Negative numbers is: " << negativeSum << endl;
cout << " Total of all numbers is: " << totalSum << endl;
return 0;
}
The code below produces the following output:
$ ./main
The (sum, avg) of negative integers = (-15, -5)
The (sum, avg) of positive integers = (6, 2)
The (sum, avg) of all numbers = (-9, -1.5)
Please read the comments because they are in fact the detailed answer.
#include <array>
#include <iostream>
int main()
{
// For convenience, keep the numbers in an std::array. std::vector is
// equally convenient.
std::array<int, 6> integers { 1, -4, 2, -5, 3, -6 };
// Define variables that store the sums and the counts.
int positiveSum = 0;
int positiveCnt = 0;
int negativeSum = 0;
int negativeCnt = 0;
// Iterate over the numbers taking one of them at a time.
int i = 0;
while (i < integers.size())
{
int number = integers[i];
// Is the number positive?...
if (number >= 0)
{
// ... it is - add it to the positive sum and increment the count.
positiveSum += number;
++positiveCnt;
}
// The number is not positive, so it must be negative...
else
{
// ... add it to the negative sum and increment the count.
negativeSum += number;
++negativeCnt;
}
// Get ready for the next number.
++i;
}
// Time to print out the results.
// Note that before we calculate the average, we have to cast at least one
// of the terms of the division to floating point type. Otherwise the
// division will be done with integers where the result is also an integer
// (e.g. 3 / 2 -> 1).
// Only affter the casting you will be getting expected answers
// (e.g. double(3) / 2 -> 1.5).
std::cout <<
"The (sum, avg) of negative integers = (" <<
negativeSum << ", " <<
double(negativeSum) / negativeCnt << ")" << std::endl;
std::cout <<
"The (sum, avg) of positive integers = (" <<
positiveSum << ", " <<
double(positiveSum) / positiveCnt << ")" << std::endl;
std::cout <<
"The (sum, avg) of all numbers = (" <<
negativeSum + positiveSum << ", " <<
double(negativeSum + positiveSum) / (negativeCnt + positiveCnt) << ")" << std::endl;
}
#include <iostream>
using namespace std;
int main()
{
char op;
float num1,num2;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch(op)
{
case '+':
cout << num1+num2;
break;
case '-':
cout << num1-num2;
break;
case '*':
cout << num1*num2;
break;
case '/':
cout << num1/num2;
break;
default:
//If the operator is other than +,-,*,/, error message is shown.
cout << "Error! operator is not correct";
break;
}
return 0;
}

maximum power a number can be raised to with out exceeding y recursion

i have this program assignment and one part of it is trying to find the max power a number will go to(x) without exceeding a number the user inputs it not to exceed(y). we are using it in a function. this is the whole program and what i have for max power it just keeps returning 0. it is the int maxpower(int x, int y) function i am trying to figure out
#include <iostream>
#include <cmath>
using namespace std;
// meunue where you can get your options from
void menue() {
cout << "choose the following options:" << endl;
cout << "1) Power of x raised by y." << endl;
cout << "2) Find the max power a number can be raised to." << endl;
cout << "3) Print out a number with its digits in reversed order." << endl;
cout << "4) Sum of integers from 1 to n." << endl;
cout << "5) Product of integers from 1 to n." << endl;
cout << "6) Quit" << endl;
}
//functions for finding the power usign recursion
int Power(int a, int b) {
int x = 1, i;
for (i = 1; i <= b; i++) {
if (b == 0) {
return Power(a, b--);
}
else {
x = x * a;
}
}
return x;
}
int maxpower(int n, int max_value) {
int temp = temp * n;
if (temp > max_value)
return 0;
else return maxpower(n, max_value + 1);
}
int reverse(int number) {
int lastDigit, numberOfDigits, sign = 1;//sets the sign equal to one
// if number is less than 0 returns 0
if (number < 0) {
return 0;
}
else
//if a number is under 10 than it can not be switched so you times the number by 10 and switch it.
if (number < 10)
return number * sign;
lastDigit = number % 10;
number = number / 10;
numberOfDigits = log10(number) + 1;
//recursive statement that calls the function
return (lastDigit * pow(10, numberOfDigits) + reverse(number)) * sign;
}
//finding the sum
int sum(int n) {
if (n != 0) {
return n + sum(n - 1);//recursive statement
}
else {
return n;
}
}
//finding the product
int product(int n) {
int temp;
if (n <= 1) {
return 1;
}
else {
temp = n * product(n - 1);
// recursive statement setting temp == to recursive statement
return temp;//returning temp
}
}
int main() {
int a;
int x;
int y;
int length = 0;
int temp;
int results;
// calls menue and get prints all the options
do {
menue();
//inserts the choice
cin >> a;
cout << "you choose:" << a << endl;//prints the choice out.
//switch statement that will take account for the number you choose and prints the results
switch (a) {
case 1:
cout << "enter the number to raise" << endl;
cin >> x;
cout << " enter the power to raise to: " << endl;
cin >> y;
Power(x, y);
cout << "the result is:" << Power(x, y) << endl;
break;
case 2:
cout << "Enter the number to raise:" << endl;
cin >> x;
cout << "Enter the number not to exceed:" << endl;
cin >> y;
maxpower(x, y);
cout << "the result is:" << maxpower(x, y) << endl;
break;
case 3:
cout << " enter numbers to be reversed by: " << endl;
cin >> x;
temp = x;
while (temp != 0) {
length++;
temp = temp / 10;
}
reverse(x);
cout << "the result is:" << reverse(x) << endl;
break;
case 4:
cout << "enter the number to sum to: " << endl;
cin >> x;
sum(x);
cout << "the result is:" << sum(x) << endl;
break;
case 5:
cout << "enter the number to multiply to:" << endl;
cin >> y;
product(y);
cout << "the result is:" << product(y) << endl;
break;
case 6:
cout << "good bye!!" << endl;
break;
}
} while (a != 6);
return 0;
}
I don't think it's necessary to use recursion for this problem. Moreover, recursion is creating a lot of overhead while solving it with a loop works just fine. Do you have to use recursion? If so, then disregard this answer :p. But you'll find below a solution that will work.
Note the #include <math.h> bit - you need that to use pow(base, exponent).
Also, while(true) is definitely not the best practice, but as long as you have sufficient checks to get out of the loop properly then you're ok. Hence the max_iteration and the actual return statement that you're looking for.
Best of luck!
#include <iostream>
#include <math.h>
int maxpower(int n, int max_value) {
if ( n > max_value ) return 0;
int previous, current = 1;
int max_iteration = 0;
while (true) {
if (max_iteration >= 1000) return -1;
if (pow(n, current) > max_value) {
return previous;
}
previous = current;
current++;
max_iteration++;
}
}
int main() {
int x;
int y;
int result;
std::cout << "Enter the base: ";
std::cin >> x;
std::cout << "Enter the max number x^pow should not exceed: ";
std::cin >> y;
result = maxpower(x, y);
if (result == -1) {
std::cout << "Max iteration reached." << std::endl;
}
else {
std::cout << result << " is the maximum power such that " << x << "^" << result << " does not exceed " << y << std::endl;
}
return 0;
}
As an example of output:
If x = 2 and y = 32, the program will return 5 as the max power (i.e. 2^5 = 32 and is not greater than, but 2^6 > 32).
EDIT:
I realized after I posted that all of your functions are recursive, so perhaps that's a requirement for your assignment. Anyway, below is a recursive solution:
int maxpower_rec_helper(int n, int power, int max_value) {
if (pow(n, power) > max_value) return power - 1;
return maxpower_rec_helper(n, power + 1, max_value);
}
int maxpower_rec(int n, int max_value) {
if ( n > max_value ) return 0;
return maxpower_rec_helper(n, 1, max_value);
}
You'll need a helper function to give the initial power 1, and so as not to disturb your max_value.
return power - 1; is essentially the same thing as return previous; in the iterative example above.

How to prevent a final cout in a loop from being executed?

I am trying to write a code which gives the prime factorization of given integer.
Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
void primefactor(int a);
int main()
{
int n;
cout<<" Enter the value of n "<<endl;
cin>>n;
primefactor(n);
return 0;
}
void primefactor(int a){
while(a%2==0){
cout<<"2*";
a/=2;
for(int i=3; i<=sqrt(a); i+=2){
while(a%i==0){
cout<<i<<"*";
a=a/i;
}
}
if(a>2){
cout<<a<<endl;
}
}
however when i run the output at the last factor i am getting an additional * in factorization. How can I remove this?
You can use
if (a != 2)
cout<<"2*";
else
cout<<"2";
instead of cout<<"2*";
I had the same issue and solved it with a goto statement.
#include <iostream>
#include <math.h>
using namespace std;
void primeFactorization(int number) {
cout << number << ": ";
// WHILE number is even
while (number % 2 == 0) {
// SET number = number / 2
number = number / 2;
// PRINT 2
cout << 2 << " " ;
// END WHILE
}
// GOTO TERMINAL
reloop:
// FOR factor in 3 to the sqrt(number), by 2
for (int factor = 3; factor <= sqrt(number); factor = factor + 2) {
// IF number modular factor equals 0 THEN
if (number % factor == 0) {
// PRINT factor
cout << factor << " " ;
// SET number = number / factor
number = number / factor;
// GOTO INITIAL
goto reloop;
// END IF
}
// END FOR
}
//IF number > 2 THEN
if (number > 2) {
//PRINT number
cout << number;
//END IF
}
cout << endl;
}
int main() {
int usersNumber;
bool userWants2Play = true;
while (userWants2Play) {
cout << "Please enter a number to be factored: " ;
cin >> usersNumber;
primeFactorization(usersNumber);
cout << "Do you want to play again? 1 or 0: " ;
cin >> userWants2Play;
}
return 0;
}
The goto statement allows for the new odd number to go through the loop again. This lets the odd prime factors print and allows the new old number to be factored again, if the factor exists.

Classifying digits of an integer value

I spent a day on this code for count even and zero and odd numbers
From long datatype I used a function to send data. Here is the code
#include <iostream>
using namespace std;
void digitCount(long long int &num);
int main ()
{
long long int num;
cout <<"Enter any No. " <<endl;
cin >>num;
cout <<endl;
digitCount(num);
return 0;
}
void digitCount(long long int &num)
{
int e = 0, z = 0, o = 0, x = 0;
for (int i = 0; i <= num; i++)
{
x= num % 10;
if(x == 0)
{
++z;
num = num / 10;
}
else if(x%2==1)
{
++o;
num = num / 10;
}
else
{
++e;
num = num / 10;
}
}
cout << "No of zeros Digits = " << z<< endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
the problem is when I count odd numbers there is a number missed
for example when i input : 12345
the result is
no of even : 2
no of odd : 2 (should be 3)
no of zero : 0
and here the question :
Write a function that takes as parameter an integer (as a long value) and returns the number of odd, even, and zero digits. Also write a program to test your function. Use pass by reference method.
Instead of the for loop you should use:
while (num > 0)
You're constantly changing num and when it gets to 1 (in your 12345 example), i is at 3. I also modified your digitcount to demonstrate some decent formatting for readable code.
void digitCount(long long int &num) {
int e(0), z(0), o(0), x(0);
while (num > 0) {
x = num % 10;
if (x == 0) {
z++;
}
else if (x % 2 == 1) {
o++;
}
else {
e++;
}
num /= 10;
}
cout << "No of zeros Digits = " << z << endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
If you believe this solves your problem && is the best answer, please click the checkmark next to this answer. Thanks

Separating Digits in C++

I am working on an exercise from my C++ book and I'm not sure how to fix it. I am supposed to get an int from the user and display the individual digits in the order they were entered. For instance 12345 would be displayed 1 2 3 4 5. 7365 would be displayed 7 3 6 5. I have most of the code written but there is a logical error and I can't figure it out. Here is my code:
int main()
{
int number = 0;
int digit = 0;
int temp = 0;
int counter = 0;
int sum = 0;
int divisor = 0;
cout << "Please enter a nonzero number.";
cin >> number;
cout << "\nThe number you entered was " << number;
// Determine the number of digits
temp = number;
while (temp != 0)
{
temp = temp / 10;
counter++;
}
cout << "\nThere are " << counter << " digits in your number.";
// Separate the digits
temp = number;
cout << "\nSeparating the digits\n";
do
{
divisor = (pow(10.0, --counter));
digit = temp / divisor;
temp = temp % divisor;
cout << digit << " ";
sum = sum + digit;
}
while (counter != 0);
cout << "\nThe sum of the number is " << sum;
return 0;
}
When I enter 5555 the output is 5560. When I enter 1234 the output is 1236. Can anyone help me find my error?
Here's one version:
// If the number is only one digit, print it.
// Otherwise, print all digits except the last, then print the last.
void digits(int x)
{
if (x < 10){
cout << x;
}
else{
digits(x / 10);
cout << " " << x % 10;
}
}
Thank you all for your help :-) Turns out my code works fine in another compiler so I guess it's just a netbeans glitch.