Palindroms numbers between 1 to 10000 - c++

I want to write a program which displays palindromes numbers between 1 and 10000, I wrote a script which displays if the number typed by the user is a palindrome or no but when I add the for loop it gives me false results
My code:
#include<iostream>
using namespace std;
int main()
{
int num, reverse = 0, remainder, temp;
for(num=0;num<1000;num++){
temp = num;
cout << "temp = " << temp << endl;
while( temp != 0)
{
remainder = temp % 10;
reverse = reverse * 10 + remainder;
temp = temp / 10;
cout << "remainder = " << remainder << endl;
cout << "reverse = " << reverse << endl;
cout << "temp = " << temp << endl;
}
cout << "Reversed number: " << reverse << endl;
if (num == reverse)
cout << "\n" << num << " is a palindrome number." << endl;
else
cout << "\n" << num << " is not a palindrome number." << endl;
}
return 0;
}

You need to make sure that reverse is always 0 at the start of loop iteration:
for(num=0;num<1000;num++){
reverse = 0;
temp = num;
cout << "temp = " << temp << endl;
while( temp != 0)
{
remainder = temp % 10;
reverse = reverse * 10 + remainder;
temp = temp / 10;
cout << "remainder = " << remainder << endl;
cout << "reverse = " << reverse << endl;
cout << "temp = " << temp << endl;
}
cout << "Reversed number: " << reverse << endl;
if (num == reverse)
cout << "\n" << num << " is a palindrome number." << endl;
else
cout << "\n" << num << " is not a palindrome number." << endl;
}
Managing variables becomes much easier if you declare them where you need them instead of lumping everything together:
int main()
{
for(int num=0;num<1000;num++){
int reverse = 0;
int temp = num;
int remainder = 0;
cout << "temp = " << temp << endl;
while( temp != 0)
{
remainder = temp % 10;
reverse = reverse * 10 + remainder;
temp = temp / 10;
cout << "remainder = " << remainder << endl;
cout << "reverse = " << reverse << endl;
cout << "temp = " << temp << endl;
}
cout << "Reversed number: " << reverse << endl;
if (num == reverse)
cout << "\n" << num << " is a palindrome number." << endl;
else
cout << "\n" << num << " is not a palindrome number." << endl;
}
return 0;
}
Now you are sure remainder is always initialized at the start of for loop iteration and it cannot live longer than one iteration (for example, it won't live to the next iteration).

I checked your program and noticed a few flaws:
1) All 1-digit numbers are Palindrome because their is reverse is same.
---Your program didn't display them as palindromes.
2) You don't have to display all the details like their remainder and reverse.
---Obviously the Palindromes reverse will be the same as the original. We don't need to display non-palindromes. In some cases reverse was displaying garbage values as well. I don't find a reason that will be of any help to the user.
Solution:-
#include<iostream>
using namespace std;
bool findPalindrome(const int);
int main()
{
for (int i = 0; i < 10000; i++) {
if (findPalindrome(i)) {
cout << "Number " << i << " is a Palindrome!" << endl;
}
}
return EXIT_SUCCESS; // Return EXIT_SUCCESS is my Specialty :D
}
bool findPalindrome(const int num) {
int temp = num;
int reve = 0;
while (temp != 0) {
reve = (reve * 10) + (temp % 10);
temp /= 10;
}
return (reve == num);
}

In addition to the excellent codes other people have posted (I would go with those), this is another (and more readable) way in which you can do the same thing..
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
bool isPalindrome(unsigned number) {
std::vector<unsigned> number_as_vec;
while (number) {
number_as_vec.push_back(number % 10);
number /= 10;
}
for (size_t i = 0, j = number_as_vec.size() - 1; i < j; i++, j--) {
if (number_as_vec.at(i) != number_as_vec.at(j)) {
return false;
}
}
return true;
}
int main(int argc) {
unsigned num = 1;
while (num != 10001) {
if (isPalindrome(num)) {
std::cout << num << "\n";
}
num++;
}
return 0;
}
Also, instead of using vectors, one can simply use a string here:
bool isPalindrome(unsigned number) {
std::string num_as_string(std::to_string(number));
for (size_t i = 0, j = number_as_string.size() - 1; i < j; i++, j--) {
if (number_as_string.at(i) != number_as_string.at(j)) {
return false;
}
}
return true;
}

Related

Is there any way to get rid of the "*" in the last digit of factorial of integers in C++ program

