This question already has answers here:
How do I extract the digits of a number in C++?
(6 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Input a 3-digit integer.
Print the largest digit in the integer (Tip: use % 10 to get the rightmost digit, and / 10 to remove the rightmost digit).
Input: 173
Expected Output: 7
We were given this activity 2 days old and still couldn't solve this mystery. Here's my own code which doesn't match the given expected output above:
#include<iostream>
using namespace std;
int main() {
int num, result;
cin >> num;
if(num > 0) {
result = num % 10;
num / 10;
cout << result;
}
return 0;
}
You separate only the last digit, but need to check all - just add a loop. Also num / 10 does nothing.
maxdigit = 0;
while (num > 0) {
maxdigit = max(maxdigit, num % 10);
num /= 10;
}
cout << maxdigit;
Different way to solve the problem. Take the input as a string. You can handle much larger numbers and the string is already decomposed into digits. You barely have to think. Just work through the string character-by-character, make sure the character is a digit, and keep track of the biggest digit seen so far.
#include<iostream>
#include <cctype> // needed for isdigit
//using namespace std; Not recommended. Causes problems
int main()
{
std::string num;
char max = 0;
std::cin >> num; // read number as a string.
for (char ch: num)
{ //iterate string character by character
if (!isdigit(static_cast<unsigned char>(ch)))
{ // if we didn't get a digit, the user screwed up (or is a jerk)
// Let's not assume malice and let them know they've made a mistake.
std::cerr << "Must input a valid number";
return -1;
}
if (ch > max)
{ // this is the biggest character seen so far.
max = ch; // update biggest
}
}
std::cout << max; // print biggest
return 0;
}
The answer of MBo is the best and should be accepted.
You are obviously not allowed to use C++ algorithms yet. And, maybe you are learing now about interger and modulo divisions.
If you would be allowed to use more advanced C++, you would probably write something like:
#include <iostream>
#include <algorithm>
int main()
{
if (std::string number{}; (std::cin >> number) and std::all_of(number.begin(), number.end(), ::isdigit))
std::cout << *max_element(number.begin(), number.end()) << '\n';
}
Below is the working example without using loops and without using std::max. Note this(without loop) is just one among many possible ways of doing it.
#include <iostream>
int findDigit(int passed_num, int current_num)
{
int lastDigit;
if (passed_num == 0) {
return current_num;
}
// find the last didit
lastDigit = passed_num % 10;
if(lastDigit > current_num)
{
current_num = lastDigit;
}
//call findDigit() repeatedly
current_num = findDigit(passed_num / 10, current_num);
std::cout<<lastDigit<<" ";
return current_num;
}
int main()
{
std::cout << "Enter a number: ";
int input_num, greatest_num;
std::cin>>input_num;
greatest_num = findDigit(input_num, 0);
std::cout<<"greatest is: "<<greatest_num<<std::endl;
std::cout<<"Enter another number: ";
std::cin>>input_num;
greatest_num = findDigit(input_num, 0);
std::cout<<"greatest is: "<<greatest_num<<std::endl;
return 0;
}
The output of the above is as follows:
Enter a number: 24344357
2 4 3 4 4 3 5 7 greatest is: 7
Enter another number: 2353639
2 3 5 3 6 3 9 greatest is: 9
#include <iostream>
using namespace std;
int main() {
int a = 11;
int b = 5;
int c = 23;
int max = (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c) ;
cout << max << endl;
}//using Ternary Operator
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 11 months ago.
Hello I am trying to count the number of digits in a given double. I am encountering an infinite loop doing so. I tried to isolate each while statement and it works fine but when I combine them I am having an infinite loop on a the second while condition. here's the code
#include <iostream>
using namespace std;
int main()
{
//Counting digits of a number
double N, M, b;
int i, j, a;
cout << "This program will count how many digits the given whole number has.\n\n";
cout << "Please enter the Number: "; // N = 123.567 Digits should be = 6
cin >> N;
a = (int)N;
M = N - a;
b = M - int(M);
j = 0;
if (a == 0 && b == 0)
cout << "You have entered number 0.";
else
{
i = 0;
j = 0;
while (a > 0) //for the integer (whole number) part of the number
{
a /= 10;
i++;
}
while (b != 0) //for the fractional part of the number
{
j++;
M *= 10;
b = M - int(M);
}
cout << "Display i: " << i << endl; // i = number of whole number digits
cout << "Display j: " << j << endl; // j = number of fractional digits
}
system("pause > 0");
}
As a double stores fraction parts to a more significant extent, you cannot count digits in a double in this way.
Instead,
Accept the number as a string.
Convert it to double using stod()
Step2 is to make sure the user has entered the number as if it's other than the number it'll give an exception.
Count digits in the string.
Here is what it will look like
#include<iostream>
#include<string.h>
using namespace std;
int main(){
string str = "";
cin>>str;
int counter =0;
try{
double d = stod(str);
for(int i=0;i<str.length();i++){
if(str.at(i) >= '0' && str.at(i) <= '9')
counter++;
}
cout<<counter;
}
catch(...){
cout<<"Please enter only numbers";
}
return 0;
}
I have used catch which is general, meaning it will catch all exceptions. You can use specific exception too.
Using a floating point type at any point in this analysis is not the correct thing to do. That's because (like an integral type) they can only store a subset of the real number set.
A good approach here would be to read the input as a string, check that it is a plausible number (e.g. does it contain only one decimal separator)? Write something clever to trim any zeros after the decimal separator and leading zeros before the number, allow for a negative sign, then count the digits.
Needle in the haystack. I'm a beginner in programming and we only learned a thing or two so far, barely reached arrays yet.
Input: 1 4325121
Output: 2
Input two values in one line. The first one shall accept any integer from 0-9 and the other one shall take a random positive integer.
Using a while loop, count how many of the first integer (0-9) is present in the digits of the second inputted integer and print the result.
No arrays to be used here, only while loops and else-if conditions with basic coding knowledge and without the use of advanced coding.
As you said, you need to keep it as simple as possible. Then this can be a solution:
#include <iostream>
int main()
{
int first { };
int second { };
std::cin >> first >> second;
int quo { second };
int rem { };
int count { };
while ( quo > 0 )
{
rem = quo % 10;
quo /= 10;
if ( first == rem )
{
++count;
}
}
std::cout << "Result: " << count << '\n';
}
Using while loop
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 4325121;
int count = 0;
while(b > 0)
{
int m = b % 10;
if(m == a)
{
count++;
}
b /= 10;
}
cout << count;
return 0;
}
Nice little problem. But actually, to keep it as simple as possible no calculations are needed at all. I simplified my example, and it just keeps working on the input text, which is 100% sufficient to solve the problem:
#include <iostream>
#include <string>
using namespace std;
int main() {
char digit;
std::string number;
cout << "Input: ";
cin >> digit >> number;
int count = 0;
for (char const character : number)
if (character == digit)
count++;
cout << "Result: " << count << endl;
return 0;
}
Given the question, this code solves the problem.
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.
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;
}
}
This question already has answers here:
Elegant ways to count the frequency of words in a file
(8 answers)
Need a code that counts the same digit in a number
(2 answers)
Closed 5 years ago.
Was trying out a question that I saw online, the questions requires the user to input the number of time the random number will be generated and to count how many digit 1, digit 2, digit 3, are there int he generated number.
For example
Enter number of time to loop : 4
2241 1204 5532 8593
There are 8 digits 1, digit 2 and digit 3.
code:
int main()
{
int input;
int ranNum;
cout << "Enter the number of time to loop" << endl;
cin >> input;
srand(time(NULL));
int i = 0;
if (input < 0 || input > 50)
{
cout << "Invalid entry";
}
else
{
while(i++ < userInput)
{
ranNum = (rand() % 10000);
cout << ranNum<< " ";
}
}
return 0;
}
The questions stated that using a switch case will be easier to get it done. However, I am not too sure how can a switch case worked for this. Or, is there any other method that I can use?
I've completed the code for the first 2 part, which is requiring user to input number as well as generating the random number based on user input
To count the number of occurrences of 1, 2 and 3 in a single integer value it would be easiest IMO to convert the integer into a string and then count the digits you are interested in:
int countDigits(int number, std::string digitsOfInterest = "123") {
int ret = 0;
std::string numberAsString = std::to_string(number); // convert it to string
for (const char& digit : numberAsString) { // loop over every character
if (digitsOfInterest.find(digit) != std::string::npos) {
ret++;
}
}
return ret;
}
Simply pass a randomly generated number into the function and add up the results. As you can see, by changing digitsOfInterest to another string, you can alter the digits you want to count.
PS.: Since I'm assuming that you have access to C++11 I would recommend to change your number generation to <random>.
Here is a non C++11 solution which works the same way the above one does:
int countDigits(int number, std::string digitsOfInterest = "123") {
int ret = 0;
std::ostringstream oss;
oss << number;
std::string numberAsString = oss.str(); // convert it to string
for (size_t i = 0; i < numberAsString.size(); ++i) { // loop over every character
if (digitsOfInterest.find(numberAsString[i]) != std::string::npos) {
ret++;
}
}
return ret;
}
Here is an example:
std::cout << "This number: '1243' contains " << countDigits(1243) << " times a digit of 1,2 or 3\n";
Result: This number: '1243' contains 3 times a digit of 1,2 or 3
I divided it to functions so it will be easier to understand.
I used switch case because that what you asked, but there are other ways as well.
#include<time.h>
#include <iostream>
#include <stdlib.h>
// This function is the UI, i.e. asking the user how many numbers to generate
int HowManyNumbers()
{
int input;
std::cout << "Enter the number of time to loop" << std::endl;
std::cin >> input;
return input;
}
// This function counts 1,2,3 for individual number
int Count123InNum(int num)
{
int count = 0;
while(num)
{
int lastDig = num % 10;
// count only if lastDigit in number is 1,2 or 3
switch(lastDig)
{
case 1:
case 2:
case 3:
++count;
break;
default:
break;
}
num /= 10;
}
return count;
}
// This function receives number of random numbers to generate,
// and its output is a print of the numbers and the joint occurences of 1,2 and 3
void Get123FromRandomNums(int nRandNumbers)
{
srand(time(NULL));
std::cout << "In the numbers: ";
int count = 0;
while(nRandNumbers--)
{
int num = rand() % 10000;
std::cout << num << " ";
count += Count123InNum(num);
}
std::cout << "There are " << count << " digits 1, digit 2, digit 3." << std::endl;
}
int main()
{
// Get number of random numbers (i.e. iterations)
int nRandNumbers = HowManyNumbers();
// check validity
if (nRandNumbers < 0 || nRandNumbers > 50)
{
std::cout << "Invalid entry" << std::endl;
}
else
{
//if valid, count and print 1,2,3 occurences
Get123FromRandomNums(nRandNumbers);
}
return 0;
}