Reversing a number (C++) - c++

I am brand new to C++, and am trying to make a simple program to determine if a user-entered integer is four digits, and if so, to reverse the order of said digits and print that output.
I have a (mostly) working program, but when I try, one of two things happens:
a) if line 16 is commented out and line 17 is active, then the program prints out an infinite number of reversed numbers and the IDE (in this case, repl.it) crashes; or
b) if line 17 is commented out and line 16 is active, then the program prints out one correct line, but the next line is "Your number is too short...again" (look at code below)
#include <iostream>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main() {
int n, reversedNumber, remainder;
bool loopControl;
char userFinalResponse;
reversedNumber=0;
cout<<"Input a 4 digit integer and press Return\n"<<endl;
cin>>n;
while (loopControl=true){
//if ((n>9999)||(n<1000))
if ((n>9999)||((n<1000)&&(n>0)))
{
cout<<"Your number is too short or too long. Please try again.\n"<<endl;
cin>>n;
loopControl=false;
} else {
while(n != 0)
{
remainder = n%10;
reversedNumber=reversedNumber*10+remainder;
n /= 10;
loopControl=true;
}//closing brace for reversal loop
cout<<"Your reversed number is "<<reversedNumber<<"\n"<<endl;
}//closing brace for else
}//closing brace for "while (loopControl>0){"
return 0;
}//closing brace for "int main() {"

You can try this:
int number = 1874 //or whatever you need
auto str = std::to_string(number);
if (str.length() == 4) {
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
}
I suggest you to give a look at the algorithm header that contains a lot of useful methods that can help you while developing programs.

According to the cpp tutorials = is the assignment operator, not the comparison operator. Because of this your while loop will never terminate. You can simply initialize loopControl to true, and then set it to false when it's okay to exit:
int n, reversedNumber, remainder;
bool loopControl = true; //Initialize to true
char userFinalResponse;
reversedNumber = 0;
cout << "Input a 4 digit integer and press Return\n" << endl;
cin >> n;
while (loopControl) {
//if ((n>9999)||(n<1000))
if ((n>9999) || ((n<1000) && (n>0)))
{
cout << "Your number is too short or too long. Please try again.\n" << endl;
cin >> n;
loopControl = true; //need to keep on looping
}
else {
while (n > 0)
{
remainder = n % 10;
reversedNumber = reversedNumber * 10 + remainder;
n /= 10;
loopControl = false; //Ok to exit
}//closing brace for reversal loop
cout << "Your reversed number is " << reversedNumber << "\n" << endl;
}
}

Related

How can I throw a error if the user enters more than one integer