The output of my code is:
5! = 1 * 2 * 3 * 4 * 5 * = 120
How can I remove the last * to have this output:
5! = 1 * 2 * 3 * 4 * 5 = 120
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int n, count, factorial = 1;
cout << "Enter a positive integer: ";
cin >> n;
cout << n << "! = ";
if (n < 0){
cout << "Error! Factorial of a negative number doesn't exist.";
}
else{
while(count < n){
count++;
factorial = factorial * count ;
cout << count << " * ";
}
cout << " = " << factorial;
}
}
Yes add an if that checks if you're not on your last number.
(Also don't use using namespace std, Why is "using namespace std;" considered bad practice?)
#include <iostream>
int main(int argc, char** argv)
{
int n = 0;
int count = 0;
int factorial = 1;
std::cout << "Enter a positive integer: ";
std::cin >> n;
std::cout << n << "! = ";
if (n < 0)
{
std::cout << "Error! Factorial of a negative number doesn't exist.";
}
else
{
while (count < n)
{
count++;
factorial = factorial * count;
std::cout << count;
// only show * if not on last number
if (n != count) std::cout << " * ";
}
std::cout << " = " << factorial;
}
}
Your code, prettied up a little bit:
else {
while (count < n) {
count++;
factorial += count ;
cout << count << " * ";
}
cout << " = " << factorial;
}
Now, let's put that " * " separator into a variable.
else {
string sep = " * ";
while (count < n) {
count++;
factorial *= count ;
cout << count << sep;
}
cout << " = " << factorial;
}
Still the same result, but let's try this:
else {
string sep = " * ";
while (count < n) {
count++;
factorial *= count ;
cout << sep << count;
}
cout << " = " << factorial;
}
Now we get the extra " * " in front of the first number. It'd work a lot better if sep were "" on the first iteration, and then we changed it to " * " on every other iteration.
else {
string sep = "";
while (count < n) {
count++;
factorial *= count ;
cout << sep << count;
sep = " * ";
}
cout << " = " << factorial;
}

Error when counting negative numbers from a text file to make frequency table

I am creating a program to make a frequency table range from <=0 to >=10 of integer numbers from a text file. However when I run the program, if it contains number that <= 0 or >= 10 all other numbers are added up but the negative numbers is not counted. I think my problem lies in my If-statement but I dont know how to correct it. This is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream abc("beef.txt");
int num;
int tem;
int N;
int noNum = 0;
cout << "Class" << " | " << "Frequency" << endl;
cout << "_________|___________" << endl;
while (abc >> tem) {
noNum++;
}
for (num = 0; num < 11; num++) {
N = 0;
while (abc >> tem) {
if (num == tem) {
N = N + 1;
}
if (tem < 0) {
N = N + 1;
}
if (tem > 10) {
N = N + 1;
}
}
abc.clear(); //clear the buffer
abc.seekg(0, ios::beg); //reset the reading position to beginning
if (num == 0) {
cout << "<=0" << " | " << N << endl;
}
else if (num == 10) {
cout << ">=10" << " | " << N << endl;
}
else {
cout << " " << num << " | " << N << endl;
}
}
cout << "The number of number is: " << noNum << endl;
}
For example if there is -5 in the text file the program would run like this
The problem is twofold. First, you forgot two clear and reset the buffer after counting the number of elements. Second, you always count the numbers lower than zero and greater than 10. You should only do this when num is 0 or 10 respectively.
The correct code should look like this:
ifstream abc("beef.txt");
int num;
int tem;
int N;
int noNum = 0;
cout << "Class" << " | " << "Frequency" << endl;
cout << "_________|___________" << endl;
while (abc >> tem) {
noNum++;
}
for (num = 0; num < 11; num++) {
abc.clear(); //clear the buffer
abc.seekg(0, ios::beg); //reset the reading position to beginning
N = 0;
while (abc >> tem) {
if (num == tem) {
N = N + 1;
}
if (tem < 0 && num == 0) {
N = N + 1;
}
if (tem > 10 && num == 10) {
N = N + 1;
}
}
if (num == 0) {
cout << "<=0" << " | " << N << endl;
}
else if (num == 10) {
cout << ">=10" << " | " << N << endl;
}
else {
cout << " " << num << " | " << N << endl;
}
}
cout << "The number of number is: " << noNum << endl;

Unhandled exception at 0x012B1CA9

