Statements

Statements

Statements are parts of the program that are executed. Expression ending with a semicolon ; is a statement. Example of expression statements executed in sequence:

#include <iostream>
int main(){
	int x; // 1st statement
	x = 1; // 2nd statement
	std::cout << "The value of x is: " << x << std::endl; // 3rd statement
}

Brace enclosed statements { statement1; statement2; statement3; }are called block statements.

Conditional statements - if else

Conditional statement if (condition) { statement; } checks the condition and executes statements accordingly.

#include <iostream>
int main(){
	int x = 10;
	if (x == 10){
		std::cout << "x is equal to 10.";
	}
}

If the condition is not met the else block of statements can be executed.

#include <iostream>
int main(){
	int x = 10;
	if (x == 10){
		std::cout << "x is equal to 10.";
	}
	else{
		std::cout << "x is not equal to 10.";
	}
}

Iteration statements

Iteration statements execute code over and over again inside a loop. We explain the for and the while loops.

The for loop

The for loop can be used to execute statements a given number of times. To execute a statement or a block of statements 5 times we can use:

#include <iostream>
int main(){
	for (int i = 0; i < 5; i++)
	{
		std::cout << i << std::endl; // this gets executed 5 times
	}
} 

To execute a (block of) statement(s) 10 times we can use:

#include <iostream>
int main(){
	for (int i = 0; i < 10; i++)
	{
		std::cout << i << std::endl; // this gets executed 10 times
	}
}

The simplified for loop signature is:

for (initialize counter; condition; increase or decrease counter;){
	statements;
}

The code will get executed as long as the condition is true.

The while loop

The while loop executes code while the condition is true. To execute a code inside a while loop we use:

#include <iostream>
int main(){
	int i = 0;
	while (i < 10)
	{
		std::cout << i << std::endl;
		i++; // increase the counter
	}
} 

The simplified while loop signature is:

while (condition){
	statements;
}