Mark As Completed Discussion

Operators are the building blocks of any programming language. In C++, we have two main types of operators: arithmetic and comparison. Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc., while comparison operators are used to compare values and return boolean results.

Just as in financial calculations where various arithmetic operations are used to calculate profit, loss, interest, etc., in C++, arithmetic operators play the same role but are applicable to a broader range of applications. An example of such an application would be the development of a financial system for tracking transactions.

Let's take a look at both types of operators individually:

  1. Arithmetic Operators: These include + (addition), - (subtraction), * (multiplication), / (Division), % (Modulus), ++ (Increment), -- (Decrement). Here's an example utilizing arithmetic operators:

  2. Comparison Operators: These include == (Equal to), != (Not equal to), < (Less than), > (Greater than), <= (Less than or equal to), >= (Greater than or equal to). A comparison operator in action would be a simple if-else decision-making statement:

In the same way we apply comparison in the financial world, for example, comparing the efficiency of two investment portfolios, in coding we also apply conditional comparisons to make decisions or control the flow.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Try this exercise. Is this statement true or false?

In C++, the != operator checks if two values are equal.

Press true if you believe the statement is correct, or false otherwise.

In C++, control flow is crucial to the way a program runs. It dictates how and in which sequence the code statements will be executed. The if-else statement forms the basis of control flow in C++, allowing the program to make decisions. It's quite similar to making decisions in finance: where to invest? Tesla or Apple? Exactly in the same way, if-else allows your code to choose between different execution paths based on certain conditions.

An if-else statement in C++ begins with an if keyword, followed by a boolean condition, followed by a block of code that is executed if the condition is true. If the condition is false, the control is passed to the else block (if there is one), and its code is executed.

Here's an example. Let's say you are a senior engineer building an AI to decide when to invest in stocks. You can use an if-else statement to decide based on the stock price:

TEXT/X-C++SRC
1int stockPriceTesla = 650;  
2int stockPriceApple = 150; 
3
4// If-else Decision making
5if (stockPriceTesla > stockPriceApple) {
6  cout<<"Invest in Apple!";
7} else {
8  cout<<"Invest in Tesla!";
9}

This bit of logic can help you decide where to invest depending on the condition specified in the if statement. If the condition is true (Tesla's price is greater than Apple's), you invest in Apple. Otherwise, you invest in Tesla (controlled by the else statement).

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Try this exercise. Fill in the missing part by typing it in.

Let's say you are a senior engineer building an AI to decide when to invest in stocks. You can use an if-else statement to decide based on the stock price:

`int stockPriceTesla = 650;
int stockPriceApple = 150;

if (stockPriceTesla ___ stockPriceApple) { cout<<"Invest in Apple!"; } else { cout<<"Invest in Tesla!"; }`.

Fill in the blank with the correct operator.

Write the missing line below.

Just like the if-else statement, the switch-case statement is another tool for controlling the flow of a program.

However, unlike an if-else statement, a switch-case statement can evaluate multiple conditions at once. This can be particularly useful in scenarios where you’re dealing with a handful of possibilities and you want to do something different depending on that possibility. For example, let's imagine you are building a system to grade the A.I predictions for financial stock predictions. The stock prediction can be graded as 'A', 'B', 'C', 'D', 'F'.

We can use a switch-case statement like so:

TEXT/X-C++SRC
1char grade = 'B'; 
2switch (grade) { 
3  case 'A' : 
4        cout << "Excellent!"; 
5        break; 
6  case 'B' : 
7  case 'C' : 
8        cout << "Well done"; 
9        break; 
10  case 'D' : 
11        cout << "You passed"; 
12        break; 
13  case 'F' : 
14        cout << "Better try again"; 
15        break; 
16  default : 
17        cout << "Invalid grade"; 
18} 
19cout << "\nYour grade is : " << grade; 

In the above code, the switch statement evaluates the variable 'grade'. Each 'case' checks whether the 'grade' matches the character it is testing for. If it does, it runs the code inside the case statement and breaks out of the switch statement. The 'default' case runs if no other case matched.

In summary, while if-else statements are effective for simpler conditions, switch-case statements offer greater readability and structure for complex, multi-condition scenarios.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Build your intuition. Is this statement true or false?

In a switch-case statement in C++, if the condition for a case is met, the program will continue to check the remaining cases even after the match is found.

Press true if you believe the statement is correct, or false otherwise.

Looping: for Loop

In C++, for loops are traditionally used when the number of iterations is known before entering the loop. Structure of a for loop is as follows:

TEXT/X-C++SRC
1for (initialization; condition; increment/decrement) {
2    statement(s);
3}
  • Initialization sets a counter to an initial value.
  • Condition is tested; if it's true, the code inside the loop is executed. If it's false, the code inside the loop does not execute and the control moves to the next statement in the program after the loop.
  • After the code inside the loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
  • The condition is now re-evaluated. If it is true, the loop executes and the process repeats itself (flow of control jumps back up to increment/decrement, and so on).
  • If the condition is false, the loop does not execute and control skips to the next line immediately following the loop.