I am new to C++ and am trying to build a simple program that with the users input to proceed will generate a random left or right. I had the program working correctly until I added in the array to try and store each item as I have to output them as soon and the user would like to exit the loop. The program seems to compile fine but at run time I receive "Unhandled exception at 0x012B1CA9" Any help would be greatly appreciated.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = '100';
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
cout << "Press 1 to pick a side or 0 to quit: ";
cin >> userSelection;
for (int i = 1; i < MAX; i++)
{
srand(time(NULL));
sel[i] = 1 + (rand() % 2);
if (sel[i] == 1)
{
cout << "<<<--- Left" << endl;
one++;
total++;
}
else
{
cout << "Right --->>>" << endl;
two++;
total++;
}
}
} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};
You have a multi-character constant here... and the behavior doesn't go as expected...
Change this line
const int MAX = '100';
to
const int MAX = 100;
Note the removed single quotes.
And secondly, I will advice you to remove the Seed of the C random generator from the for loop because, you'll likely get the same values from the rand() if you always call it immediately after seeding...
But preferable use the algorithm from C++'s random header
Here is a corrected version of your original code....
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = 100; // <---changed
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
cout << "Press 1 to pick a side or 0 to quit: ";
cin >> userSelection;
srand(time(NULL)); //< moved to here
for (int i = 0; i < MAX; i++) // <-- modified starting index
{
sel[i] = 1 + (rand() % 2);
if (sel[i] == 1)
{
cout << "<<<--- Left" << endl;
one++;
total++;
}
else
{
cout << "Right --->>>" << endl;
two++;
total++;
}
}
} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};
I think that it is basically good idea to read more about C data types and declaration. Your error:
const int MAX = '100' should be const int MAX = 100 without any quotes. C++ does implicit conversion from character literals to int.

Access Violation Violation Location With Low Numbers

