Easy
tutorial for C / C++ Control statement 1 (if, if else statements)
- Normally in a computer program, the statements are
executed in the order in which they were written (down from the top of the
code).
- However, depending on the situation, you may want to run
only when the conditions are right or sometimes you want to do it with certain
rules.
- For this purpose, control statements (such as an if
statement, a for statement, a while statement, etc.) are provided.
- The advantage of using control statements is that they can be efficient and
simple to code.
- First, let's summarize the control statements that are executed under certain
conditions.
if statement :
- The 'if' statement is a statement that says to execute a
specific statement if the condition is satisfied. The structure of 'if' statement is as follows:
if ('condition') {'execute statement'}
- If this 'condition' is satisfied, it executes the execution statement and does
not execute if the condition is not satisfied.
- The 'condition' statement usually uses a conditional expression that evaluates
the result as true or false. Depending on the situation, an expression that gives a result of 1 or 0 is
used. In this case, 1 is true and 0 is false.
Example Code
#include
<iostream>
using
namespace std;
int
main() {
int a ;
a = 3 ;
if(a > 1){
cout<<" a > 1 is true !!! "<<endl ;
}
return 0;
}
results:
a
> 1 is true !!!
- Declares an integer variable a and assigns 3 to a. In the
if statement, the conditional statement has a condition of a > 1.
- 3 is stored in a and thus a is larger than 3, so the result is true. The
following statement is executed: "a> 1 is true !!!"
if else statement :
- The structure of 'if else' statement is as follows:
if ('condition') {'execute statement 1'}
else{'execute statement 2'}
-
If the condition is satisfied, 'execution statement 1' is
executed. If condition is not satisfied, 'execution statement 2' is executed.
Example Code
#include
<iostream>
using
namespace std;
int
main() {
int a, b;
a = 3 ;
b = 1 ;
if( a > 2 ){
cout<<" a > 2 is true !!! "<<endl ;
} else {
cout<<" a > 2 is false !!!
"<<endl ;
}
if( b > 2 ){
cout<<" b > 2 is true !!! "<<endl ;
} else {
cout<<" b > 2 is false
!!! "<<endl ;
}
return 0;
}
results:
a
> 2 is true !!!
b
> 2 is false !!!
- 'a' has a value of 3. In the first 'if' statement, 'a'
is greater than 2, so the "a> 2 is true !!!" is printed.
- 1 was
assigned to 'b'. Because the condition of the second 'if' statement is not
satisfied, the "b> 2 is false !!!" is printed.
No comments:
Post a Comment