Introduction
In this lab, we will learn how to determine if a user-entered number is positive or negative using C++ programming language. We will achieve this by using the concept of if-else
blocks.
In this lab, we will learn how to determine if a user-entered number is positive or negative using C++ programming language. We will achieve this by using the concept of if-else
blocks.
In the newly created main.cpp
file,
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to this C++ program! \n\n";
return 0;
}
This will import the necessary libraries and print the welcome message.
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to this C++ program! \n\n";
int num;
cout << "Enter a non-zero numeric value: ";
cin >> num;
return 0;
}
Here, we prompt the user to input a non-zero numeric value using the cin
statement and store the value in num
.
if-else
Block to Determine if the Number is Positive or Negative#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to this C++ program! \n\n";
int num;
cout << "Enter a non-zero numeric value: ";
cin >> num;
if (num > 0) {
cout << num << " is a positive number." << endl;
} else {
cout << num << " is a negative number." << endl;
}
return 0;
}
In this step, we create an if-else
block to compare num
with 0
. If num
is greater than 0
, it is a positive number; else, it is a negative number.
Open the terminal in Ubuntu system, navigate to the directory where the main.cpp
file is located, and use the following command to compile and run the program:
$ g++ main.cpp -o main && ./main
In this lab, we learned how to determine if a user-entered number is positive or negative using C++ programming language. We achieved this by using the concept of if-else
blocks.