Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Pass Array to Functions in C++
Next article icon

One Dimensional Arrays in C++

Last Updated : 27 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

One-dimensional arrays are like a row of boxes where you can store things where each box can hold one item, such as a number or a word. For example, in an array of numbers, the first box might hold 5, the second 10, and so on. You can easily find or change what's in each box by referring to its position, called an index. Arrays are handy because they let you store lots of related data in one place and access it quickly.

In this article, we will learn about One Dimensional Arrays in C++.

Syntax of 1D Array in C++

The one dimensional array can be declared as shown below:

element_type array_name [size]

Properties of 1D Array in C++

One-dimensional arrays are organized as a sequence of contiguous memory locations, each capable of holding a single data element of the same type. Following are the main properties of 1D array in C++:

Contiguous Memory Allocation

When you create an array in C++, it allocates a block of memory to hold all the elements. This means the elements are stored right next to each other in memory, without any gaps. For example, if you have an array of integers, each integer occupies a fixed-size space in memory, and they're arranged one after the other.

Index-Based Access

Elements in the array are accessed using an index, which is a numeric value indicating the position of the element within the array. The index starts from 0 for the first element and goes up to one less than the size of the array. So, if you have an array with five elements, the indices range from 0 to 4.

Fixed Size

One-dimensional arrays have a fixed size, meaning once you declare an array with a certain number of elements, you can't change its size during runtime. The size of the array needs to be specified at compile time.

Linear Structure

The elements in a one-dimensional array are arranged in a linear or one-dimensional structure. This means there's only one dimension to consider when accessing or arranging the elements. Unlike multi-dimensional arrays, which have rows and columns, one-dimensional arrays have a single row or sequence of elements.

One-dimensional arrays in C++ are organized as a contiguous block of memory locations, accessed using indices, with a fixed size determined at compile time. Their linear structure and index-based access make them efficient for storing and accessing collections of data in computer programs.

How to Use 1d Array in C++

Usage of one-dimensional arrays in C++ involves declaring the array, initializing it with values (optional), accessing and modifying elements, and performing various operations on the array.

Declaring an Array

To declare an array in C++, you specify the data type of the elements followed by the array name and the size of the array in square brackets. For example, to declare an array of integers with five elements:

int arr[5];

This creates an array named arr capable of holding five integers.

Initializing the Array

You can optionally initialize the array with values at the time of declaration or later using a loop or by assigning values individually. For example:

int arr[5] = {10, 20, 30, 40, 50}; // Initializing with values

This initializes the array arr with five integers: 10, 20, 30, 40, and 50.

Accessing and Modifying Elements

Elements in the array are accessed using indices, starting from 0 for the first element. You can access and modify elements using square brackets []. For example:

int value = arr[2]; // Accessing the element at index 2 (30)

arr[3] = 60; // Modifying the element at index 3 to 60

Performing Basic Operations

You can perform various operations on arrays, such as searching for an element, sorting the elements, or calculating the sum of all elements. These operations typically involve iterating through the array using loops and applying the necessary logic. For example, to find the sum of all elements in the array:

int sum = 0;

for (int i = 0; i < 5; i++) {

sum += arr[i];

}

This loop iterates through each element of the array and adds it to the sum variable.

Dynamic Memory Allocation (Optional)

In addition to fixed-size arrays, you can also dynamically allocate memory for arrays using pointers. This allows you to create arrays of variable sizes at runtime. For example:

int* dynamicArr = new int[5]; // Dynamically allocating memory for an array of 5 integers

Remember to deallocate the memory using delete[] when you're done using the dynamically allocated array to avoid memory leaks.

Complexity Analysis of Basic Array Operations

Several basic operations can be performed on one-dimensional arrays in C++, each with its associated time and space complexity:

Accessing an Element by Index

Time Complexity: O(1). Since arrays provide constant-time access to elements based on their indices, accessing an element by index takes constant time regardless of the size of the array.

Space Complexity: O(1). This operation requires no additional space beyond the memory used by the array itself.

Modifying an Element by Index

Time Complexity: O(1). Similar to accessing an element, modifying an element by index takes constant time regardless of the size of the array.

Space Complexity: O(1). No additional space is required beyond the memory used by the array.

Insertion/Deletion

Time Complexity:

Insertion/Deletion at the beginning or middle of the array: O(n). Since shifting elements requires iterating through and potentially moving each element, the time complexity is linearly proportional to the size of the array.

