Example ..
string name;
getline (cin, name)
if (name != Anik)
cout << " Invalid /n";
But when I compile and run, the compiler says " Anik was not declared in this scope"....
Can anyone help me?
2 Replies
C++ if Statement
The syntax of the if
statement is:
if (condition) {
// body of if statement
}
The if
statement evaluates the condition
inside the parentheses ( )
.
condition
evaluates to true
, the code inside the body of if
is executed.condition
evaluates to false
, the code inside the body of if
is skipped.Example 1: C++ if Statement
// Program to print positive number entered by the user
// If the user enters a negative number, it is skipped
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;
// checks if the number is positive
if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";
return 0;
}
Output 1
Enter an integer: 5
You entered a positive number: 5
This statement is always executed.
When the user enters 5
, the condition number > 0
is evaluated to true
and the statement inside the body of if
is executed.
Output 2
Enter a number: -5
This statement is always executed.
When the user enters -5
, the condition number > 0
is evaluated to false
and the statement inside the body of if
is not executed.
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;
// checks if the number is positive
if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";
return 0;
}