Array Elements

How do you see what is the first, second, third... element of an int array? After, how do you delete an element of an array.

1
2
int a[10]={3,567,23,64,13,235,65,1,76,23};
//how to see every element there is 


Thanks!!!!!!!!!!!!!!!!
The first element is a[0], the second is a[1], and so on, and the last (10th) element is a[9].
Note that the first element is actually position zero, not position one.

So if you wanted to print all of the elements, you could use a for loop:
1
2
for (int i = 0; i < 10; ++i)
    std::cout << a[i] << ' '; // Prints all of the elements, separated by spaces 

You can't really "delete" an element per se, but you can shift all of the elements after it down a spot by assigning every element after that to the previous array position.
That is, if you wanted to "delete" the 5th element (a[4]), then you would assign the value of a[5] to a[4], a[6] to a[5], and so on.
This leaves the last element, a[9], as a sort of "open spot", though it's still part of the array and you can still access/modify it just like any other array element.
So if you want to completely forget about that last element, you can keep track of a size variable and update it accordingly, and have the rest of your program use that variable to judge where the end of the array is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int array[10] = {1,2,3,4,5,6,7,8,9,10};
int size = 10; // Size of the array

// Print the elements
for (int i = 0; i < size; ++i)
    std::cout << array[i] << ' ';
std::cout << '\n';

// Delete the 5th element (a[4])
for (int i = 5; i < size; ++i)
    array[i-1] = array[i]; // Move the 6th-10th elements down one
--size; // Update size accordingly

// Print elements again
for (int i = 0; i < size; ++i)
    std::cout << array[i] << ' '; // This time 'size' is 9, so the last element won't be printed 
Thanks a lot!
Last edited on
What if I wanted to do the same thing but using words, like entering which word to remove?
Same idea.
Just with std::string instead of int.
But for the comparing, you can't compare ints with strings. Can you also make a program to show me? Thanks sooooo much.
most deff cant compare ints with strings //Demonstrates the standard class string.
2 #include <iostream>
3 #include <string>
4 using namespace std;
5 int main( )
6 {
7 string phrase;
8 string adjective("fried"), noun("ants");
9 string wish = "Bon appetite!";
10 phrase = "I love" + adjective + " " + noun + "!";
11 cout << phrase << endl
12 << wish << endl;
13 return 0;
14 }
thanks
Topic archived. No new replies allowed.