C++ / C++ Arrays and Strings

Working with Arrays in C++

This tutorial will guide you through the basics of working with single and multi-dimensional arrays in C++. You will learn how to declare, initialize, and manipulate arrays.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explores working with arrays, multi-dimensional arrays, and string manipulation.

Working with Arrays in C++

1. Introduction

Goal of the Tutorial

This tutorial aims to provide an in-depth understanding of how to work with arrays in C++. We will cover single-dimensional and multi-dimensional arrays, how to declare, initialize, and manipulate them.

Learning Outcomes

By the end of this tutorial, you will be able to:
- Understand what arrays are and why they are useful
- Declare and initialize single and multi-dimensional arrays
- Access and modify elements within an array
- Understand the basics of memory allocation with arrays

Prerequisites

Basic knowledge of C++ syntax and data types is recommended.

2. Step-by-Step Guide

What is an Array?

An array is a data structure that allows you to store multiple values of the same type in a single variable. This is especially useful when you need to store many values, but don't want to create a separate variable for each one.

Declaring and Initializing an Array

To declare an array in C++, you specify the type of its elements, followed by the name of the array and the array size in square brackets.

int myArray[5];

To initialize an array, you can assign values to it at the time of declaration:

int myArray[5] = {10, 20, 30, 40, 50};

Accessing Array Elements

To access an array element, you use the array name followed by the index of the element in square brackets. Remember that array indices start at 0, not 1.

cout << myArray[0]; // Outputs: 10

3. Code Examples

Example 1: Single-Dimensional Array

#include <iostream>
using namespace std;

int main() {
    // Declare and initialize an array
    int scores[5] = {89, 95, 76, 85, 92};

    // Access and print each element
    for(int i = 0; i < 5; i++) {
        cout << "Score " << (i+1) << ": " << scores[i] << endl;
    }

    return 0;
}

Expected Output:

Score 1: 89
Score 2: 95
Score 3: 76
Score 4: 85
Score 5: 92

Example 2: Multi-Dimensional Array

#include <iostream>
using namespace std;

int main() {
    // Declare and initialize a 2D array
    int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};

    // Access and print each element
    for(int i = 0; i < 2; i++) {
        for(int j = 0; j < 3; j++) {
            cout << "Element at [" << i << "][" << j << "]: " << matrix[i][j] << endl;
        }
    }

    return 0;
}

Expected Output:

Element at [0][0]: 1
Element at [0][1]: 2
Element at [0][2]: 3
Element at [1][0]: 4
Element at [1][1]: 5
Element at [1][2]: 6

4. Summary

In this tutorial, we have learned what arrays are, how to declare, initialize, access, and manipulate them. We also discussed the importance of memory allocation with arrays. The next steps would be to dive deeper into more complex data structures and algorithms, which often make use of arrays.

5. Practice Exercises

Exercise 1:
Declare an array of size 10, initialize it with numbers from 1 to 10, and print them in reverse order.

Exercise 2:
Declare a 3x3 two-dimensional array and initialize it with numbers from 1 to 9. Then print the matrix.

Solutions

Solution 1:

#include <iostream>
using namespace std;

int main() {
    // Declare and initialize the array
    int myArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    // Print in reverse order
    for(int i = 9; i >= 0; i--) {
        cout << myArray[i] << endl;
    }

    return 0;
}

Solution 2:

#include <iostream>
using namespace std;

int main() {
    // Declare and initialize the 2D array
    int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

    // Print the matrix
    for(int i = 0; i < 3; i++) {
        for(int j = 0; j < 3; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

File Size Checker

Check the size of uploaded files.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help