We can either display the entire 1D Array to know what the elements are or we can use the method of indexing in order to display only those Array values which we require.
Note: Array Indexing always starts from 0.
Example 1
COPY CODE
# To print a single element of an array
int arr [5] = {1, 3, 5, 7, 9} ;
cout << arr[3] ; // arr[3] i.e. index 3 of array will print the value 7
Manipulation of 1D Array Elements
If we want to change a specific element stored in an array, we will use the following method:
Example
COPY CODE
#include
using namespace std;
int main()
{
int arr [7] = {10, 20, 30, 40, 55, 60, 70} ;
cout << "5th value of Array Before updation : \n" << arr[4] ;
arr [4] = 50 ;
cout << "\n 5th value of Array After updation : \n" << arr[4] ;
}
Output
COPY CODE
5th value of Array Before Updation :
55
5th value of Array After Updation :
50
We can use 1D Arrays to find out the sum of all elements and the average of the array by using the following method:
Declaration of Strings in 1D Arrays
One Dimensional Array not only includes numeric data but can also contain alphabetic values. Strings are nothing but a collection of characters, or we might also say Strings are an array of characters. Strings can also be stored in Arrays by using the char data type. The syntax for initializing a string array is as follows:
Syntax
COPY CODE
char str [20] = {"Hello World"} ;
cout << str ;
Output
COPY CODE
Hello World
Using Strings in 1D Array, we can perform various operations such as finding the length of a string, comparing 2 strings, copy a string, reverse the string, delete specific words/alphabets from the strings, count the number of words/letters, etc.
Do'stlaringiz bilan baham: |