So this is my code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
long int iterFunc(int);
long int recurFunc(int);
int main() {
int n;
while(true){
try{
cout << "Enter: ";
if (!(cin >> n))
throw("Type Error");
if (n < 0)
throw n;
else
if (n == 0)
break;
cout << "Iterative: " << iterFunc(n) << endl;
cout << "Recursive: " << recurFunc(n) << endl;
}
catch(int n){
cout << "Error. Enter positive number." << endl;
}
catch(...){
cin.clear();
cin.ignore(100, '\n');
cout << "Error. Please enter a number" << endl;
}
}
cout << "Goodbye!";
return 0;
}
long int iterFunc(int n){
vector<long int> yVec = {1, 1, 1, 3, 5};
if (n <= 5)
return yVec[n - 1];
else
for(int i = 5;i < n; i++){
long int result = yVec[i - 1] + 3 * yVec[i- 5];
yVec.push_back(result);
}
return yVec.back();
}
long int recurFunc(int n){
switch (n) {
case 1:
case 2:
case 3:
return 1;
break;
case 4:
return 3;
break;
case 5:
return 5;
break;
default:
return recurFunc(n - 1) + 3 * recurFunc(n - 5);
break;
}
}`
The program shoud accept only one integer and return the y of the function using both iterative and recursive implemetations. Ex.: 30, 59, 433. How can I throw an error message if the user enters more then one integer, separated by space? Ex.: '3 45 32'.
I tried using if (cin.getline == ' ') throw("Error name") but the program still executes and return the y of the function for number in the input
Something like this works:
int main()
{
std::string str;
std::cout << "? : ";
std::getline(std::cin, str);
std::string::size_type pos(0);
int i = std::stoi(str, &pos);
if (pos != str.length())
return 1;
}
I found a part of my old code that might come in handy.
int val;
do
{
cin>>val;
if(!cin){ //you can add more conditions here
cin.clear();
cin.sync();
/* additional error handling */
}
else{
break; //input is correct - leaving loop
}
}while(true); //or here
Basically what !cin does is - it checks what type of value you actually want to write to, because it's needed anyway to figure out if data type is written to the correct type of our val. This means, that "30" or "433" etc. are integers (correct), "s" or "string" etc. are strings (or char*, correct me if I am wrong) (incorrect).
This also means, that "3 45 32" should be interpreted as string, which should result in another loop run.
Note: I didn't really test this code, so it might be completely wrong.
Edit: Okay now after some tests I realised this code needs some retweaking.
Firstly, "3 45 32" is not interpreted as string (now understandable). Instead, first number (before whitespace) is saved as an integer and all other numbers are stored in the buffer (next cin will be filled with it), which we can avoid using cin.clear() and cin.sync() once again.
The question is - is it okay for you to accept the first integer and ignore everything after the first whitespace? If not, you will have to save the input as string and extract whatever data you want from it.
I am leaving the original answer as is for simplicity of finding references in this edit.

How to reverse my input including the negative

This is my code that I have currently but it always outputs 0 I'm trying to get it to output the reverse of the input including the negative for example -123425 will be 524321-:
#include<iostream>
using namespace std;
int main() {
int number;
bool negative;
cout << "Enter an integer: ";
cin >> number;
while (number != 0) {
number % 10;
number /= 10;
}
if (number < 0) {
negative = true;
number = -number;
cout << number << "-";
}
else {
negative = false;
}
cout << number << endl;
return EXIT_SUCCESS;
}
You could convert the input to a std::string, then reverse its content with std::reverse.
#include <algorithm> // reverse
#include <cstdlib> // EXIT_SUCCESS
#include <iostream> // cin, cout, endl
#include <string> // string, to_string
using namespace std;
int main()
{
cout << "Enter an integer: ";
int number;
cin >> number;
auto str = to_string(number);
reverse(str.begin(), str.end());
cout << str << endl;
return EXIT_SUCCESS;
}
Reading to an int first - and not to a std::string - makes sure that we parse a valid integer from the input. Converting it to a std::string allow us to reverse it. This let us feed inputs like -042 and -0 to the program, and get 24- and 0 as a result, not 240- and 0-.
After the first loop
while (number != 0) {
number % 10;
number /= 10;
}
the variable number is equal to 0.
So the following if statement
if (number < 0) {
negative = true;
number = -number;
cout << number << "-";
}
else {
negative = false;
}
does not make sense.
Pay attention to that it can happen such a way that a reversed number can not fit in an object of the type int. So for the result number you should select a larger integer type.
Here is a demonstrative program that shows how the assignment can be done.
#include <iostream>
int main()
{
std::cout << "Enter an integer: ";
int n = 0;
std::cin >> n;
bool negative = n < 0;
const int Base = 10;
long long int result = 0;
do
{
int digit = n % Base;
if ( digit < 0 ) digit = -digit;
result = Base * result + digit;
} while ( n /= Base );
std::cout << result;
if ( negative ) std::cout << '-';
std::cout << '\n';
return 0;
}
Its output might look like
Enter an integer: 123456789
987654321-
I think trying to visualize the process of your program is a great way to see if your solution is doing what you expect it to. To this end, let's assume that our number is going to be 12345. The code says that while this is not equal to 0, we will do number % 10 and then number /= 10. So if we have 12345, then:
number % 10 --> 12345 % 10 --> 5 is not assigned to any value, so no change is made. This will be true during each iteration of the while loop, except for different values of number along the way.
number /= 10 --> 12345 /= 10 --> 1234
number /= 10 --> 1234 /= 10 --> 123
number /= 10 --> 123 /= 10 --> 12
number /= 10 --> 12 /= 10 --> 1
number /= 10 --> 1 /= 10 --> 0 (because of integer division)
Now that number == 0 is true, we proceed to the if/else block, and since number < 0 is false we will always proceed to the else block and then finish with the cout statement. Note that the while loop will require number == 0 be true to exit, so this program will always output 0.
To work around this, you will likely either need to create a separate number where you can store the final digits as you loop through, giving them the correct weight by multiplying them by powers of 10 (similar to what you are hoping to do), or cast your number to a string and print each index of the string in reverse using a loop.
Quite simple:
int reverse(int n){
int k = abs(n); //removes the negative signal
while(k > 0){
cout<<k % 10; //prints the last character of the number
k /= 10; //cuts off the last character of the number
}
if(n < 0) cout<<"-"; //prints the - in the end if the number is initially negative
cout<<endl;
}
int main(){
int n = -1030; //number you want to reverse
reverse(n);
}
If you don't want to use String or have to use int, here is the solution.
You want to check the negativity before you make changes to the number, otherwise the number would be 0 when it exit the while loop. Also, the modulus would be negative if your number is negative.
number % 10 only takes the modulus of the number, so you want to cout this instead of just leaving it there.
The last line you have cout << number << endl; will cout 0 since number has to be 0 to exit the while loop.
if(number < 0) {
number = -number;
negative = true;
}
while (number != 0) {
cout << number % 10;
number /= 10;
}
if (negative) {
cout << "-"<< endl;
}
EDIT: With a broader assumption of the input taking all int type values instead of the reversed integer being a valid int type. Here is a modified solution.
if(number < 0) {
negative = true;
}
while (number != 0) {
cout << abs(number % 10);
number /= 10;
}
if (negative) {
cout << "-"<< endl;
}
using namespace std;
int main()
{
int number,flag=1;
long long int revnum=0;
bool negative;
cout << "Enter an integer: ";
cin >> number;
if(number<0)
{ negative=true;
}
while (number > 0) {
revnum=revnum*10+number %10;
number /= 10;
}
if (negative)
{ revnum=(-revnum);
cout << revnum << '-'<<endl;
}
else
{ cout<<revnum<<endl;
}
return 0;
}
A few changes I did -
checking the number whether it's negative or positive
if negative converting it to positive
3.reversing the number with the help of a new variable revnum
4.and the printing it according to the requirement
To reverse the num-
revnum=revnum*10 + number%10
then num=num/10
like let's try to visualize
1.take a number for example like 342
2.for 1st step revnum=0 so revnum*10=0 and num%10=2 , so revnum will be 2
and the number now is num/10 so 34
4.next now rev = 2 the rev*10=20 and num%10=4 then rev*10 + num/10 =24
5.finally we get 243
Hope it helps :)
edit:-
just a small edit to solve the problem of the overflow of int , made revnum as long long int.

My loop won't loop

I have an assignment where we have to write code that finds a number that fits four parameters. My idea was to split up that number into its individual digits, then have an if statement that checks if the number fits the parameters. If it doesn't I wanted it to increase by one and loop until it finds the number. My loop only runs once however, and doesn't even return all four digits. Any direction on what I should do would be appreciated.
#include <iostream>
using namespace std;
int digit_breakdown(int& number);
int main()
{
int number = 1000; //This is the variable I will change to find the secret number
int last_dig, third_dig, sec_dig, first_dig; // These are variables that represent each of the four digits
int secret_number = 0; //This variable holds the secret number
do{
number++;
last_dig = number%10; //This series of code breaks up the number into digits
number /= 10;
third_dig = number%10;
number /= 10;
sec_dig = number%10;
number /= 10;
first_dig = number%10;
number /=10;
if((first_dig != sec_dig) && (first_dig != third_dig) && (first_dig != last_dig) && (sec_dig != third_dig) && (sec_dig != last$
number = secret_number;
}while((secret_number = 0));
cout << "You found the secret number! That number is " << secret_number;
cout << last_dig << endl;
cout << third_dig << endl;
cout << sec_dig << endl;
cout << first_dig << endl;
}
I have changed the logic and few statements as per the problematic statement given. Even though you will change the while loop condition as suggested, you will not get exact output.
So the changes are.
A) secret_number assigned at the beginning of the loop and holds the incremented number
B) do the modification operations on secret_number variable
C) use "break" once the condition is met.(because you got your secret number)
E) Because your condition is endless till you find a required number changed the loop to while(1) [This is optional you can set it to some upper limit]
F) Display the number itself.
Below is the code details.
#include <iostream>
using namespace std;
int digit_breakdown(int& number);
int main()
{
int number = 1000; //This is the variable I will change to find the secret number
int last_dig, third_dig, sec_dig, first_dig; // These are variables that represent each of the four digits
int secret_number = 0; //This variable holds the secret number
do{
secret_number = ++number;
last_dig = secret_number%10; //This series of code breaks up the number into digits
secret_number /= 10;
third_dig = secret_number%10;
secret_number /= 10;
sec_dig = secret_number%10;
secret_number /= 10;
first_dig = secret_number%10;
secret_number /=10;
if((first_dig != sec_dig) && (first_dig != third_dig) && (first_dig != last_dig) && (sec_dig != third_dig) && (sec_dig != last_dig)){
break;
}
}while(1); //To avoid endless loop you can set some upper_limit
cout << "You found the secret number! That number is " << number<<endl;
cout << last_dig << endl;
cout << third_dig << endl;
cout << sec_dig << endl;
cout << first_dig << endl;
return 0;
}
Output is as follows:
/WorkDir/checks/stackover> vi loop_digit.cpp
/WorkDir/checks/stackover> g++ -Wall -Wextra -O2 -o loop_digit loop_digit.cpp
/WorkDir/checks/stackover> ./loop_digit
You found the secret number! That number is 1022
2
2
0
1
Change
while((secret_number = 0));
to
while(secret_number == 0);
Single = is an assignment operator, for comparison you need ==
There's also a $ sign in one of the conditions of if-statement inside while loop that you might want to rectify.

How to take numerous inputs without assigning variable to each of them in C++?

I'm beginning with C++. The question is: to write a program to input 20 natural numbers and output the total number of odd numbers inputted using while loop.
Although the logic behind this is quite simple, i.e. to check whether the number is divisible by 2 or not. If no, then it is an odd number.
But, what bothers me is, do I have to specifically assign 20 variables for the user to input 20 numbers?
So, instead of writing cin>>a>>b>>c>>d>>.. 20 variables, can something be done to reduce all this calling of 20 variables, and in cases like accepting 50 numbers?
Q. Count total no of odd integer.
A.
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n,odd=0;
cout<<"Number of input's\n";
cin>>n;
while(n-->0)
{
int y;
cin>>y;
if(y &1)
{
odd+=1;
}
}
cout<<"Odd numbers are "<<odd;
return 0;
}
You can process the input number one by one.
int i = 0; // variable for loop control
int num_of_odds = 0; // variable for output
while (i < 20) {
int a;
cin >> a;
if (a % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
If you do really want to save all the input numbers, you can use an array.
int i = 0; // variable for loop control
int a[20]; // array to store all the numbers
int num_of_odds = 0; // variable for output
while (i < 20) {
cin >> a[i];
i++;
}
i = 0;
while (i < 20) {
if (a[i] % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
Actually, you can also combine the two while-loop just like the first example.
Take one input and then process it and then after take another intput and so on.
int n= 20; // number of input
int oddnum= 0; //number of odd number
int input;
for (int i = 0; i < n; i ++){
cin >> input;
if (input % 2 == 1) oddnum++;
}
cout << "Number of odd numbers :"<<oddnum << "\n";

Read digits from an int and counting them

Alright so I've been looking though Google and on forums for hours and can't seem to understand how to solve this problem.
I need to write a program that first determines if the number entered by the user is a base 5 number (in other words, a number that only has 0s, 1s, 2s, 3s, and 4s in it). Then, I have to count how many 0s, 1s, 2s, etc are in the number and display it to the user.
I've seen people saying I should convert int to a string and then using cin.get().
I noticed that I can't use cin.get() on a string, it needs to be a char.
I can only use a while loop for this assignment, no while... do loops.
Any help is appreciated!!
Here's what I have so far, obviously with all my mistakes in it:
//----------------------------------------------
// Assignment 3
// Question 1
// File name: q1.cpp
// Written by: Shawn Rousseau (ID: 7518455)
// For COMP 218 Section EC / Winter 2015
// Concordia University, Montreal, QC
//-----------------------------------------------
// The purpose of this program is to check if the
// number entered by the user is a base of 5
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
// Declaring variables
int number;
int zeros;
int ones;
int twos;
int threes;
int fours;
bool base5;
// Get data and calculate
cin >> number;
string numberString = to_string(number);
// Determine if the number is a base 5 number
while (cin.get(numberString) == 0 || cin.get(numberString) == 1 ||
cin.get(numberString) == 2 || cin.get(numberString) == 3 ||
cin.get(numberString) == 4)
base5 = true;
// Determine the number of each digits
zeros = 0;
ones = 0;
twos = 0;
threes = 0;
fours = 0;
return 0;
}
Several things you need to beware of:
One way to get a specific character from a std::string is by []. e.g.
std::string myString{"abcdefg"};
char myChar = myString[4]; // myChar == 'e'
cin.get(aString) is not trying to get data from aString. It continues to get data from stdin and store in aString. Once you have get the data and put into the string, you can simply manipulate the string itself.
a short piece of code that will count number of vowel in a string. If you can understand it, there should be no problem doing your work. (Haven't compiled, probably some typos)
std::string inputString;
std::cin >> inputString;
// you said you need a while loop.
// although it is easier to with for loop and iterator...
int i = 0;
int noOfVowels = 0;
while (i < inputString.length()) {
if (inputString[i] == 'a'
|| inputString[i] == 'e'
|| inputString[i] == 'i'
|| inputString[i] == 'o'
|| inputString[i] == 'u' ) {
++noOfVowels;
}
++i;
}
std::cout << "number of vowels : " << noOfVowels << std::endl;
Well you can try this approach. This will solve your needs I guess.
#include <iostream>
#include <string>
#include <sstream>
#include <conio.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int number=0;
int zeros=0;
int ones=0;
int twos=0;
int threes=0;
int fours=0;
bool valid=true;;
int counter = 0;
cout<<"Enter the number: ";
cin >> number;
stringstream out;
out << number; //int to string
string numberString = out.str();
cout<<"\n\nNumber after string conversion : "<<numberString;
cout<<"\nPrinting this just to show that the conversion was successful\n\n\n";
while (counter < numberString.length())
{
if (numberString[counter] == '0')
zeros++;
else if(numberString[counter] == '1')
ones++;
else if(numberString[counter] == '2')
twos++;
else if(numberString[counter] == '3')
threes++;
else if(numberString[counter] == '4')
fours++;
else
valid=false;
counter++;
}
if(valid==true)
{
cout<<"\nZeros : "<<zeros;
cout<<"\nOnes : "<<ones;
cout<<"\nTwos : "<<twos;
cout<<"\nThrees : "<<threes;
cout<<"\nFours : "<<fours;
}
else
cout<<"\n\nInvalid data...base of 5 rule violated";
_getch();
return 0;
}
If you don't want to use std::string then use characters, first loop over the input from the user until ENTER is pressed.
char ch = 0;
while ((ch = cin.get()) != '\n')
{
...
}
For each character read, check if it is a digit (std::isdigit) and if it is in the range 0..4, if not quit and give some message of not being base 5
have an array of ints to keep track of the frequency of the digits
int freq[5] = {0,0,0,0,0};
after you have checked that the character is valid subtract the ascii value from the digit and use that as index in the array, increment that:
freq[ch - '0']++;
e.g.
char ch;
int freq[5] = {0};
while ((ch = cin.get()) != '\n')
{
cout << ch;
freq[ch-'0']++;
}
for (int i = 0; i < sizeof(freq)/sizeof(freq[0]); ++i)
{
cout << static_cast<char>(48+i) << ":" << freq[i] << endl;
}
Here's a useful function that counts digits:
// D returns the number of times 'd' appears as a digit of n.
// May not work for n = INT_MIN.
int D(int n, int d) {
// Special case if we're counting zeros of 0.
if (n == 0 && d == 0) return 1;
if (n < 0) n = -n;
int r = 0;
while (n) {
if (n % 10 == d) r++;
n /= 10;
}
return r;
}
In your code you can use this naively to solve the problem without any further loops.
if (D(n, 5) + D(n, 6) + D(n, 7) + D(n, 8) + D(n, 9) != 0) {
cout << "the number doesn't consist only of the digits 0..4."
}
cout << "0s: " << D(n, 0) << "\n";
cout << "1s: " << D(n, 1) << "\n";
cout << "2s: " << D(n, 2) << "\n";
cout << "3s: " << D(n, 3) << "\n";
cout << "4s: " << D(n, 4) << "\n";
You could also (or should also) use loops here to reduce the redundancy.