Site icon Teaching Newbies since 2014

If-while statements in C++

If and while statements are pretty powerful as you can control when statement/statements of code are executed.
Syntax:
if(condition fulfilled){
do this;
} else{
do that
}
Example:
#include <iostream>
using namespace std;

int main() 
{

    // Set a equal to true here.
    bool a =  false;

    if (a) {
      cout << "Hooray! You made it into the if statement!" << "\n";
    } else{
        cout << "OOOOOPPSSS" << "\n";
}
}
While
While statements allow you to execute a block of code till/while a condition is true
Syntax:
while (condition){
do this;
}
Example:
Print out numbers 0-5 while i is less than or equal to <= 5
#include <iostream>
using namespace std;
int main(){
  int i = 0;
    while (i < 5) {
      cout << i << "\n";
      i++;
    }
}
Exit mobile version