In the context of our financial AI predictions, let's say we have five stock portfolios to analyze. Here's how we can use a for loop:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5
6  for (int portfolio = 1; portfolio <=5; portfolio++) {
7    cout << "Checks on stock portfolio number "<< portfolio << " completed."<< endl;
8  }
9
10  return 0;
11}

Every time the loop iterates, the value of portfolio increases by 1 until it eventually becomes 6, at which point the loop ends because our condition portfolio <=5 is no longer met.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Try this exercise. Is this statement true or false?

In the structure of a 'for' loop in C++, 'initialization' sets a counter to an initial value, 'condition' is tested at the end of each iteration before the next round starts in the loop, and 'increment/decrement' allows you to update any loop control variables.

Press true if you believe the statement is correct, or false otherwise.

Looping: while Loop

In C++, while loops are used when number of iterations is not known before entering the loop. Sometimes, this makes them a more flexible tool for programmers to use in certain situations. For example, we might utilize a while loop when analyzing real-time data in the AI financial prediction sphere, where we don't necessarily know for how many cycles the data needs to be processed.

The structure of a while loop is as follows:

TEXT/X-C++SRC
1while (condition) {
2    statement(s);
3}
  • Condition is tested; if it's true, the code inside the loop is executed. If it's false, the code inside the loop does not execute and the flow of control moves to the next statement in the program after the loop.
  • After the code inside the loop executes, the flow of control jumps back up to the condition. Hence, the condition is now re-evaluated.
  • If it is still true, the loop executes again and this process repeats.
  • If the condition is false, the loop does not execute and control skips to the next line immediately following the loop.

Continuing the context of our financial AI predictions, let's say we have a variable number of stock portfolios to analyze. Here's how we can use a while loop:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  int portfolio = 1;
6  while (portfolio <= 5) {
7    cout << "Analysis on stock portfolio number " << portfolio << " completed.\n";
8    portfolio++;
9  }
10  return 0;
11}

The while loop checks each portfolio until there are no portfolios left to check, thus being responsive to the real-time nature of financial data.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Are you sure you're getting this? Is this statement true or false?

"While" loop in C++ is used only when number of iterations is known before entering the loop.

Press true if you believe the statement is correct, or false otherwise.

Looping: do-while Loop

The do-while loops function similar to while loops but with a subtle difference - the do-while loop is execute at least once irrespective of the condition, and then the condition is checked. It is mostly used when the number of iterations is not known, but we need to execute the loop at least once.

The loop begins with the do keyword, followed by a block of code to be executed, and then the while condition is evaluated. If it is true, the loop is repeated, else it stops.

TEXT/X-C++SRC
1int portfolio = 1;
2do {
3  cout << "Analysis on stock portfolio number " << portfolio << " completed.\n";
4  portfolio++;
5} while (portfolio <= 5);

This above code ensures that we at least analyze one portfolio. Then, if we have more than one portfolio, the loop will keep analyzing the portfolios until there are none left.

In the realm of AI finance, this is a common need - we often have tasks that we need to execute at least once, and then continue executing if a certain condition is met. In our example, we ensured we completed at least one portfolio analysis, and if there were more portfolios to analyze, we continued doing so.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Try this exercise. Is this statement true or false?

The do-while loop in C++ will not execute if the condition is evaluated as false the very first time.

Press true if you believe the statement is correct, or false otherwise.

Putting It All Together

We have now successfully learned all about operators, conditions, and loops in C++. Let's take this opportunity to revisit all we've learned while also diving into a hypothetical financial situation.

Suppose you have an investment with a fixed return rate and you wish to see how much your investment grows after six years -- we can simulate this using a for loop. With if-else statements, we can indicate whether the investment has doubled or not.

Furthermore, we can simulate trading activities, such as executing three trades with a do-while loop which guarantees at least one execution of the loop. This is beneficial in situations such as when the market opens and we want to execute at least one trade.

Lastly, for decision-making processes we can use switch-case statements. For instance, when our automated trading system has various options like 'buying stocks', 'selling stocks', or 'waiting'. Based on the available data, our system can use a case structure to decide on the action to take.

Understanding and effectively using these fundamental constructs of C++ such as operators, conditions, and loops is the key to creating efficient and flexible programs. Especially in the context of real-world use cases like finance or AI, these tools become incredibly valuable.

In this tutorial we've built a sound foundation. Our next steps should be diving deeper into C++, exploring more complex data structures and advanced features of the language.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Try this exercise. Is this statement true or false?

A do-while loop in C++ will not execute if the condition is false from the start.

Press true if you believe the statement is correct, or false otherwise.

Generating complete for this lesson!