nide
nide

Reputation: 3

Recognizing if one value is larger or smaller than the second value (C++)

My Comp Sci teacher gave us 2 basic C++ tasks to do for homework. I've managed to do the first one, but this second one is confusing me. I'm supposed to write code that recognizes if one value is larger than the other, and print out a message saying if one value is larger or not larger than the other. The code:

#include<iostream>
using namespace std;
int main() {
    int num1, num2;
    cout << "Unesi broj" << endl;
    cin >> num1, num2;
    if (num1 > num2) {
        cout << "First number is bigger than the second" << endl; }
    else if (num1 < num2); {
            cout << "First number isn't bigger than the second" << endl;
    }
    return 0;   
}

If anyone could help me out it'd be amazing, since this is a graded task.

Upvotes: 0

Views: 1412

Answers (2)

Gary Strivin&#39;
Gary Strivin&#39;

Reputation: 908

Problems:

  1. std::cin >> num1, num2; only affects the first argument. The comma operator doesn't make std::cin apply num2 (More info about how comma operator works here).
  2. else if (num1 < num2); does not guard the block cout << "First number isn't bigger than the second" << endl; because of the semicolon after the condition so cout << "First number isn't bigger than the second" << endl; will always execute.
  3. Even if the else if guarded the block your solution is wrong when num1 == num2: It does not print anything.

Solutions:

  1. Replace the comma (,) with >>.
  2. Delete the semicolon after else if (num1 < num2).
  3. Replace else if (num1 < num2) with else if (num1 <= num2) or, even better, with else.

Additional information:

  1. using namespace std; is considered a bad practice (More info here).

Full code:

#include <iostream>

int main() {
    int num1, num2;
    std::cout << "Enter numbers:" << std::endl;
    std::cin >> num1 >> num2;
    if (num1 > num2)
        std::cout << "First number is bigger than the second." << std::endl;
    else
        std::cout << "First number isn't bigger than the second" << std::endl;
    return 0;   
}

Upvotes: 1

singhAmandeep007
singhAmandeep007

Reputation: 499

do:

cin >> num1 >> num2 ;

instead of :

cin >> num1,num2;

Upvotes: 1

Related Questions