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
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
string erase in C++
Next article icon

Arrays and Strings in C++

Last Updated : 07 May, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Arrays

An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar types of elements as in the data type must be the same for all elements. They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C or C++ can store derived data types such as the structures, pointers, etc.
There are two types of arrays:

  • One Dimensional Array
  • Multi Dimensional Array

One Dimensional Array: A one dimensional array is a collection of same data types. 1-D array is declared as:

  data_type variable_name[size]    data_type is the type of array, like int, float, char, etc.  variable_name is the name of the array.  size is the length of the array which is fixed.  

Note: The location of the array elements depends upon the data type we use.

Below is the illustration of the array:

Below is the program to illustrate the traversal of the array:




// C++ program to illustrate the traversal
// of the array
#include "iostream"
using namespace std;
  
// Function to illustrate traversal in arr[]
void traverseArray(int arr[], int N)
{
  
    // Iterate from [1, N-1] and print
    // the element at that index
    for (int i = 0; i < N; i++) {
        cout << arr[i] << ' ';
    }
}
  
// Driver Code
int main()
{
  
    // Given array
    int arr[] = { 1, 2, 3, 4 };
  
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Function call
    traverseArray(arr, N);
}
 
 
Output:
  1 2 3 4  

MultiDimensional Array: A multidimensional array is also known as array of arrays. Generally, we use a two-dimensional array. It is also known as the matrix. We use two indices to traverse the rows and columns of the 2D array. It is declared as:

  data_type variable_name[N][M]    data_type is the type of array, like int, float, char, etc.  variable_name is the name of the array.  N is the number of rows.  M is the number of columns.  

Below is the program to illustrate the traversal of the 2D array:




// C++ program to illustrate the traversal
// of the 2D array
#include "iostream"
using namespace std;
  
const int N = 2;
const int M = 2;
  
// Function to illustrate traversal in arr[][]
void traverse2DArray(int arr[][M], int N)
{
  
    // Iterate from [1, N-1] and print
    // the element at that index
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            cout << arr[i][j] << ' ';
        }
        cout << endl;
    }
}
  
// Driver Code
int main()
{
  
    // Given array
    int arr[][M] = { { 1, 2 }, { 3, 4 } };
  
    // Function call
    traverse2DArray(arr, N);
  
    return 0;
}
 
 
Output:
  1 2   3 4  

Strings

C++ string class internally uses character array to store character but all memory management, allocation, and null termination are handled by string class itself that is why it is easy to use. For example it is declared as:

  char str[] = "GeeksforGeeks"  

Below is the program to illustrate the traversal in the string:




// C++ program to illustrate the
// traversal of string
#include "iostream"
using namespace std;
  
// Function to illustrate traversal
// in string
void traverseString(char str[])
{
    int i = 0;
  
    // Iterate till we found '\0'
    while (str[i] != '\0') {
        printf("%c ", str[i]);
        i++;
    }
}
  
// Driver Code
int main()
{
  
    // Given string
    char str[] = "GeekforGeeks";
  
    // Function call
    traverseString(str);
  
    return 0;
}
 
 
Output:
  G e e k f o r G e e k s  

The string data_type in C++ provides various functionality of string manipulation. They are:

  1. strcpy(): It is used to copy characters from one string to another string.
  2. strcat(): It is used to add the two given strings.
  3. strlen(): It is used to find the length of the given string.
  4. strcmp(): It is used to compare the two given string.

Below is the program to illustrate the above functions:




// C++ program to illustrate functions
// of string manipulation
#include "iostream"
#include "string.h"
using namespace std;
  
// Driver Code
int main()
{
  
    // Given two string
    char str1[100] = "GeekforGeeks";
    char str2[100] = "HelloGeek";
  
    // To get the length of the string
    // use strlen() function
    int x = strlen(str1);
  
    cout << "Length of string " << str1
         << " is " << x << endl;
  
    cout << endl;
  
    // To compare the two string str1
    // and str2 use strcmp() function
    int result = strcmp(str1, str2);
  
    // If result is 0 then str1 and str2
    // are equals
    if (result == 0) {
        cout << "String " << str1
             << " and String " << str2
             << " are equal." << endl;
    }
    else {
  
        cout << "String " << str1
             << " and String " << str2
             << " are not equal." << endl;
    }
  
    cout << endl;
  
    cout << "String str1 before: "
         << str1 << endl;
  
    // Use strcpy() to copy character
    // from one string to another
    strcpy(str1, str2);
  
    cout << "String str1 after: "
         << str1 << endl;
  
    cout << endl;
  
    return 0;
}
 
 
Output:
  Length of string GeekforGeeks is 12    String GeekforGeeks and String HelloGeek are not equal.    String str1 before: GeekforGeeks  String str1 after: HelloGeek  


Next Article
string erase in C++

M

mohakshrivastava2019
Improve
Article Tags :
  • Arrays
  • C++
  • DSA
  • Misc
  • Strings
Practice Tags :
  • CPP
  • Arrays
  • Misc
  • Strings

Similar Reads

  • Array of Strings in C++
    In C++, a string is sequence of characters that is used to store textual information. Internally, it is implemented as a dynamic array of characters. Array of strings is the array in which each element is a string. We can easily create an array of string in C++ as shown in the below example: [GFGTAB
    4 min read
  • STD::array in C++
    The array is a collection of homogeneous objects and this array container is defined for constant size arrays or (static size). This container wraps around fixed-size arrays and the information of its size are not lost when declared to a pointer. In order to utilize arrays, we need to include the ar
    5 min read
  • string at() in C++
    The std::string::at() in C++ is a built-in function of std::string class that is used to extract the character from the given index of string. In this article, we will learn how to use string::at() in C++. Syntaxstr.at(idx) Parametersidx: Index at which we have to find the character.Return ValueRetu
    1 min read
  • string erase in C++
    The string erase() function is a built-in function of the string class that is used to erase the whole or part of the string, shortening its length. The function provides different ways to delete a portion of a string based on either an index position or a range of characters or delete the whole str
    4 min read
  • Strings in C++
    In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class. Creating a StringCreating a st
    6 min read
  • Strings in C
    A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is work as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. DeclarationDeclaring a string in C
    6 min read
  • Pointer to an Array in C++
    Pointers in C++ are variables that store the address of another variable while arrays are the data structure that stores the data in contiguous memory locations. In C++, we can manipulate arrays by using pointers to them. These kinds of pointers that point to the arrays are called array pointers or
    6 min read
  • std::string::append() in C++
    The string::append() in C++ is used append the characters or the string at the end of the string. It is the member function of std::string class . The string::append() function can be used to do the following append operations: Table of Content Append a Whole StringAppend a Part of the StringAppend
    3 min read
  • array::size() in C++ STL
    The array::size() method is used to find the number of elements in the array container. It is the member method std::array class defined inside <array> header file. In this article, we will learn about the array::size() method in C++. Example: [GFGTABS] C++ // C++ Program to illustrate the use
    2 min read
  • stringstream in C++ and its Applications
    A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input. Basic methods are: clear()- To clear the stream.st
    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