Basically I would like to make a small little program that when u enter a number (say 145) it read the 3 digits and prints the largest one.
int a, b, c, max;
cout << "Enter a, b and c: ";
cin >> a >> b >> c;
max = a;
if (b>max)
max = b;
if (c>max)
max = c;
cout << "Max is " << max << "\n";
I was think of using something like this, but I have no idea how to get the computer to read each individual digit.
thanks!
Change int on the first line to char.
#include <iostream>
int main() {
char a, b, c, max;
std::cout << "Enter a, b and c: ";
std::cin >> a >> b >> c;
max = a;
if (b>max)
max = b;
if (c>max)
max = c;
std::cout << "Max is " << max << "\n";
}
This works, but is really not the right way to approach this problem IMO for C++.
This is slightly better, but with no kind of input validation:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string s;
std::cout << "Enter a number: ";
std::cin >> s;
char maxChar = *max_element(s.begin(), s.end());
std::cout << "Max is " << maxChar << "\n";
}
No need to resort to anything C++-specific when plain C will do it in less time than the conversions in keith.layne's answer if you already have the number in hand:
unsigned big_digit(unsigned value)
{
unsigned biggest = 0;
while (value) {
unsigned digit = value % 10;
if ( digit > biggest )
biggest = digit;
value /= 10;
}
return biggest;
}
Hope that wasn't homework.
You can make use of %(modulus) for such operations.
I think this LINK will do you justice
Basically I would like to make a small little program that when u enter a number (say 145) it read the 3 digits and prints the largest one.
int a, b, c, max;
cout << "Enter a, b and c: ";
cin >> a >> b >> c;
max = a;
if (b>max)
max = b;
if (c>max)
max = c;
cout << "Max is " << max << "\n";
I was think of using something like this, but I have no idea how to get the computer to read each individual digit. thanks!
While the answer using by keith.layne with strings works if you would like an answer that doesn't use strings you can just use integer division and modulus to get the same result:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int userInput, max;
cout << "Input a number and I'll give the biggest digit: ";
cin >> userInput;
cout << "The max digit of " << userInput << " is ";
max = userInput % 10; // sets one's digit to max
userInput /= 10; // reduces number by a digit
while(userInput > 0) // while number has remaining digits
{
if(userInput % 10 > max)// checks for a new max
{
max = userInput % 10;
}
userInput /= 10; // reduces number by a digit
}
cout << max << endl;
return 0;
}
spec :must be a4 digit number, either - or +, Modify this code to get your desired output. cheers!
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
int a, b, c, d, rem;
int no;
int max = 0;
int min = 0;
cin >> no;
if (no < 0)
no = abs(no);
a = no/1000;
rem = no%1000;
b = rem/100;
rem = rem%100;
c = rem/10;
rem = rem%10;
//cout<<a;
if(a > 0 && a <= 9)
{
if(a > max)
max = a;
else min = a;
if(b > max)
max = b;
else min = b;
if(c > max)
max = c;
else min = c;
if(rem > max)
max = rem;
else min = rem;
if(max > min)
cout << max << endl;
else
cout << min << endl;
}
else
cout<<"Invalid no"<<endl;
return 0;
}
I came up with this while trying to solve a codewars problem.
int i = 0;
int num_ = num; //we will need a dummy, num is the original
while(num_ != 0){ //count the number of digits
num_ /= 10;
i++; //yayyy
}
int *ptr = new int[i]; //dynamic array to store individual numbers
int pos = 0;
while(1){ //copy digits to dynamic array
if(num > 10){
num_ = num%10;
ptr[pos] = num_;
num /= 10;
pos++;
}
else{
num_ = num%10;
ptr[pos] = num_;
break;
} //array now contains our digits
}
Related
This is the simple program to convert any base(2-9) to decimal.
It is completely compiled, but the output is not what I expected.
Please let me know what's the problem.
#include <iostream>
#include <cmath>
using namespace std;
int size_int(int num) //the number of num
{
int n = 0;
while(num > 0)
{
num = num/10;
n = n+1;
}
return n;
}
int convert(int num, int b) //conver num base b to base 10
{
int sum = 0;
int n = size_int(num);
while(n>0)
{
sum += (num/pow(10,n-1)) * (pow(b,n-1));
n -= 1;
}
return sum;
}
int main()
{
int num;
cout << "Enter a number to convert: ";
cin >> num;
int b;
cout << "Enter the base of number: ";
cin >> b;
int sum;
sum = convert(num, b);
cout << "Its decimal value is: "<< sum << endl;
return 0;
}
Enter a number to convert: 10110
Enter the base of number: 2
Its decimal value is: 12632
This is the result when I executed.
You calculated your current digit seems not right num/pow(10,n-1).
This is my suggestion:
#include <iostream>
#include <cmath>
using namespace std;
int size_int(int num) //the number of num
{
int n = 0;
while (num > 0)
{
num = num / 10;
n = n + 1;
}
return n;
}
int convert(int num, int b) //conver num base b to base 10
{
int sum = 0;
int n = size_int(num);
int counter = 0;
while (num > 0) {
int temp = num % 10;
num = num / 10;
sum += temp * (pow(b, counter));
counter++;
}
return sum;
}
int main()
{
int num;
cout << "Enter a number to convert: ";
cin >> num;
int b;
cout << "Enter the base of number: ";
cin >> b;
int sum;
sum = convert(num, b);
cout << "Its decimal value is: " << sum << endl;
return 0;
}
Can someone help me in this?
This is a c++ program that I need to find prime numbers of fibonacci series.
the question says that after you enter the n ( the number of fibonacci series ) the program has to extract the prime numbers from it, and then, if the sum of those prime numbers is an odd number, it has to show 'A' and if it's even, it should show 'D'. The problem is I know how to find both fibonacci series and prime numbers, but I can't merge them.
And I need to keep the code as simple as possible
Can someone help me in this?
This one is for fibonacci series:
#include <iostream>
#include <conio.h>
using namespace std;
int main(){
int n, a = 1, b = 1, c;
cin >> n;
cout << a << endl;
cout << b << endl;
int i = 2;
while (i < n)
{
c = a + b;
cout << c << endl;
a = b;
b = c;
i++;
}
getch();
}
And this one is for prime numbers :
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
int a, b = 1, r = 1, c = 0, x, m;
cout << "please enter number :";
cin >> a;
while (b <= a) {
m = a;
x = b;
while (x != 0) {
r = m % x;
m = x;
x = r;
}
if (m == 1){
c++;
b++;
}
cout << c;
getch();
}
I have to put them together so i can extract the prime numbers in the fibonacci, but I dont know how.
And, I need it to show the prime numbers but my code shows how many numbers are prime
One solution could be to make a function to find the n'th fibonacci number, another function to test if a number is prime, and then loop over the fibonacci number to find the primes
#include <iostream>
int fib(int n) { /* code */ }
bool is_prime(int n) { /* code */ }
int sum_of_prime_in_fib(int lim)
{
int sum = 0;
// loop over the fibonacci number to sum the primes
for (int i = 1; i <= lim; ++i) {
int f = fib(i);
if (is_prime(f))
sum += f;
}
return sum;
}
int main()
{
int n;
std::cout << "please enter number :";
std::cin >> n; //remember to check for errors, which I wont do
std::cout << "the sum of primes is: " << sum_of_prime_in_fib(n) << "\n";
}
I have left the implementation of the two functions as an exercise
Since you did not include conio.h content, I will pose a solution from bare-bone.
This question revolves around several stages.
get all fibonacci sequence in a list
use fibonacci sequence to find if any prime numbers exist (put them in a list)
calculate the sum of the prime numbers from that list
if the sum is even, print "A" otherwise print "D".
The code can be broken down to several functions to make it easier and more intuitive.
#include <iostream>
#include <conio.h>
#include <vector>
using namespace std;
vector<int> generate_fibonacci(int n){
int a = 1, b = 1, c;
//cout << a << endl;
//cout << b << endl;
int i = 2;
vector<int> f;
f.push_back(a);
f.push_back(b);//assuming that the a,b are part of the fibonacci
while (i < n)
{
c = a + b;
f.push_back(c);
a = b;
b = c;
i++;
}
return f;
}
bool is_prime(int n)
{
// Corner case
if (n <= 1)
return false;
// Check from 2 to n-1
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
vector<int> find_prime_from_f(vector<int> v){
vector<int> fp;
for(int i: v){
if(is_prime(i))
{
fp.push_back(i);
}
}
return fp;
}
int main(){
cout << "please enter the number of fibonacci" << endl;
int n;
cin >> n;
vector<int> fibonacciNumber = generate_fibonacci(n);
vector<int> fibonacciPrime = find_prime_from_f(fibonacciNumber);
int sum;
for(int i: fibonacciPrime)
{
sum += i;
}
if(sum %2 != 0) cout << "A" <<endl; //if it is odd
else cout << "D" <<endl; //if it is even
}
You can of course tailor some of the details of these functions, including adding some bound checking for negative numbers, and optimize the algorithm by using array, doing the calculation and checking on the fly, or simplify the code a little. However, this should serve as a starting point for your further implementation.
So i have a task that i'm supposed to find the max and minimum number by rearranging given number.
The hard part is that, in this task especially i'm not allowed to use arrays,vectors and string into array way.
Example:
Input: 598
Output: 589, 985
I done that, but only using the array, that sort every number by desc and asc.
Here's my code:
#include<iostream>
#include<algorithm>
#include <vector>
using namespace std;
int main() {
int num;
int dec;
bool flag = false;
int curNum;
vector<int> numbers;
cout << "Enter three digit number: ";
cin >> num;
while (num > 0) {
curNum= num % 10;
num /= 10;
flag = false;
for (int i = 0; i < chisla.size(); ++i) {
if (numbers[i] > curNum) {
flag = true;
numbers.insert(numbers.begin() + i, curNum);
break;
}
}
if (!flag) numbers.push_back(curNum);
}
// Сортиране на масива, като се подрежда в низходящ ред.
sort(numbers.begin(), numbers.end(), greater<int>());
dec = 1;
int min_val = 0;
for (auto &it : numbers) {
min_val += it * dec;
dec *= 10;
}
sort(numbers.begin(), numbers.end());
dec = 1;
int max_val = 0;
for (auto &it : numbers) {
max_val += it * dec;
dec *= 10;
}
cout << "е: \n"
<< (max_val - min_val) << endl;
return 0;
}
So the main question is there any way to that without arrays, sorting and etc. (Don't ask why i can't use them, just the current task don't allow that.)
Thanks in advance.
Wish u all good.
I did it in that way.
int a,b,c,temp,x=123;
a = x/100;
b = (x/10)%10;
c = x%10;
if(b>a){
temp=a;
a=b;
b=temp;
}
if(c>b){
temp=b;
b=c;
c=temp;
}
if(b>a){
temp=a;
a=b;
b=temp;
}
cout << "smallest: " << a+(b*10)+(c*100) << "\n";
cout << "biggest: " << (a*100)+(b*10)+c << "\n";
If there's some other way, please let me know!
Trying to get some C++ basics but have a problem. I need to get an average value of temperature array values. Posting code in here. I know that I've done something wrong, because I'm getting the wrong answers. Can you please tell me what's wrong?
#include <iostream>
using namespace std;
int main()
{
int d = 0, i;
double avg = 0, sum = 0, Temperature[100];
// -----------------------------------------
cin >> d;
for (i = 1; i <= d; i++)
{
cin >> Temperature[i];
}
for (i = 1; i <= d; i++)
{
cout << Temperature[i] << endl; // was Temperatura[i] ?
}
for (i = 1; i <= d; i++);
{
sum += Temperature[i];
}
avg= sum / d;
cout << "Average: " << avg << " Sum: " << sum << endl;
system("pause");
return 0;
}
The problem is a result of silly mistake:-
for (i = 1; i <= d; i++); << semicolon
Remove semicolon from end of for loop.
Maybe it because the input number d is larger than 100
#include <iostream>
using namespace std;
int main()
{
int d = 0, i;
double avg = 0, sum = 0, *Temperature=0;
// -----------------------------------------
cin >> d;
Temperature=new double[d]; //<== Use new to allocate array
for (i = 0; i < d; i++) //<== Normaly array start at 0
{
cin >> Temperature[i];
}
for (i = 0; i < d; i++)
{
cout << Temperatura[i] <<endl;
}
for (i = 0; i < d; i++);
{
sum += Temperature[i];
}
average = sum / d;
cout << "Average: " << avg << " Sum: " << sum << endl;
if(Temperature!=0) //<== Free memory
{
delete []Temperature;
}
system("pause");
return 0;
}
You don't need to initialize int d; if you are taking d as input before it use for first time.
Once d taken as input. Now declare the int Temperature[d]; so that if the total number of observation exceed 100 it should work.
Now iterate the array, for taking input and calculating sum. Note that - Array indices starts from zero instead of one. Goes to d-1.
for() loop doesn't have; at the end.
Steps:
You declare the Temperatures array, the number of temperatures (you used 'd', but you don't need to initialize it with 0, just read it) and a variable which keeps the sum of Temperatures (ex.: double sum = 0)
In a for loop (for i = 1; i <= d; i++ || for i = 0; i < d; i++) you read the Temperatures and increase the sum with each of the elemens (sum += Temperatures[i] || sum = sum + Temperatures[i]
Output: cout << sum / n; Formula : average = (elem1 + elem2 + ... + elem n) / n
I am currently doing a task in a book which asks me to calculate the mathematical constant e using the while loop. I managed that fairly easily, however I am having troubles calculating e^x, whereas the user inputs x and the degree of accuracy. The code I used for computing e is:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int degreeOfAccuracy, x = 1;
long double e = 1;
cout << "Enter degree of accuracy of mathimatical constant e: ";
cin >> degreeOfAccuracy;
while (x <= degreeOfAccuracy)
{
int conter = x;
int intial = x;
long double number = x;
int counter = 1;
while (conter > 1)
{
number = number*(intial-counter);
counter++;
conter--;
}
e += (1/number);
x++;
}
cout << endl << "The mathematical constantr e is: "
<< setprecision(degreeOfAccuracy) << fixed << e << endl;
system("pause");
return 0;
}
However, when I tried e^x the following code returned a completely wrong value:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int degreeOfAccuracy, x = 1, exponent;
long double e = 1;
cout << "Enter degree of accuracy of mathimatical constant e: ";
cin >> degreeOfAccuracy;
cout << "Enter the number of which you wish to raise to e: ";
cin >> exponent;
int temp = exponent;
while (x <= degreeOfAccuracy)
{
exponent = temp;
int conter = x;
int intial = x;
long double number = x;
int counter = 1;
while (conter > 1)
{
number = number*(intial-counter);
counter++;
conter--;
}
int counterr = 1;
while (counterr < x)
{
exponent *= exponent;
counterr++;
}
e += (exponent/number);
x++;
}
cout << endl << "The mathematical constantr e is: " << setprecision(degreeOfAccuracy) << fixed << e << endl;
system("pause");
return 0;
}
Any ideas where the calculations went wrong?
This line:
exponent *= exponent;
is wrong. It should be:
exponent *= temp;