I'm working on an assignment for school. The code is supposed to read form a file and create an array, then sort the values of the array to output certain info. It works just fine as long as I have 3+ lines of info in the file. If not, I get the following error:
First-chance exception at 0x01305876 in Homework11.exe: 0xC0000005: Access violation reading location 0xcd71b288.
Unhandled exception at 0x01305876 in Homework11.exe: 0xC0000005: Access violation reading location 0xcd71b288.
I can't figure out why, any help would be appreciated. Here's the code:
#include <iostream> //calls the information needed
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <string>
using namespace std; //sets all unmarked commands to std::
const int ARRSIZE = 1000;
struct Student
{
string firstName;
string lastName;
string id, temp;
double gpa;
};
int readArray(ifstream& ifile, Student arr[]);
void swapElements(Student arr[], int i, int j);
void sortArray(Student arr[], int numberInTheArray);
int main()
{ // Declares the needed variables
double sought, min, max;
int i, ival, returnvar, count = 0, mincount, maxcount;
string filename;
ifstream ifile;
Student arr[ARRSIZE];
cout << "Input File Name: ";//requesting the file name
cin >> filename;
ifile.open(filename.c_str());//opening the file
if (!ifile)//checking if it opened or not
{
cout << endl << "That file does not exist!" << endl;//informing the user it did
return 1;//not open and returning 1
}
cout << "Which number do you want to return? ";//requesting the desired number
cin >> ival;
i = ival - 1;
cout << endl;
returnvar = readArray(ifile, arr);
min = arr[0].gpa;
max = arr[0].gpa;
sought = arr[0].gpa;
while (count < returnvar)
{
if (arr[count].gpa < min)
{
min = arr[count].gpa;
mincount = count;
}
if (arr[count].gpa > max)
{
max = arr[count].gpa;
maxcount = count;
}
if (count == i)
{
sought = arr[count].gpa;
}
count++;
}
if (count == 0)
{
cout << "The file is empty!" << endl;
return 1;
}
cout << "Before Sort:" << endl;
cout << " Min GPA is " << min << " for " << arr[mincount].lastName << "." << endl;
cout << " Max GPA is " << max << " for " << arr[maxcount].lastName << "." << endl;
if (returnvar < ARRSIZE)
{
cout << " WARNING: Only " << returnvar << " numbers were read into the array!" << endl;
}
if (i >= returnvar)
{
cout << " There aren't that many numbers in the array!" << endl << endl;
}
else if (i > ARRSIZE)
{
cout << " " << i << " is bigger than " << ARRSIZE << "!" << endl << endl;
}
else if (i < returnvar)
{
cout << " Value " << ival << " is " << sought << " for " << arr[i].lastName << "." << endl << endl;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
sortArray(arr, returnvar);
count = 0;
while (count < returnvar)
{
if (arr[count].gpa < min)
{
min = arr[count].gpa;
mincount = count;
}
if (arr[count].gpa > max)
{
max = arr[count].gpa;
maxcount = count;
}
if (count == i)
{
sought = arr[count].gpa;
}
count++;
}
cout << "After Sort:" << endl;
cout << " Array[0] GPA is " << min << " for " << arr[0].lastName << "." << endl;
cout << " Array[" << (returnvar - 1) << "] GPA is " << max << " for " << arr[(returnvar - 1)].lastName << "." << endl;
if (returnvar < ARRSIZE)
{
cout << " WARNING: Only " << returnvar << " numbers were read into the array!" << endl;
}
if (i >= returnvar)
{
cout << " There aren't that many numbers in the array!" << endl << endl;
}
else if (i > ARRSIZE)
{
cout << " " << i << " is bigger than " << ARRSIZE << "!" << endl << endl;
}
else if (i < returnvar)
{
cout << " Value " << ival << " is " << sought << " for " << arr[i].lastName << "." << endl << endl;
}
return 0;
}
int readArray(ifstream& ifile, Student arr[])
{
int counter = 0;
while ((ifile) && (counter <= ARRSIZE))
{
ifile >> arr[counter].firstName;
ifile >> arr[counter].lastName;
ifile >> arr[counter].id;
ifile >> arr[counter].gpa;
counter++;
}
return (counter - 1);
}
void sortArray(Student arr[], int numberInTheArray)
{
for (int i = 0 ; i < numberInTheArray - 1; i++)
{
for (int j = 0 ; j < numberInTheArray - 1; j++)
{
if ( arr[j].gpa > arr[j + 1].gpa)
{
swapElements(arr, j, j+1);
}
}
}
}
void swapElements(Student arr[], int i, int j)
{
Student temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Please ignore the insanity and comments. Like I said, for an entry level course.
Try replacing counter <= ARRSIZE with counter < ARRSIZE (a rule of thumb in C is: never use <= in operations related to container sizes).
EDIT: also in your main(), you must check that i < ARRSIZE (equivalently, return error if i >= ARRSIZE). At present you seem to accept the case i == ARRSIZE, which is also wrong. And finally, readArray should return counter (that is, one more than the last written index).

Output desired number of columns

I was wanting to get some tips on how to get my program to output a desired number of columns by the user. For example, if the user enters 2 for termsPerLine, then the program should print the values generated by the Juggler series in two columns, or if the user enters 3 for termsPerLine, 3 columns and so forth. The output variable is firstTerm. Any assistance would be great.
#include <string>
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int ValidateInput(string Prompt);
int main()
{
int count;
double Odd;
double Even;
long long int firstTerm;
int noOfTerms;
int termsPerLine;
cout << "Program will determine the terms in a Juggler Series" << endl << endl;
firstTerm = ValidateInput("Enter the first term: ");
noOfTerms = ValidateInput("Enter the number of terms to calculate (after first): ");
termsPerLine = ValidateInput("Enter the terms to display per line: ");
cout << "First " << noOfTerms << " terms of JUGGLER SERIES starting with " << firstTerm << endl;
count = 1;
do
{
if (firstTerm % 2 == 0 )
{
firstTerm = pow(firstTerm , 0.5);
cout << setw(16) << firstTerm << endl;
count++;
}
if (firstTerm % 2 != 0 )
{
firstTerm = pow(firstTerm, 1.5);
cout << setw(16) << firstTerm << endl;
count++;
}
}
while (count <= noOfTerms);
cout << endl;
system("Pause");
return 0;
}
int ValidateInput( string Prompt)
{
int num;
cout << Prompt << endl;
cin >> num;
while ( num <= 0 )
{
cout << "Enter a positive number" << endl;
cin >> num;
}
return num;
}
Try this at the top of the loop:
if ((count % termsPerLine) == 0)
{
cout << "\n";
}
or this at the bottom of the loop:
if ((count % termsPerLine) == termsPerLine)
{
cout << "\n";
}
just Fix your loop as:
for (count = 1; count <= numOfTerm; count++)
{
if(firstTerm % 2 == 0)
firstTerm = pow(firstTerm, 0.5);
else
firstTerm = pow(firstTerm, 1.5);
if(count % termPerLine != 0)
cout << setw(15) << firstTerm;
else
cout << setw(15) << firstTerm << endl;
};