In this tutorial you will learn the basics of C++ and how to use arrays. This will allow you to write a simple C++ program that you will then compile. The program will be a Visual Studio console application
About this Tutorial –
Objectives –
This course is aimed at students who need to get up to speed in C++. The course introduces object-oriented concepts and shows how they are implemented in C++. The course does not require awareness or familiarity with object-oriented programming techniques, but programming experience would be useful but not necessarily required.
Audience
Students who are new to object orientation (or programming) and need to learn C++.
Prerequisites
No previous experience in C++ programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.
Experience using a contemporary OO language such as Java or C# would be useful but is not required.
Contents
The C++ course covers these topics and more:
Introduction to C++: Key features of C++; Defining variables; Formulating expressions and statements; Built-in data types; Console input/output
Operators and types: Assignment; Compound Assignment; Increment and decrement operators; Const declarations; Type conversions
Going Further with Data Types: Enumerations; Arrays; Using the standard vector class; Using the standard string class; Structures
Where size is a compile-time constant type arrayName[size];
Examples:
Note that these statements actually reserve the storage for the arrays (on the stack) int examMarks[10];
double rainfallFigures[12];
string premierLeagueTeams[20];
Using an Array Initializer
You can create and populate an array all in one go, using array initializer syntax
You can omit the size inside the []
The compiler counts the number of terms enclosed in the {} type arrayName[] = { value0, value1, ... };
If you overflow, you access whatever data is in that space! arrayName[index]
You can read and write array elements
As long as the array isn’t const, of course string topTeams[] = { "Man City", "Man Utd", "Arsenal" };
cout << "The top team is " << topTeams[0] << endl;
topTeams[1] = "Swansea City";
cout << "The next best team is " << topTeams[1] << endl;
Traversing an Array
You can traverse an array using a for loop
This is the traditional approach
Use an integer array index that ranges from 0 to (n-1) const string DAYS_OF_WEEK[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
for (int i = 0; i < 7; i++)
{
cout << "Day " << i << " is " << DAYS_OF_WEEK[i] << endl;
}
Note 1:
Arrays don't have a "length" property in C++
Note 2:
There is no such construct as a "foreach" loop in C++
Although there's an algorithm that emulates it - see later
Copying Arrays
You can't assign arrays to each other int array1[10];
int array2[10];
array1 = array2;
Instead, you must assign each array element individually int array1[10];
int array2[10];
for (int i = 0; i < 10; i++)
{
array1[i] = array2[i];
}
In Visual Studio, create a new C++ project named ArraysApp2 in the student folder. Write code to declare and use a 2D array, to hold the lap times for athletes in a 1600m race. Suggestions and requirements:
First, write a header file named AthleteDeclarations.h. In the header file, add two #define directives as follows:
Define a symbol named NUM_ATHLETES, and set this value to 8 #define NUM_ATHLETES 8
Define a symbol named NUM_LAPS, and set this value to 4 (there are 4 laps in a 1600m race). #define NUM_LAPS 4
Now, in your source code file, define a 2D array to hold the lap times for all the athletes. The 2D array should have NUM_ATHLETES rows and NUM_LAPS columns. Note that the lap times will be fractional values, not whole numbers double athleteTimes[NUM_ATHLETES][NUM_LAPS];
Write a for-loop to prompt the user to enter the lap times for each athlete. For example: // Words
Athlete 1, lap 1 time? xxx
Athlete 1, lap 2 time? xxx
Athlete 1, lap 3 time? xxx
...
Athlete 2, lap 1 time? xxx
Athlete 2, lap 2 time? xxx
etc...
// CODE
cout << "Enter the lap times for each athlete:" << endl;
for (int athlete = 0; athlete < numAthletes; athlete++)
{
for (int lap = 0; lap < numLaps; lap++)
{
double time;
cout << "Athlete " << athlete + 1 << ", lap " << lap + 1 << " time: ";
cin >> time;
athleteLapTimes[athlete][lap] = time;
}
}
Write another for-loop to display all the lap times for each athlete cout << endl << "Lap times for each athlete:";
for (int athlete = 0; athlete < numAthletes; athlete++)
{
cout << endl << "Athlete " << athlete + 1 << " lap times: ";
for (int lap = 0; lap < numLaps; lap++)
{
cout << athleteLapTimes[athlete][lap] << " ";
}
}
cout << endl;
The function receives the address of the first element in the array
In other words, the function has access to the original array!
This is different from how all other types work in C++!!!
When passing arrays into functions, it's commonplace to pass two parameters
The array itself
The count of elements in the array
Example
Here's an example of a function that displays an array of integer values to the console
Note that you do not specify the array size inside the []
This is because the function only receives the address of the first element, not a copy of the entire array void displayArray(int array[], int count)
{
for (int i = 0; i < count; i++)
cout << array[i] << endl
}
You can pass any array of integers into the example function int examMarks[10];
int lotteryNumbers[6];
...
displayArray(examMarks, 10);
displayArray(lotteryNumbers, 6);
Updating Arrays
Functions are allowed to modify the elements in an array
Because functions receive the start address of the actual array
Example: void tripleValues(int array[], int count)
{
for (int i = 0; i < count; i++)
array[i] *= 3;
}
int myNumbers[] = { 10, 20, 30, 40, 50 };
displayArray(myNumbers, 5); // Displays 10, 20, 30, 40, 50.
tripleValues(myNumbers, 5); // Updates actual array elements.
displayArray(myNumbers, 5); // Displays 30, 60, 90, 120, 150.
Protecting Arrays
If you want to indicate (and ensure) a function doesn't modify an array...
Declare the array as const (in the prototype and the definition)
Client code can rest assured that the function will not change the array values
Very good practice!
Example: void safeDisplayArray(const int array[], int count)
{
for (int i = 0; i < count; i++)
cout << array[i] << endl
}
Lab
Passing a 2D array into a function
Write functions to populate and display your 2D array of athlete lap times. Here are the function prototypes for you to add to your header file:
GetAthleteLapTimes void GetAthleteLapTimes(double athleteLapTimes[][NUM_LAPS],
int numAthletes);
DisplayAthleteLapTimes void DisplayAthleteLapTimes(const double athleteLapTimes[][NUM_LAPS],
int numAthletes);
Implement these functions in your source file. This is easy, you can simply copy-and-paste much of the code from main(), and then just call your new functions from main() // From main()
GetAthleteLapTimes(athleteTimes, NUM_ATHLETES, NUM_LAPS);
DisplayAthleteLapTimes(athleteTimes, NUM_ATHLETES, NUM_LAPS);
// E.g. in source file
void GetAthleteLapTimes(double athleteLapTimes[][NUM_LAPS], int numAthletes, int numLaps)
{
cout << "Enter the lap times for each athlete:" << endl;
...
}
All the arrays we've seen so far have been 1-dimensional except in the labs
Declared and indexed using a single set of []
C++ also allows you to define multi-dimensional arrays
E.g. for grids, cubes, etc.
Use multiple sets of []
Creating a Multi-Dimensional Array
To create a multi-dimensional array (e.g. 2 dimensions): type arrayName[numRows][numCols];
You can use initializer syntax, with multiple sets of braces type arrayName[][numCols] = {
{ ..., ..., ... },
{ ..., ..., ... },
};
To traverse a multi-dimensional array, use nested loops for (int r = 0; r < numRows; r++)
{
for (int c = 0; c < numCols; c++)
{
// Access element arrayName[r][c]
}
}
Passing into Functions
You can pass multi-dimensional arrays into a function
Specify the correct number of []
You must specify all but the first dimension void displayPeoplesLotteryNumbers(int lotteryNumbers[][6], int numPeople)
{
for (int r = 0; r < numPeople; r++)
{
cout << "Here are the lottery numbers for person " << r << endl;
for (int c = 0; c < 6; c++)
{
cout << lotteryNumbers[r][c] << endl
}
}
}
// Client Side
int myFriendsLotteryNumbers[10][6]; // 10 rows, 6 columns per row.
displayPeoplesLotteryNumbers(myFriendsLotteryNumbers, 10);
Lab
Further array processing
Calculate the total finishing time for each athlete as follows:
Write a new function named DisplayFinishingTimes() void DisplayFinishingTimes(const double athleteLapTimes[][NUM_LAPS], int numAthletes, int numLaps)
{
...
}
In this function, write a loop to step through all the athlete lap times. Then write a nested loop to add up the 4 lap times for that athlete. Display the total time for each athlete cout << endl << "Total finishing times for each athlete: " << endl;
for (int athlete = 0; athlete < numAthletes; athlete++)
{
double athleteTotalTime = 0;
for (int lap = 0; lap < numLaps; lap++)
{
athleteTotalTime += athleteLapTimes[athlete][lap] ;
}
cout << "Total time for athlete " << athlete + 1 << ": " << athleteTotalTime << endl;
}
Call your new function from main(), to test it DisplayFinishingTimes(athleteTimes, NUM_ATHLETES, NUM_LAPS);
If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Manage cookie consent
You can view this website without consenting to extra cookies. However you will need to accept the 'marketing' cookies to send messages via the contact forms & see any maps displayed on the site
Functional
Always active
Cookies necessary for the website to work.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.Cookies used to track user interaction on the site, which helps us to evaluate & improve the website.
Marketing: Forms & additional content (Marketing)
We need your permission to place ‘marketing’ cookies, so you are able to use the contact forms & see embedded content e.g. videos and maps. - - - - We have added protection to our contact forms to help prove that a human (rather than a spambot) is filling
If you would like to see more content like this in the future, please fill-in our quick survey.