본문 바로가기

Programming/C++ Basic

[Basic C++] 07 - Flow Control (Loop, if-else, and Jump) - 1

In this post, I am going to talk about flow control statements in C++. There are mainly three flow control statements in C++; for/while loops / if-else statements / jump statements. Each one of them is very useful and you will use them almost everywhere.

 

Flow control statements are extremely useful when some lines of code need to be repeated certain times or execute a specific segment of code under certain circumstances. 


Table of Contents

1. for loop and while loop

and sleep_for


1. for loop and while loop

These statements are born for iteration work. There are three crucial parts in loop statements; when to start, when to stop, and how many times.

 

1.1) while loop and do-whole loop

A while loop repeats given statements until a given condition becomes false. When a compiler meets a while loop, first it checks whether the condition is true. If the condition is true, the statements are iterated until the condition becomes false. If the condition is false in the beginning, the while loop is ignored. The syntax of a while loop is,

 

// Syntax of a while loop
while (condition) 

{

 statements

}

The below example uses a while loop printing out the value of a from 1 and increases the value of a by 1 each iteration. The condition is a < 10, thus the loop ends if a becomes 10. We already know what "boolalpha" is. It is a function turns 'boolalpha flag' on which it returns a string type boolean result.

 

Code example 1

#include <iostream>

int main()
{
	int a = 1;

	while (a < 10)
	{
		std::cout << "Iteration number :" << a 
			<< " and condition is " << std::boolalpha << (a < 10) << std::endl;
		a++;
	}

	std::cin.get();
}

Figure 1 Result of code example 1

 

There is another while loop called a do-while loop. The original while loop checks the condition first and executes the given statements, while a do-while loop executes the given statements and checks the condition. Therefore the do-while loop is executed at least once even if the condition is false at the beginning. The syntax of do-while loop is below,

 

// do - while loop
do
{
	statements
} while (condition) ;

 

Code examples 2

#include <iostream>

int main()
{
	int a = 11;

// While Loop
	while (a < 10)
	{
		std::cout << "While loop Iteration number :" << a 
			<< " and condition is " << std::boolalpha << (a < 10) << std::endl;
		a++;
	}

// Do-While Loop
	do 
	{
		std::cout << "do-while loop Iteration number :" << a
			<< " and condition is " << std::boolalpha << (a < 10) << std::endl;
		a++;
	} while (a < 10);

	std::cin.get();
}

Figure 2 Result of code example 2

 

See what has happened in code example 2. The first loop (while loop) was never executed because the condition was false (a is 11) at the beginning. On the other hand, the second loop (do-while loop) was executed once.

 

1.2) for loop

There are two ways to write for loops in C++. The syntax is following,

// for loop 1
for (data_type variable_name initial_value; condition; next_iteration)
{
	statements;
}

// for loop 2
for (data_type variable_name : range)
{
	statements;
}

For loop 1 needs three parts. 

 

(1) data_type / variable_name / initial_value

: This part is for the initialization of iteration. The first value of the iteration is determined.

 

(2) condition

: The loop is continued until the condition becomes false.

 

(3) next_interation

: This part is executed at the end of every iteration.

 

For loop 2 needs two parts.

 

(1) data_type / variable_name

: This part says the data type of elements it iterates within the given range.

 

(2) range

: It defines a range to iterate.

 

Code example 3

#include <iostream>

int main()
{
	
	char str[4] = "asd";

	// for loop 1
	for (int i = 0; i < 10; i++)
	{
		std::cout << i;
	}
	std::cout << '\n';

	// for loop 2
	for (char s : str)
	{
		std::cout << s;
	}

	std::cin.get();
}

Figure 3 Result of code example 3

The initial value of the for loop 1 was 0 ( int i = 0 ) and the increment was 1. It continued until 'i' became 9. On the other hand, the range of iteration was an array itself at the for loop 2. The 'char array' 'str' had 4 bytes but it seemed it only stored three characters "asd". The point is that 'char array' always implicitly has a value '0' at the end.

 

1.3) (std::this_thread::) Sleep_for

The above statements in while loops are trivial and the execution is less than a millisecond. However, what about you want your loop to be executed for some period of time, like countdown?. 'sleep_for' function is perfect for this job. sleep_for function stopes the flow of code during the span of time specified by 'rel_time'. Below is the syntax of sleep_for function.

#include <thread> // for > std::this_thread::sleep_for
#include <chrono>// for  > corono::seconds
std::this_sthread::sleep_for (const chrono::duration<Rep,Period>& rel_time);

Be aware that this function only stops the execution of a given thread for a certain amount of time (rel_time) but it is not 100% correct. It technically takes more than a given sleep time because of overhead (low-level process to execute code actually by CPU). Multi-threading operations should also be taken care of carefully if used.

 

code example 4

#include <iostream>
#include <ctime>
#include <thread>
#include <chrono>

int main()
{
	struct tm stm;
	// Time structue containing a calander date and time.

	while (true)
	{
	
		// time contains current time
		time_t t = time(NULL);
	
		// localtime_s converts a time_t time value to a tm structure, and corrects for the local time zone
		// localtime_s (pointer to the time structure, pointer to the stored time)
		localtime_s(&stm, &t);
		std::cout << stm.tm_sec <<" sec " <<"\n";
		std::this_thread::sleep_for(std::chrono::milliseconds(1000));
		
	}
}

Figure 4 Result of code example 4

The result is showing the second of the current time approximately every 1000 milliseconds.