The Wayback Machine - https://web.archive.org/web/20240822171805/https://www.geeksforgeeks.org/arrays-and-strings-in-c/
Open In App

Arrays and Strings in C++

Last Updated : 07 May, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Basic
15.91%
23.3K

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


Similar Reads

Test Case Generation | Set 2 ( Random Characters, Strings and Arrays of Random Strings)
Set 1 (Random Numbers, Arrays and Matrices) Generating Random Characters C/C++ Code // A C++ Program to generate test cases for // random characters #include&lt;bits/stdc++.h&gt; using namespace std; // Define the number of runs for the test data // generated #define RUN 5 // Define the range of the test data generated // Here it is 'a' to 'z' #def
11 min read
Count of possible arrays from prefix-sum and suffix-sum arrays
Given 2*N integers which are elements of a prefix and suffix array(in shuffled order) of an array of size N, the task is to find the no of possible array's of the size N which can be made from these elements Examples: Input: arr[] = {5, 2, 3, 5} Output: 2 Explanation: 1st array can be : {2, 3} Its prefix array:{2, 5} Its suffix array:{5, 3} 2nd arr
15+ min read
Difference between Static Arrays and Dynamic Arrays
In the Data structure, we know that an array plays a vital role in having similar types of elements arranged in a contiguous manner with the same data type. According to the concept of array, an array can be defined in two ways as per the memory allocation concept. Types of Arrays:There are basically two types of arrays: Static Array: In this type
5 min read
Maximum OR sum of sub-arrays of two different arrays
Given two arrays of positive integers. Select two sub-arrays of equal size from each array and calculate maximum possible OR sum of the two sub-arrays. Note: Let f(x, l, r) is the OR sum of all the elements in the range [l, r] in array x. Examples : Input : A[] = {1, 2, 4, 3, 2} B[] = {2, 3, 3, 12, 1} Output : 22 Explanation: Here, one way to get m
5 min read
Merge k sorted arrays | Set 2 (Different Sized Arrays)
Given k sorted arrays of possibly different sizes, merge them and print the sorted output.Examples: Input: k = 3 arr[][] = { {1, 3}, {2, 4, 6}, {0, 9, 10, 11}} ;Output: 0 1 2 3 4 6 9 10 11 Input: k = 2 arr[][] = { {1, 3, 20}, {2, 4, 6}} ;Output: 1 2 3 4 6 20 We have discussed a solution that works for all arrays of the same size in Merge k sorted a
7 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Find sub-arrays from given two arrays such that they have equal sum
Given two arrays A[] and B[] of equal sizes i.e. N containing integers from 1 to N. The task is to find sub-arrays from the given arrays such that they have equal sum. Print the indices of such sub-arrays. If no such sub-arrays are possible then print -1.Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {6, 2, 1, 5, 4} Output: Indices in array 1 : 0, 1
15+ min read
Generate all possible sorted arrays from alternate elements of two given sorted arrays
Given two sorted arrays A and B, generate all possible arrays such that the first element is taken from A then from B then from A, and so on in increasing order till the arrays are exhausted. The generated arrays should end with an element from B. Example: A = {10, 15, 25} B = {1, 5, 20, 30} The resulting arrays are: 10 20 10 20 25 30 10 30 15 20 1
12 min read
Count of possible unique arrays after swapping elements at same index of given Arrays
Given two arrays arr1[] and arr2[] with distinct elements of size N.The task is to count the total number of possible combinations after swapping elements at the same index of both the arrays such that there are no duplicates in both the arrays after performing the operation. Examples: Input: arr1[] = {1, 2, 3, 4}, arr2[] = {2, 1, 4, 3}, N = 4Outpu
12 min read
Find count of Alphabetic and Alphanumeric strings from given Array of Strings
Given an array of strings arr[] of size N. Each of the strings contains lowercase English letters or numbers only. The task is to find the frequency of alphabetic and alphanumeric strings in the array. Note: If any string has atleast one number in it, the string is an alphanumeric string. Examples: Input: arr[] = {"abcd", "mak87s", "abcd", "kakjdj"
7 min read
Number of common base strings for two strings
Given two strings s1 and s2, we need to find number of common base strings of two. A substring of a string s is called base string if repeated concatenation of the substring results in s. Examples: Input : s1 = "pqrspqrs" s2 = "pqrspqrspqrspqrs" Output : 2 The two common base strings are "pqrs" and "pqrspqrs". Input: s1 = "bbb" s2 = "bb" Output: 1
6 min read
Count of distinct Strings possible by swapping prefixes of pairs of Strings from the Array
Given an array string[] consisting of N numeric strings of length M, the task is to find the number of distinct strings that can be generated by selecting any two strings, say i and j from the array and swap all possible prefixes between them. Note: Since the answer can be very large, print modulo 1000000007. Examples: Input: N = 2 M = 3 string[] =
6 min read
Distinct strings such that they contains given strings as sub-sequences
Given two strings str1 and str2 of lengths M and N respectively. The task is to find all the distinct strings of length M + N such that the frequency of any character in the resultant string is equal to the sum of frequencies of the same character in the given strings and both the given strings are present as a sub-sequence in all the generated str
6 min read
Count of Palindrome Strings in given Array of strings
Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to return the count of all palindromic string in the array. Examples: Input: arr[] = {"abc","car","ada","racecar","cool"}Output: 2Explanation: "ada" and "racecar" are the two palindrome strings. Input: arr[] = {"def","aba"}Output: 1Exp
5 min read
Count of same length Strings that exists lexicographically in between two given Strings
Given two string S1 and S2 of length L, the task is to count the number of strings of length L, that exists in between S1 and S2, which are lexicographically greater than S1 but smaller than S2. Examples: Input: S1 = "b", S2 = "f" Output: 3 Explanation: These are 3 strings which come lexicographically in between S1 and S2 i.e. "c", "d" &amp; "e"Inp
8 min read
Check whether two strings can be made equal by reversing substring of equal length from both strings
Give two strings S1 and S2, the task is to check whether string S1 can be made equal to string S2 by reversing substring from both strings of equal length. Note: A substring can be reversed any number of times. Example: Input: S1 = "abbca", S2 = "acabb" Output: Yes Explanation: The string S1 and S2 can be made equal by: Reverse S1 in the range [2,
12 min read
Print all Strings from array A[] having all strings from array B[] as subsequence
Given two arrays A[] and B[] consisting of strings, the task is to print the strings from array A[] having all strings in B[] as a subsequence.Examples: Input: A[] = {"geeksforgeeks", "mapple", "twitter", "table", "Linkedin"}, B[] = {"e", "l"} Output: mapple table linkedin Explanation: Both the strings "e" and "l" are subsets in "mapple", "table",
11 min read
Search strings with the help of given pattern in an Array of strings
Prerequisite: Trie | (Insert and Search) Given an array of strings words[] and a partial string str, the task is to find the strings of the given form str from the given array of string. A partial string is a string with some missing characters. For Example: "..ta", is a string of length 4 ending with "ta" and having two missing character at index
12 min read
Print all strings of maximum length from an array of strings
Given an array of strings arr[], the task is to print all the strings of maximum length from the given array. Example: Input: arr[] = {“aba”, “aa”, “ad”, “vcd”, “aba”}Output: aba vcd abaExplanation:Maximum length among all the strings from the given array is 3.The strings having length equal to 3 from the array are “aba”, “vcd”, “aba”. Input: arr[]
7 min read
Append digits to the end of duplicate strings to make all strings in an array unique
Given an array arr[] consisting of N strings, the task is to modify the array by replacing the duplicate strings by appending any number such that all the strings in the array are unique. Examples: Input: S = {"aa", "bb", "cc", "bb", "aa", "aa", "aa"}Output: {"aa", "bb", "cc", "bb1", "aa1", "aa2", "aa3"}Explanation:The output of the second occurren
5 min read
Check if given strings can be made same by swapping two characters of same or different strings
Given an array of equal-length strings, arr[] of size N, the task is to check if all the strings can be made equal by repeatedly swapping any pair of characters of same or different strings from the given array. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { "acbdd", "abcee" } Output: YES Explanation: Swapp
11 min read
Count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array
Given an array arr[] consisting of N strings, the task is to find the pair of strings that is not present in the array formed by any pairs (arr[i], arr[j]) by swapping the first characters of the strings arr[i] and arr[j]. Examples: Input: arr[] = {"good", "bad", "food"}Output: 2Explanation:The possible pairs that can be formed by swapping the firs
13 min read
Convert given Strings into T by replacing characters in between strings any number of times
Given an array, arr[] of N strings and a string T of size M, the task is to check if it is possible to make all the strings in the array arr[] same as the string T by removing any character from one string, say arr[i] and inserting it at any position to another string arr[j] any number of times. Examples: Input: arr[] = {"abc", "abb", "acc"}, T = "
9 min read
Count of isogram strings in given array of strings with length at least K
Given an array arr[] containing N strings and an integer K, the task is to find the number of strings which are isograms and at least of length K. Examples: Input: arr[] = {"abcd", "der", "erty"}, K = 4Output: 2Explanation: All given strings are isograms, but only "abcd" and "erty" are of length at least K. Hence count is 2 Input: arr[] = {"ag", "b
5 min read
Count of Isogram strings in given Array of Strings
Given an array arr[] containing N strings, the task is to find the count of strings which are isograms. A string is an isogram if no letter in that string appears more than once. Examples: Input: arr[] = {"abcd", "derg", "erty"}Output: 3Explanation: All given strings are isograms. In all the strings no character is present more than once. Hence cou
5 min read
Find all Palindrome Strings in given Array of strings
Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to find all palindromic string in the array. Print -1 if no palindrome is present in the given array. Examples: Input: arr[] = {"abc", "car", "ada", "racecar", "cool"}Output: "ada", "racecar"Explanation: These two are the only palindro
6 min read
Make all Strings palindrome by swapping characters from adjacent Strings
Given an array of strings S[] of size X where each string has length N. In one move, you can swap the ith character of two adjacent strings, the task is to find the minimum number of moves to make every string a palindrome. If this is not possible, print -1. Examples: Input: S[] = {"13", "21", "32"}Output: 2?Explanation: We make all the strings pal
10 min read
Check if two strings can be made equal by reversing a substring of one of the strings
Given two strings X and Y of length N, the task is to check if both the strings can be made equal by reversing any substring of X exactly once. If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: X = "adcbef", Y = "abcdef"Output: YesExplanation: Strings can be made equal by reversing the substring "dcb" of string X. Input:
12 min read
Count of strings in Array A that can be made equal to strings in Array B by appending characters
Given two arrays of strings SearchWord[] and FindWord[]. The task is to check how many strings in FindWord[] can be formed after the following operations on as many strings as possible: Pick a string from SearchWord[].Add one English alphabet (that is not present in that string).Rearrange the string as you like.Note: Every alphabet in the SearchWor
13 min read
Concatenating Strings (combining multiple strings into one)
Given two strings str1 and str2, the task is to concatenate these two strings. Given two strings str1 and str2, the task is to concatenate these two strings. Examples: Input: str1 = "hello", str2 = "world"Output: helloworld Input: str1 = "Geeks", str2 = "World"Output: GeeksWorld Approach 1: Using the "+" operatorThe most traditional method of conca
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg