C++ Practice Assignment #10 – How to use pointers C++

 

Apart from using analogies and diagrams to understand pointers like I have done with my other article on understanding pointers, the best way to get a grip of how they work is to actually delve into the code and play around with them.

In this practice assignment, I break down the code of creating pointers and printing out the pointer address variables and values. Pointers can be tricky to understand, but by having a strong baseline understanding of how they work can reduce confusion.

 

#include <iostream>

using namespace std;
 
int main()
{
  int* variable; // Pointer declared called variable
  int value = 10; // value = 10
 
  cout << value << "\n"; // This is going to print out the value of 10
 
  cout << &value << "\n"; // Memory address of variable value
 
  variable = &value; // This also is going to print out the memory address of the variable value
 
  cout << variable << "\n"; // Address of what variable has been pointed to
 
  cout << *variable; // Value of what has been pointed to
}

 

Infinite loops C++ Implementation

If you are undertaking any embedded software development, it’s crucial that you understand how to write infinite loops. Implementing infinite loops in c++ is actually a piece of cake and I’ll show you three examples that do the job. Keep in mind that infinite loops repeat indefinitely with no terminating condition, so use them wisely.


// While Loop Infinite Loop
while (1)
{

}


// For Lopp Infinite Loop
for (;;)
{
}

&amp;lt;/pre&amp;gt;
// Do While Infinite Loop
do
{

}
while (true) 

Orthogonality programming

Orthogonality in programming can be defined in simple terms when changes in one thing do not affect any of the others. To visualise this definition, Module A should not make changes to things in Module B and vice versa.

If you design a system where Module A affects Module B; which affects module C and so on, things quickly start going out of control and the system becomes a nightmare to understand and manage.

In a real-life example describing Orthogonality in programming from the book The Self Taught Programmer, you can change the interface without affecting the database, and swap databases without changing the interface.

Diagram from JavaWorld.com

Fizz buzz question and solution in C++ – C++ Practice Assignment 9

The Fizz buzz question is popular among programmers going for job interviews as it’s designed to weed out people that cannot program. From this article on “Why Can’t Programmers..Program, an alarming majority of comp sci graduates and senior programmers take more than 10-15 minutes to write a solution.

The assignment of the Fizz buzz question is to write a program that prints the numbers from 1 to 100. But for multiples of three, print “Fizz” instead of the number and for the multiples of five print “Buzz”. The key to solving this problem is using the Modulo operation. To solve this problem you simply need to iterate from 1 to 100 using a for loop and check if each number is divisible by 3, 5 or both.

Here is the C++ solution


//-------------------------------------------------------------------------------
// FizzBuzz C++ Solution
// Write a program that prints the numbers from 1 to 100
// But for multiples of three, print "Fizz" instead of the number and for the multiples of five print "Buzz".
//-------------------------------------------------------------------------------

#include &lt;iostream&gt;

using namespace std;

int main()
{
// Print numbers from 1 to 100
for (int i = 1; i &lt; 101; i++)
{
// Check to see if's both divisable by 3 and 5
if (i % 3 == 0 &amp;&amp; i % 5 == 0)
{
cout &lt;&lt; "FizzBuzz" &lt;&lt; endl;
}
// Check to see if it's divisable by 3
else if (i % 3 == 0)
{
cout &lt;&lt; "Fizz" &lt;&lt; endl;
}
// Check to see if it's divisable by 5
else if (i % 5 == 0)
{
cout &lt;&lt; "Buzz" &lt;&lt; endl;
}
else
// Print out the rest of the numbers from 1 to 100
cout &lt;&lt; i &lt;&lt; endl;
}
}

String Array C++ – Implementation with an example

If you haven’t learned about arrays or strings before, then read up on string array c++ first before proceeding to read this.

Two-dimensional arrays can be used to create string array c++. The way they work is the following

  1. Create a 2D character array
  2. The left array determines the number of strings
  3. The right array specifies the maximum length of each string, which also includes the null terminator

For example, the following declares an array of 40 strings, each having a maximum length of 69 characters, plus the null terminator.

char str_array[40][70]

You can access each individual string by specifying only the left index. Using the gets() function, we can call the 2nd string in the str_array;

gets(str_array[1]);

To access an individual character within the second string which will display the fourth character of the 2nd string, you can use the statement:

cout << str_array[2][3];

The example code below shows string array c++ being applied by creating a simple student database. The two-dimensional array of numbers holds pairs of names and student numbers. To find a number, you enter the name which the student number displayed.

// A Student database applying array of strings

#include &lt;iostream&gt;
#include &lt;cstdio&gt;

using namespace std;

