Counting and Looping a List
Counting and Looping a List
Counting and Looping a List
Introduction
We have already learned various ways to create an array. Here is an example:
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
The list has a number of items. We saw that you can specify the number of items when creating the array. Here is an example:
double[] numbers = new double[5] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
As seen in our introductions, there are various ways you can access the elements of an array. As opposed to accessing one item at a time, a loop allows you to access the items as a group. Each item can still be accessed by its index. You can first declare a variable that would hold the index for an item. Here is an example:
int counter = 0;
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
One of the operators you can use to access the items of an array is the while keyword. As one way to use that keyword, to access an item in a loop, use the name of the array but pass the index in the square brackets of the variable. Here is an example:
#include <iostream>
using namespace std;
int main()
{
short counter = 0;
float numbers[] = { 12.44, 525.38, 6.28, 2448.32, 632.04 };
while (counter <= 4)
{
cout << "Number: " << numbers[counter] << endl;
counter++;
}
cout << "==================\n";
}
This would produce:
Number: 12.44 Number: 525.38 Number: 6.28 Number: 2448.32 Number: 632.04 ================== Press any key to continue . . .
In the same way, to change the value of an item, access it by its index and assign the desired value to it. Here is an example:
#include <iostream>
using namespace std;
int main()
{
int counter = 0;
short numbers[] = { 203, 9580, 81, 7495, 40 };
cout << "====================================" << endl;
cout << "Original List" << endl;
while (counter <= 4)
{
cout << "Number: " << numbers[counter] << endl;
counter++;
}
cout << "-------------------------------------" << endl;
cout << "Updating the numbers of the list..." << endl;
numbers[3] = 9999;
numbers[1] = 555;
cout << "-------------------------------------" << endl;
counter = 0;
cout << "Updated Numbers" << endl;
while (counter <= 4)
{
cout << "Number: " << numbers[counter] << endl;
counter++;
};
cout << "====================================" << endl;
}
This would produce:
==================================== Original List Number: 203 Number: 9580 Number: 81 Number: 7495 Number: 40 ------------------------------------- Updating the numbers of the list... ------------------------------------- Updated Numbers Number: 203 Number: 555 Number: 81 Number: 9999 Number: 40 ==================================== Press any key to continue . . .
Practical Learning: Introducing Loops in Lists
#include <iostream>
using namespace std;
int main()
{
int estimatedLife = 0;
double machineCost = 0.00;
double salvageValue = 0.00;
cout << "Enter the values for the machine depreciation" << endl;
try
{
cout << "Machine Cost: " << endl;
machineCost = double.Parse(ReadLine()!);
}
catch(Exception ex) when (ex is FormatException fex)
{
cout << "You might have typed a valid value that represents the " +
"cost of the machine. Since you did not provide a " +
"valid value, we will set the machine cost to 0.00." << endl;
cout << "The machine error is: " + fex.Message << endl;
}
try
{
cout << "Salvage Value: ";
salvageValue = double.Parse(ReadLine()!);
}
catch(Exception ex) when (ex is FormatException fex)
{
cout << "You must have provided that value you estimate the machine " +
"will have at the end of the cycle (or the end of its " +
"life). Since you didn't enter a valid value, we will " +
"consider the estimated end value to 0.00." << endl;
}
try
{
cout << "Estimated Life (in Years): ";
estimatedLife = int.Parse(ReadLine()!);
}
catch (Exception ex) when (ex is FormatException fex)
{
cout << "You didn't enter a valid number of years for the life of " +
"the machine. Instead, we will consider that this machine " +
"has no life, or a life of 0 years." << endl;
}
catch (Exception ex) when (ex is DivideByZeroException dze)
{
cout << "The value for the length of the estimated life of the machine must always be greater than 0." << endl;
cout << "The machine error is: " + dze.Message);
}
double depreciatiableAmount = machineCost - salvageValue;
double depreciationRate = 100 / estimatedLife;
double yearlyDepreciation = depreciatiableAmount / estimatedLife;
Clear();
cout << "====================================" << endl;
cout << "Depreciation - Straight-Line Method" << endl;
cout << "------------------------------------" << endl;
cout << "Machine Cost: " << machineCost << endl;
cout << "Salvage Value: " << salvageValue << endl;
cout << "Estimate Life: {0} Years", estimatedLife << endl;
cout << "Depreciation Rate: {0}%", depreciationRate << endl;
cout << "------------------------------------" << endl;
cout << "Depreciable Amount: " << depreciatiableAmount << endl;
cout << "Yearly Depreciation: " << yearlyDepreciation << endl;
cout << "====================================";
int i = 1;
int year = 1;
double[] bookValues = new double[estimatedLife + 1];
bookValues[0] = machineCost;
while(i <= estimatedLife - 1)
{
bookValues[i] = bookValues[i - 1] - yearlyDepreciation;
i++;
}
i = 0;
bookValues[estimatedLife] = salvageValue;
cout << " Accumulated" << endl;
cout << "Year Book Value Distribution" << endl;
while(i <= estimatedLife - 1)
{
double accumulatedDepreciation = yearlyDepreciation * year;
cout << "------------------------------------" << endl;
cout << " {0} {1, 10} {2, 12}", year, bookValues[i], accumulatedDepreciation);
i++;
year++;
}
cout << endl << "====================================";Machine Cost: 7448.85 Salvage Value: 955.50 Estimated Life: 5
====================================
Depreciation - Straight-Line Method
------------------------------------
Machine Cost: 7448.85
Salvage Value: 955.5
Estimate Life: 5 Years
Depreciation Rate: 20%
------------------------------------
Depreciable Amount: 6493.35
Yearly Depreciation: 1298.67
====================================
Accumulated
Year Book Value Distribution
------------------------------------
1 7448.85 1298.67
------------------------------------
2 6150.18 2597.34
------------------------------------
3 4851.51 3896.01
------------------------------------
4 3552.84 5194.68
------------------------------------
5 2254.17 6493.35
====================================
Press any key to continue . . .Doing Something While on a List
We saw that a while loop first checks a condition before performing an action. A do...while loop first performs an action before checking a condition. That's their main difference. Otherwise, you can perform a do...while operation where you would have used a while loop. This is also valid for lists such as arrays. Consider a while loop we used earlier as follows:
#include <iostream>
using namespace std;
int main()
{
int counter = 0;
float numbers[] = { 12.44, 525.38, 6.28, 2448.32, 632.04 };
while (counter <= 4)
{
cout << "Number: " << numbers[counter] << endl;
counter++;
}
cout << "==================\n";
}
Instead of first checking a condition before performing an action in a while loop, you may want to first perform the desired action before checking a condition. In that case, the above code can be changed as follows:
#include <iostream>
using namespace std;
int main()
{
int counter = 0;
float numbers[] = { 12.44, 525.38, 6.28, 2448.32, 632.04 };
do {
cout << "Number: " << numbers[counter] << endl;
counter++;
} while (counter <= 4);
cout << "==================\n";
}
Practical Learning: doing Something while a Condition is True
#include <iostream>
using namespace std;
int main()
{
using static System.Math;
using static System.Console;
cout << "=-= Depreciation - Double Declining Balance =-=");
cout << "-----------------------------------------------");
cout << "Provide the following values about the machine");
double machineCost = 0d;
int estimatedLife = 0;
try
{
cout << "Machine Cost: ");
machineCost = double.Parse(ReadLine()!);
}
catch(FormatException fe)
{
cout << "Please provide a valid value for the cost of the machine. " +
"The error produced is: " + fe.Message);
}
try
{
cout << "Estimated Life: ");
estimatedLife = int.Parse(ReadLine()!);
}
catch(FormatException fe)
{
cout << "You must provide a valid number for " +
"the length of the life of the machine. " +
"The error produced is: " + fe.Message);
}
double decliningRate = (100.00 / estimatedLife) * 2.00;
double depreciation = machineCost * decliningRate / 100.00;
Clear();
cout << " =-= Depreciation - Double Declining Balance =-=");
cout << "===========================================================");
cout << "Depreciation Estimation");
cout << "-----------------------------------------------------------");
cout << "Machine Cost: {0:N}", machineCost);
cout << "-----------------------------------------------------------");
cout << "Estimated Life: {0} years", estimatedLife);
cout << "-----------------------------------------------------------");
cout << "Declining Rate: {0:N}", decliningRate);
cout << "-----------------------------------------------------------");
cout << "Depreciation First Year: {0:N}", depreciation);
cout << "===========================================================");
int i = 1;
int year = 1;
double[] yearlyDepreciations = new double[estimatedLife];
double[] bookValuesEndOfYear = new double[estimatedLife];
double[] bookValuesBeginningOfYear = new double[estimatedLife];
// Year 1
bookValuesBeginningOfYear[0] = machineCost;
yearlyDepreciations[0] = machineCost * decliningRate / 100.00;
bookValuesEndOfYear[0] = machineCost - yearlyDepreciations[0];
// The other years
do
{
yearlyDepreciations[i] = bookValuesEndOfYear[i - 1] * decliningRate / 100.00;
bookValuesEndOfYear[i] = bookValuesEndOfYear[i - 1] - yearlyDepreciations[i];
bookValuesBeginningOfYear[i] = bookValuesEndOfYear[i - 1];
i++;
} while(i <= estimatedLife - 1);
i = 0;
cout << " Book Value at Book Value at");
cout << "Beginning of Year Depreciation for Year End of Year");
cout << "-----------------------------------------------------------");
do
{
cout << "{0,10}{1,22}{2,20}", year,
Ceiling(@bookValuesBeginningOfYear[i]),
Ceiling(@yearlyDepreciations[i]),
Ceiling(@bookValuesEndOfYear[i]));
cout << "-----------------------------------------------------------");
i++;
year++;
} while(i <= estimatedLife - 1); =-= Depreciation - Double Declining Balance =-=
===========================================================
Depreciation Estimation
-----------------------------------------------------------
Machine Cost: 24,669.55
-----------------------------------------------------------
Estimated Life: 8 years
-----------------------------------------------------------
Declining Rate: 25.00
-----------------------------------------------------------
Depreciation First Year: 6,167.39
===========================================================
Book Value at Book Value at
Beginning of Year Depreciation for Year End of Year
-----------------------------------------------------------
1 24670 6168
-----------------------------------------------------------
2 18503 4626
-----------------------------------------------------------
3 13877 3470
-----------------------------------------------------------
4 10408 2602
-----------------------------------------------------------
5 7806 1952
-----------------------------------------------------------
6 5855 1464
-----------------------------------------------------------
7 4391 1098
-----------------------------------------------------------
8 3293 824
-----------------------------------------------------------
Press any key to close this window . . .For a List
The primary purpose of a loop is to act on a list, such as an array of items, a list of numbers, etc. As it happens, mathematics (or algebra) automatically provides a list of numbers. This makes it possible to automatically have available a list of numbers as soon as you create an array. On the other hand, if you want a particular list of numbers, you can explicitly create it, as we saw with the while loop. After creating such an array, you can use a for loop to access each item by its position. The formula you can use is:
// Create a list or array of objects for(counter; counter[<][<=][>][>=] start-or-end-value; counter-frequency) { // Optional operations list-or-array-of-objects[counter]; // Optional operations }
Based on this, a for loop primary performs the same operations as a while or a do...while loop. The primary difference is that, for a while or a do...while loop, you can (must) first declare, outside the loop, a variable that holds the starting value of the loop. For a for loop, you can also first declare a variable for the starting value, which you can do outside the loop, but, by tradition, that variable is declared in the parentheses of the for loop. Other than in the body of any of those loops, you can access the elements of the array or list using square brackets. Consider a while loop we used earlier as follows:
#include <iostream>
using namespace std;
int main()
{
int counter = 0;
float numbers[] = { 12.44, 525.38, 6.28, 2448.32, 632.04 };
while (counter <= 4)
{
cout << "Number: " << numbers[counter] << endl;
counter++;
}
cout << "==================\n";
}
Using a for loop, the above code can be changed as follows:
#include <iostream>
using namespace std;
int main()
{
float numbers[] = { 12.44, 525.38, 6.28, 2448.32, 632.04 };
for (unsigned short counter = 0; counter <= 4; counter++)
{
cout << "Number: " << numbers[counter] << endl;
}
cout << "==================\n";
}
Practical Learning: Counting for a Loop
#include <iostream>
using namespace std;
int main()
{
using static System.Math;
using static System.Console;
double GetMachineCost()
{
double machineCost = 0d;
cout << "=-= Depreciation - Sum-of-the-Year's Digits =-=");
cout << "----------------------------------------------");
try
{
cout << "Provide the following values about the machine");
cout << "Machine Cost: ");
machineCost = double.Parse(ReadLine()!);
}
catch (FormatException fe)
{
cout << "The value you provided for the machine cost cannot be used.");
cout << "The error reported is: " + fe.Message);
}
return machineCost;
}
double GetSalvageValue()
{
double salvageValue = 0d;
try
{
cout << "Salvage Value: ");
salvageValue = double.Parse(ReadLine()!);
}
catch (FormatException fe)
{
cout << "The value you provided for the machine cost cannot be used.");
cout << "The error reported is: " + fe.Message);
}
return salvageValue;
}
ubyte GetEstimatedLife()
{
ubyte estimatedLife = 0;
try
{
cout << "Estimated Life: ");
estimatedLife = ubyte.Parse(ReadLine()!);
}
catch (FormatException fe)
{
cout << "The value you provided for the machine cost cannot be used.");
cout << "The error reported is: " + fe.Message);
}
return estimatedLife;
}
double cost = GetMachineCost();
double salvage = GetSalvageValue();
ubyte life = GetEstimatedLife();
double depreciatiableAmount = cost - salvage;
Clear();
cout << "=-= Depreciation - Sum-of-the-Year's Digits =-=");
cout << "===============================================");
cout << "Depreciation Estimation");
cout << "-----------------------------------------------");
cout << "Machine Cost: {0:N}", cost);
cout << "Salvage Value: {0:N}", salvage);
cout << "Estimated Life: " << life);
cout << "depreciatiable Amount: {0:N}", depreciatiableAmount);
int year = 1;
int counter = 0;
int sumOfYears = (life * (life + 1)) / 2;
double[] depreciations = new double[life];
string[] fractions = new string[life];
for (ubyte i = 0; i <= life - 1; i++)
{
fractions[counter] = (i + 1) + "/" + sumOfYears;
depreciations[counter] = (depreciatiableAmount * (i + 1)) / sumOfYears;
counter++;
}
cout << "===============================================");
cout << "Year Fraction Depreciation");
cout << "-----------------------------------------------");
for(ubyte i = 0; i <= life - 1; i++)
{
cout << "{0,3}{1,15}{2,20}", year, fractions[i], Ceiling(@depreciations[i]));
cout << "-----------------------------------------------");
year++;
}=-= Depreciation - Sum-of-the-Year's Digits =-= =============================================== Depreciation Estimation ----------------------------------------------- Machine Cost: 6,849.95 Salvage Value: 524.85 Estimated Life: 5 depreciatiable Amount: 6,325.10 =============================================== Year Fraction Depreciation ----------------------------------------------- 1 1/15 422 ----------------------------------------------- 2 2/15 844 ----------------------------------------------- 3 3/15 1266 ----------------------------------------------- 4 4/15 1687 ----------------------------------------------- 5 5/15 2109 ----------------------------------------------- Press any key to close this window . . .
Reversing the Looping Direction
The primary way to use a loop is to proceed from a lower counting value to a higher counting value. You can reverse that operation by decrementing a counting from a higher to a lower value. This opeation also works on arrays and lists.
Practical Learning: Reversing the Counting Direction
#include <iostream>
using namespace std;
int main()
{
using static System.Math;
double GetMachineCost()
{
double machineCost = 0d;
cout << "=-= Depreciation - Sum-of-the-Year's Digits =-=");
cout << "----------------------------------------------");
try
{
cout << "Provide the following values about the machine");
cout << "Machine Cost: ");
machineCost = double.Parse(ReadLine()!);
}
catch(Exception exc) when (exc is FormatException fe)
{
cout << "The value you provided for the machine cost cannot be used.");
cout << "The error reported is: " + fe.Message);
}
return machineCost;
}
double GetSalvageValue()
{
double salvageValue = 0d;
try
{
cout << "Salvage Value: ");
salvageValue = double.Parse(ReadLine()!);
}
catch (Exception exc) when (exc is FormatException fe)
{
cout << "The value you provided for the machine cost cannot be used.");
cout << "The error reported is: " + fe.Message);
}
return salvageValue;
}
ubyte GetEstimatedLife()
{
ubyte estimatedLife = 0;
try
{
cout << "Estimated Life: ");
estimatedLife = ubyte.Parse(ReadLine()!);
}
catch (Exception exc) when (exc is FormatException fe)
{
cout << "The value you provided for the machine cost cannot be used.");
cout << "The error reported is: " + fe.Message);
}
return estimatedLife;
}
double cost = GetMachineCost();
double salvage = GetSalvageValue();
ubyte life = GetEstimatedLife();
double depreciatiableAmount = cost - salvage;
Clear();
cout << "=-= Depreciation - Sum-of-the-Year's Digits =-=");
cout << "===============================================");
cout << "Depreciation Estimation");
cout << "-----------------------------------------------");
cout << "Machine Cost: {0:N}", cost);
cout << "Salvage Value: {0:N}", salvage);
cout << "Estimated Life: " << life);
cout << "depreciatiable Amount: {0:N}", depreciatiableAmount);
int year = 1;
int reverse = 0;
int sumOfYears = (life * (life + 1)) / 2;
double[] depreciations = new double[life];
string[] fractions = new string[life];
for(ubyte i = life - 1; i >= 0; i--)
{
fractions[reverse] = (i + 1) + "/" + sumOfYears;
depreciations[reverse] = (depreciatiableAmount * (i + 1)) / sumOfYears;
reverse++;
}
cout << "===============================================");
cout << "Year Fraction Depreciation");
cout << "-----------------------------------------------");
for(ubyte i = 0; i <= life - 1; i++)
{
cout << "{0,3}{1,15}{2,20}", year, fractions[i], Ceiling(@depreciations[i]));
cout << "-----------------------------------------------");
year++;
}=-= Depreciation - Sum-of-the-Year's Digits =-= =============================================== Depreciation Estimation ----------------------------------------------- Machine Cost: 6,849.95 Salvage Value: 524.85 Estimated Life: 5 depreciatiable Amount: 6,325.10 =============================================== Year Fraction Depreciation ----------------------------------------------- 1 5/15 2109 ----------------------------------------------- 2 4/15 1687 ----------------------------------------------- 3 3/15 1266 ----------------------------------------------- 4 2/15 844 ----------------------------------------------- 5 1/15 422 ----------------------------------------------- Press any key to close this window . . .
Instead of visiting the elements of a list by counting them, you may want to visit each item directly. To assist you with this, the C++ language provides another way to use a for loop. The formula to use it is:
for(variable : array-or-list) statement;
To make your code easy to read, you can (and should) write the statement on its own line. The formula becomes:
for(variable : array-or-list) statement;
The loop starts with the for keyword followed by parentheses. In the parentheses, you can declare a variable by prodviding a data type and a name. The data type shold be the same as that of the array, or it should be compatible, or it should be convertible. After the name of the variable, type a colon (:). This is followed by the name of the array. Outside the parentheses, create a statement of your choice. At a minimum, you can simply display the variable's value to the user. Here is an example:
#include <iostream>
using namespace std;
int main()
{
float numbers[] = { 12.44, 525.38, 6.28, 2448.32, 632.04 };
for (float nbr : numbers)
cout << "Number: " << nbr << endl;
cout << "==================\n";
}
In the above example, we first declared a variable for the array, and then we used the name of the array in the for loop. This is necessary if you are planning to use the array variable more than once. Otherwise, you can include the array directly in the array-or-list placeholder of the loop. Here is an example:
#include <iostream>
using namespace std;
int main()
{
for (float nbr : { 12.44, 525.38, 6.28, 2448.32, 632.04 })
cout << "Number: " << nbr << endl;
cout << "==================\n";
}
Controlling the Number of Elements to Process
So far, when calling a function that used an array as a parameter, we considered that the function would used all the elements of the array. Another situation that was real so far is that the function that was using the array didn't know the number of elements in the parameter. Here is an example:
#include <iostream>
using namespace std;
void Create(string values[8]);
using namespace std;
void Create(string member[8]);
int main()
{
string members[8];
members[0] = "Celeste";
members[1] = "Mathurin";
members[2] = "Alex";
members[3] = "Germain";
members[4] = "Jeremy";
members[5] = "Mathew";
members[6] = "Anselme";
members[7] = "Frederique";
Create(members);
cout << "======================\n";
}
void Create(string people[8])
{
unsigned short counter = 0;
while(counter < 8) {
cout << "Person: " << people[counter] << endl;
++counter;
}
}
This would produce:
People[0]: Celeste People[1]: Mathurin People[2]: Alex People[3]: Germain People[4]: Jeremy People[5]: Mathew People[6]: Anselme People[7]: Frederique ====================== Press any key to close this window . . .
In some cases, you want the function to process only some elements. In these two scenarios, one way to deal with the issue is to pass an additional parameter to the function. That other paraemter would hold a constant value that represents the number of items that the function should process. Of course, when calling the function, you must pass both arguments. Here is an example:
#include <iostream> using namespace std; void Create(string values[8], int max); int main() { string members[8]; members[0] = "Celeste"; members[1] = "Mathurin"; members[2] = "Alex"; members[3] = "Germain"; members[4] = "Jeremy"; members[5] = "Mathew"; members[6] = "Anselme"; members[7] = "Frederique"; Create(members, 4); cout << "======================\n"; } void Create(string people[], int max) { unsigned short counter = 0; while(counter < max) { cout << "Person: " << people[counter] << endl; ++counter; } }
This would produce:
People[0]: Celeste People[1]: Mathurin People[2]: Alex People[3]: Germain ====================== Press any key to close this window . . .
Controlling the Range of Elements to Process
You can control the range of items to processin an array. This means that you can specify the starting and ending limits of the elements to process in the array passed as parameter. To do this, besides the array, pass two additional integer values to the function. One of the values would hold the starting point and the other value would be the ending point. In the body of the function, use those additional arguments accordingly. Here is an example:
#include <iostream> using namespace std; void Create(unsigned short start, string values[8], unsigned short end); int main() { string members[8]; members[0] = "Celeste"; members[1] = "Mathurin"; members[2] = "Alex"; members[3] = "Germain"; members[4] = "Jeremy"; members[5] = "Mathew"; members[6] = "Anselme"; members[7] = "Frederique"; Create(2, members, 6); cout << "======================\n"; } void Create(unsigned short start, string people[], unsigned short end) { unsigned short counter = start; while(counter < end) { cout << "Person: " << people[counter] << endl; ++counter; } }
This would produce:
Person: Alex Person: Germain Person: Jeremy Person: Mathew ====================== Press any key to close this window . . .
When declaring a function that takes an array argument, as we learned with other arguments, you don't have to provide a name to the argument. Simply typing the square brackets on the right side of the data type in the parentheses is enough. The name of the argument is only necessary when defining the function. Therefore, the above function can be declared as follows:
#include <iostream>
using namespace std;
void Create(unsigned short start, string[], unsigned short end);
int main()
{
string members[8];
members[0] = "Celeste";
members[1] = "Mathurin";
members[2] = "Alex";
members[3] = "Germain";
members[4] = "Jeremy";
members[5] = "Mathew";
members[6] = "Anselme";
members[7] = "Frederique";
Create(2, members, 6);
cout << "======================\n";
}
void Create(unsigned short start, string people[], unsigned short end)
{
unsigned short counter = start;
while(counter < end) {
cout << "Person: " << people[counter] << endl;
++counter;
}
}
Nesting a Conditional Statement in a Loop
In the body of a loop (while, do...while, for), you can create and include a conditional statement. Here is an example:
#include <iostream>
using namespace std;
int main()
{
unsigned short numbers[] = { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };
cout << "Original List" << endl;
cout << "--------------------------" << endl;
for (int i = 0; i < 10; i++)
cout << "Number: " << numbers[i] << endl;
cout << "==========================" << endl;
cout << "Only the first 4 elements" << endl;
cout << "--------------------------" << endl;
for (int i = 0; i < 10; i++)
if (i < 4)
cout << "Number: " << numbers[i] << endl;
cout << "==========================\n";
}
This would produce:
Original List -------------------------- Number: 102 Number: 44 Number: 525 Number: 38 Number: 6 Number: 28 Number: 24481 Number: 327 Number: 632 Number: 104 ========================== Only the first 4 elements -------------------------- Number: 102 Number: 44 Number: 525 Number: 38 ========================== Press any key to continue . . .
You can use the same technique to get the last m members of a list. You can also use a similar technique to get one or a few values inside of the list, based on a condition of your choice. Here is an example that gets the values that are multiple of 5 from the array:
#include <iostream>
using namespace std;
int main()
{
ushort[] numbers = new ushort[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };
for(int i = 0; i < 10; i++)
if(numbers[i] % 5 == 0)
cout << "Number: " << numbers[i]);
cout << "===============================");
This would produce:
Number: 525 =============================== Press any key to continue . . .
Operations on Arrays
Introduction
Each member of an array is a pseudo-variable and can be processed as such. This means that you can add the values of two members of the array(number[2] + number[0]), you can subtract the value of one of the members from another member(member[1] - number[4]). In the same way, you can perform multiplication, division, or remainder operations on members of an array.
Calculating a Sum of Numbers
One of the regular operations performed on an array consists of adding the values of the members to produce a sum. Here is an example:
#include <iostream>
using namespace std;
int main()
{
unsigned long long sum = 0;
unsigned long long number[10];
cout << "Please type 10 integers.";
cout << "\n-------------------------------------\n";
for(unsigned short i = 0; i < 10; i++)
{
cout << "Number " << i + 1 << ": ";
cin >> number[i];
sum += number[i];
}
cout << "-------------------------------------\n";
cout << "The sum of these numbers is " << sum << endl;
cout << "=====================================\n";
}
Here is an example of running the program:
Please type 10 integers. ------------------------------------- Number 1: 22468 Number 2: 5529 Number 3: 137993 Number 4: 63964 Number 5: 3136811 Number 6: 397284 Number 7: 17522 Number 8: 6362753 Number 9: 39748 Number 10: 5824477 ------------------------------------- The sum of these numbers is 16008549 ===================================== Press any key to close this window . . .
Searching a Value in an Array
Another type of operation regularly performed on an array consists of looking for a value held by one of its members. For example, you may want to know if one of the members holds a particular value you are looking for. Here is an example:
#include <iostream>
using namespace std;
int main()
{
short valueToFind;
unsigned short i, m = 8;
short numbers[] = { 8, 25, 36, 44, 52, 60, 75, 89 };
cout << "Enter a number to search: ";
cin >> valueToFind;
for (i = 0; (i < m) and (numbers[i] != valueToFind); ++i)
continue;
// Find out whether the number typed is a member of the array
if (i == m)
cout << valueToFind << " is not in the list." << endl;
else
{
cout << "--------------------------------------\n";
if(i == 0)
cout << valueToFind << " is the first element in the list." << endl;
else if (i == 1)
cout << valueToFind << " is the second element in the list." << endl;
else if (i == 2)
cout << valueToFind << " is the third element in the list." << endl;
else
cout << valueToFind << " is the " << i + 1
<< "th element in the list." << endl;
}
cout << "======================================\n";
}
Here is an example of running the program:
Enter a number to search: 40 40 is not in the list. ====================================== Press any key to close this window . . .
Here is another example of running the program:
Enter a number to search: 8 -------------------------------------- 8 is the first element in the list. ====================================== Press any key to close this window . . .
Here is another example of running the program:
Enter a number to search: 25 -------------------------------------- 25 is the second element in the list. ====================================== Press any key to close this window . . .
Here is another example of running the program:
Enter a number to search: 52 -------------------------------------- 52 is the 5th element in the list. ====================================== Press any key to close this window . . .
Practical Learning: Ending the Lesson
|
|
|||
| Previous | Copyright © 2001-2026, FunctionX | Monday 06 October 2025, 14:40 | Next |
|
|
|||