+ 3
What are else or if statements?
I am having a hard time understanding the concept of if and else statements. Can someone please elaborate?
3 Answers
+ 4
It's simple really. Think about closing a computer:
if (button_pressed == shutdown)
enter_shutdown();
else if (button_pressed == hibernate)
enter_hibernate();
else
cout << "Button not recognized" << endl;
+ 2
lets say you have a variable called number:
int number = 6;
with an if statement you can check for example if the variable number is equale to 8:
if (number == 8){
}
if you want to check if something is equale to something you use == do not confuse with =.
so if you want to give a variable a value you use = and if you want to check if something is equale to something you use ==.
you see after the if statement there are two curly brackets
if (number == 8){
cout << "number is 8" << endl;
}
everything thats between those two curly brackets will be executed if the if statement is true. so in this example, if the var number is 8 the console will print out "number is 8".
so now else statments
so now we have a if statement that executes code if it is true. but is there a way to execute something if the is statement is not true? yes there is: the else statement:
if (number == 8){
cout << "number is 8" << endl;
{
else
{
cout << "number is NOT 8" << endl;
}
i hope this was helpfull
0
they are common in Java or c++