I've searched several times and can't find specifically what I'm looking for:
We're about 1-month into the course) and I have no prior programming experience.
I need to make a program that will determine which digit out of an integer designated by the user is largest.
#include "stdafx.h"
#include <iostream>
usingnamespace std;
int _tmain(int argc, _TCHAR* argv[])
{ /*Number is entered. Number is divided by 10, If the remainder (r) is less than or equal to 9 then r = max.
If not then n % 10 will loop until and compare against max until condition is met.*/
int n, r, max;
cout << "Enter number: ";
cin >> n;
max = 0;
r / 10;
while (r <= 9)
r = n % 10;
cout << "The result is: " << r << endl;
return 0;
}
Any help would be extremely appreciated! Thank you!
while (r <= 9) if you enter a number above 9 your program isn't going to do anything, and if you enter a number below 9 then what's the point? It must be one digit, therefore it is the highest digit.
you'll need to divide by 10 until the division resolves to 0, you'll also need to take n mod 10 before each division to get the end digit, then compare it with the last highest number.
1 2 3 4 5 6 7 8 9 10 11 12
int max = 0;
int num;
cin >> num;
while ( num > 0 )
{
int remainder = num % 10;
if ( remainder > max )
max = remainder;
num /= 10;
}
This probably isn't the easiest way to do it, but you could store the number in a string, take it apart piece by piece, and atoi each character after storing it in a character. Like so...
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <string>
using std::string;
#include <limits>
int main(int argc, char* argv[])
{
string number;
cout << "Enter a number: ";
cin >> number;
int size = number.size();
int num = 0, max = 0;
char x[1];
for(int i = 0;i < size;i++)
{
x[0] = number[i];
num = atoi(x);
if(num > max)
{
max = num;
}
}
cout << "The largest digit in that integer is: " << max << endl;
cin.get();
cout << "Press <ENTER> to continue...";
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return 0;
}
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int number, max =0, rem;
cout << "Enter a number: ";
cin >> number;
while ( number ! = 0) // This while block finds out the max digit.
{
rem = number % 10;
if(rem>max)
{
max = rem;
}
number = number /10;
}
cout << "The largest digit in that integer is: " << max << endl;
cin.get();
cout << "Press <ENTER> to continue...";
return 0;
}
I have not used argc, argv parameters, you can use them if you want. The logic of finding out max digit is in the while block. You can handle way of input/output as you want. Just use the entire while block for finding out the max digit.