Insertion/Deletion at the end of the array (if space is available): O(1). If there's available space at the end of the array, inserting or deleting an element requires only updating the array's size and doesn't involve shifting elements.

Space Complexity: O(1). Inserting or deleting an element in the array doesn't require additional space beyond the memory used by the array itself.

Understanding the time and space complexities of these basic operations is essential for designing efficient algorithms and data structures that utilize one-dimensional arrays.

Example of One Dimensional Array in C++

C++
#include <iostream> using namespace std;  int main() {     // Declaration and initialization of an array     int arr[5] = {10, 20, 30, 40, 50};      // Accessing elements of the array     cout << "Element at index 2: " << arr[2] << endl;      // Modifying elements of the array     arr[3] = 60;     cout << "Modified element at index 3: " << arr[3] << endl;      // Calculating the sum of all elements     int sum = 0;     for (int i = 0; i < 5; i++) {         sum += arr[i];     }     cout << "Sum of all elements: " << sum << endl;      return 0; } 

Output
Element at index 2: 30  Modified element at index 3: 60  Sum of all elements: 170  

Applications of One Dimensional Array

One-dimensional arrays in C++ find wide-ranging applications across various domains due to their simplicity, efficiency, and versatility. Here are some common applications of one-dimensional arrays:

  1. Data Storage and Retrieval
  2. Numerical Computations
  3. Algorithm Design and Implementation
  4. Input and Output Operations
  5. Memory Management'



Next Article
Pass Array to Functions in C++
author
omkarchavan_07
Improve
Article Tags :
  • C++
  • CPP-DSA
  • misc-cpp
Practice Tags :
  • CPP

Similar Reads

  • One Dimensional Arrays in C
    In C, an array is a collection of elements of the same type stored in contiguous memory locations. This organization allows efficient access to elements using their index. Arrays can also be of different types depending upon the direction/dimension they can store the elements. It can be 1D, 2D, 3D,
    5 min read
  • One Dimensional Array in Java
    An array is a type of Data Structure that can store collections of elements. These elements are stored in contiguous memory locations and the it provides efficient access to each element based on the index of the array element. In this article, we will learn about a one-dimensional array in Java. Wh
    7 min read
  • C++ Multidimensional Array
    A multidimensional array is an array with more than one dimension. It means that it can grow in different directions i.e. instead of changing the length only, it can also change in width, depth or more. It is the homogeneous collection of items where each element is accessed using multiple indices.
    10 min read
  • How to declare a Two Dimensional Array of pointers in C?
    A Two Dimensional array of pointers is an array that has variables of pointer type. This means that the variables stored in the 2D array are such that each variable points to a particular address of some other element. How to create a 2D array of pointers: A 2D array of pointers can be created follo
    3 min read
  • Pass Array to Functions in C++
    In C++, a collection of elements stored in contiguous memory locations and having the same data type is called an array. Passing arrays to functions is done to perform various operations on array elements without messing up with the main code. In C++, an array can be passed in a function using a poi
    5 min read
  • Array Type Manipulation in C++
    This article demonstrates some of the inbuilt functions that can be used to query and manipulate array types, even a multidimensional array. These functions can be useful in cases we need information or manipulate array we initiated with different dimensions. These functions are defined in header fi
    5 min read
  • Array Definition & Meaning in DSA
    An array is a collection of items of same data type stored at contiguous memory locations Types of Arrays:One-dimensional Array: It is the simplest kind of array where all the elements are stored linearly in a single row. Two-dimensional Array: A two-dimensional array is an array with 2 dimensions,
    4 min read
  • Pass Array to Functions in C
    Passing an array to a function allows the function to directly access and modify the original array. In this article, we will learn how to pass arrays to functions in C. In C, arrays are always passed to function as pointers. They cannot be passed by value because of the array decay due to which, wh
    3 min read
  • How to Get Value of Multidimensional Array in C?
    Prerequisite: Array in C An array is a type of data structure where we can store multiple elements of similar data types. A multidimensional array can be termed an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays are stored in row-major order. Declaration
    8 min read
  • Initialization of Multidimensional Arrays in C++
    In C++, multidimensional arrays are the type of arrays that have multiple dimensions, i.e., they can expand in multiple directions. In this article, we will discuss how to initialize the multidimensional arrays in C++. Methods to Initialize Multidimensional Array in C++We can initialize multidimensi
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences