SamD
SamD

Reputation: 11

comparing two integers using IF statement

hi i'm trying to solve a practice problem using if statement, finding the minimum between two integers. the instructions are

  1. Declare a variable where you want to store the minimum (say 'min')
  2. Declare two variables, ask a user to input two integers and save them into those variables
  3. assume that first integer is a minimum and save it to a 'min'variable declared in step 1
  4. write an if-statement that compares these two values and updates the variable from step1 (there won't be any 'else' if you do it correctly)

here is my code

#include <iostream>
using namespace std;

int main ()
{
int mins,a,b;
cout << "Enter two integers: ";
cin >> a >> b;
mins = a;
if (a<b)
    {
    cout << "The minimum of the two is " << mins;
    }
else

return 0;

the programs jumps to the end if the first integer is higher than the second, my problem is that it doesn't update the 'mins'. thanks in advance

Upvotes: 0

Views: 2505

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 311028

write an if-statement that compares these two values and updates the variable from step1 (there won't be any 'else' if you do it correctly)

I think what you need is the following.

#include <iostream>
using namespace std;

int main()
{
    int min;                   // Step 1
    int a, b;                  // Step 2

    cout << "Enter two integers: ";

    cin >> a >> b;

    min = a;                   // Step 3
    if ( b < a ) min = b;      // Step 4

    cout << "The minimum of the two is " << min << endl;

    return 0;
}

The program output might look like

Enter two integers: 3 2
The minimum of the two is 2

So among the presented code in the answers it is only my code that does it correctly.:)

Upvotes: 0

Ivan Sheihets
Ivan Sheihets

Reputation: 830

You can use shortland if/else:

#include <iostream>
#include <algorithm>

int main() {
    int a, b;
    std::cout << "Enter a and b: ";
    std::cin >> a >> b;
    int min = (a>b) ? b : a;
    std::cout << "The min element is: " << min;
}

Upvotes: 0

sameera lakshitha
sameera lakshitha

Reputation: 1971

this is wrong

mins = a;
if (a<b)
{
cout << "The minimum of the two is " << mins;
}
else

It should be.

if (a < b){
  mins = a;
}
else{
  mins = b;
}
cout << "The minimum of the two is " << mins;

Upvotes: 0

Jabberwocky
Jabberwocky

Reputation: 50822

Your program logic is wrong. You want this instead:

int main()
{
  int mins, a, b;
  cout << "Enter two integers: ";
  cin >> a >> b;

  if (a < b)
    mins = a;
  else
    mins = b;

  cout << "The minimum of the two is " << mins << endl;

  return 0;
}

Now this is still not entirely correct because the output is incorrect if a and b are equal.

The correction is left as an exercise to the reader.

Upvotes: 1

Related Questions