Programming 101 – Logic Structures

Hey guys!

Last time on Programming 101 we took a look at the very basic structure of a C++ program. Preprocessor directives, libraries, and classes were also briefly discussed. I recommend reading that post first, right over here, as it will help provide more context to today’s discussion.

Alright then! I’ll try to cover as much as possible in this post – starting with conditional branches. Programming is all about logic and it really teaches you to think. In C++, one way of expressing your logic is with the help of conditional branches. The two commonly used conditional branch types are if/else statements and switches. Today we’ll be looking exclusively at if/else statements.

 

Programming is a lot like playing with dominoes – structure is everything.

Programming is a lot like playing with dominoes – structure is everything.

 

The basic structure of an if statement is:

if (condition)

{

statement(s);

}

 

If the condition in the bracket is false, the if statement will not resolve and will continue on to the next line of code. I’ve given a more concrete example below:

if (number7 != 7)

{

number7 = 7;

}

 

In this example, if the integer variable number7 is not equal to 7 the program proceeds to make it equal to 7. We can add different conditional statements when comparing two variables including ==, !=, >, <, >=, <=, and the remainder operation %. Composite conditions can be created through the use of || (or) and && (and). Through the use of else statements, we can also extend the initial structure of an if piece of code.

 

Choices, choices, choices.

Choices, choices, choices.

 

The basic structure of an if/else statement is:

if (condition)

{

// first logic block

}

else

{

// second logic block

}

 

Similarly, the syntax for a larger if/else statement is as follows:

if (condition)

{

// first logic block

}

else if (condition)

{

// second logic block

}

else if (condition)

{

// fourth logic block

}

else

{

// third logic block

}

 

A cool, but impossible, visual representation of a queue.

A cool, but impossible, visual representation of a queue.

 

Try and see if you can work out what the value of the integer variable bigsum will be at the end of the if/else statement below:

int num1 = 4, num2 = 7, bigsum = 0;

if (num1 < 3 && num2 == 7)

{

bigsum = num1 + num2;

}

else if (num1 == 4 || num2 == 6)

{

bigsum = num2 – num1;

}

else

{

bigsum = 10;

}

 

Did you get a value of 3 for bigsum? I hope you guys enjoyed this post. Let me know which topics I should cover next time in the comments below and on our social media channels. Good luck Code Warriors!

Until next time,

 

– MAZ

Related Posts