Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show the smallest digit from three digits in C++

I want to make a program in which user enter the three digits separated by the space and i want to show the smallest digit.

See my code:

#include<iostream>
using namespace std;
int main( )
{
   int a,b,c;
   cout<<" enter three numbers separated by space... "<<endl;               
   cin>>a>>b>>c;
   int result=1;

   while(a && b && c){
           result++;
           a--; b--; c--;
           }
   cout<<" minimum number is "<<result<<endl;

    system("pause");
    return 0;   
}  

Sample input:

3 7 1

Sample output:

2

It doesn't show the smallest digit. What's the problem in my code and how can I solve my problem?


1 Answers

The result should be initialized by zero

int result = 0;

nevertheless the approach is wrong because the user can enter negative values.

The program could be written the following way

#include <iostream>
#include <algorithm>

int main( )
{
    std::cout << "Enter three numbers separated by spaces: ";

    int a, b, c;
    std::cin >> a >> b >> c;

    std::cout << "The minimum number is " << std::min( { a, b, c } ) << std::endl;

    return 0;   
}
like image 112
Vlad from Moscow Avatar answered Jan 31 '26 11:01

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!