int main()
{
int i;
char str[70]; // Read string entered in

// Create a list of 40 strings with a maximum of 69 characters
char numbers[40][70] =
{
"Sahil", "s3432952",
"David", "s5656564",
"Aaron", "s4962768",
"Cletus", "s223564",
"Mohamaad", "s3489112",
};

// Main Menu
cout &lt;&lt; "Enter name:";

cin &gt;&gt; str;

// Search and match for the correct name
for (i = 0; i &lt; 40; i = i + 2)
if (!strcmp(str, numbers[i]))
{
// Display student number
cout &lt;&lt; "Number is " &lt;&lt; numbers[i + 1] &lt;&lt; "\n";
break;
}

if (i == 40)
cout &lt;&lt; "Not found\n";

return 0;
}

Operators in C++

Logical operators in C++ can instruct the program to perform mathematical or logical operations. With the help of logical operators, we can use them to operate variables we have defined.

Arithmetic Operators

What is the % operator?

This is called the modulus which is represented by a percentage symbol. It stands for modulus division which finds the remainder of a calculated division in a program. Here’s an example.


#include <iostream>
#include <math.h>

using namespace std;

int main()
{
// Result variable of the modulus division
int x;

x = 11 % 3;

// Display the remainder value from the modulus division
cout << x;

return 0;
}

Result of the modulus division of 11 divided by 3

 

What is increment and decrement?

The operators ++ and — are the increment and decrement operators. The most simple way to explain them is they are shortcuts for addition and subtraction in programming.

For example

x = x + 1;

is actually the same as x++

and x = x – 1;

is the same as –x;

Does it matter where I put the ++ and — when I am implementing increment or decrement?

++x is known as a pre increment

x++ is known as a post increment

In this simple example, there is no difference where you place the ++ or — in your code. But if you are dealing with a large expression, it can become a important difference. Remember to always test your code when you are implementing increment or decrement operations as the complier cannot pick up logical errors.


#include <iostream>
#include <math.h>

using namespace std;

int main()
{
// Variables for pre and post increment example
int x;
int y;

x = 5;
y = 7;

// Pre increment value of x
++x;

// Post increment value y
y++;

cout << "x value pre increment value" << "\n" << x << "\n";
cout << "y value post increment value" << "\n" << y << "\n";

return 0;
}

In this sample program of pre and post increment, the values of x and y have been incremented by one with the x value starting with 5 and y value starting with 7. With the results shown below, it is showing the end result operation of pre and post increment.

 

Logical operators

In C++, logical operators deal with true and false statements acting together. In logic, this can be AND, OR, NOT. The symbols used for these operations are in the following table.


#include <iostream>

using namespace std;

int main()
{
// Values used for logical operators
bool value1;
bool value2;

// Set values to true and false
value1 = true;
value2 = false;

// AND Operation
if (value1 && value2)
// This will not be displayed because this logical operator
// Will not work
cout << "This won't work\n";

// NOT AND Operation
if(!(value1 && value2))
cout << "!(value1 && value2) works\n";

// OR Operation
if (value1 || value2)
cout << "value1 || value2 is true\n";

return 0;
}

Let’s look at what is going on with the code. This may be tricky to understand at first but let’s go through line by line at what’s happening. Don’t worry about the “if” keyword just yet. They will be taught in the chapter “program control statements”.

Line 11 and 12: We are just declaring two boolean values to be used for the logical operations. We cannot use int or double because they deal with numbers.

Line 16 and 17: The two boolean values are now being initialised with a value. Value1 is being set to true and Value2 is set to false.

Lines 19 – 23: The first logical operation being used is an AND operation. As you can see in the simulation, cout << “This won’t work\n”; is not being displayed in the simulation. The reason why it is not showing is because value1 && value 2 are not both true or false. One is different from the other, thus line 23 will not be outputted in the simulation.

AND Operation diagram

Lines 25 – 27: This is very similar to lines 19 – 23 but if you look closely, there is a “!” before the expression (value1 && value2). “!” represents NOT, so since value1 and value2 are the not the same, it will display in the simulation “!(value1 && value2) works”.

Lines 29 – 31: OR operation being implemented here. This is the opposite of the AND operation. If value1 and value2 have different values so it will display “value1 || value2 is true” in the simulation.

OR Operation diagram

 

Relational operators

These operators deal with logic operations such as less than, equal or greater than. These are not as difficult as logical operators and can easily be mastered.

In the code example, the value of i is 5 and value of j is set to 6. In the code, I am programming the computer to question the following

– Is i less than j

-Is i greater than l

-Is i not equal to j

-Is i equal to j

-Is i greater than or equal to j

-Is i less than or equal to j


#include <iostream>

using namespace std;

int main()
{
// Integer variables
int i, j;

// Set variables
i = 5;
j = 6;

// Relational operators
if (i < j)
cout << "i is less than j\n";
if(i > j)
cout << "i is greater than j\n";
if(i != j)
cout << "i is not equal to j\n";
if(i == j)
cout << "i equal to j\n";
if (i >= j)
cout << "This won't work\n";
if(i <= j)
cout << "i is less than or equal to j\n";

return 0;
}

The lines which are true would be displayed in the output simulation.