use of array

Iam new to C++ programming, can any one help me please how to use array and write a simple program in C++
1
2
3
4
5
int main()
{
    int A[10] = {1,2,3,4,5,6,7,8,9,10};  //set up an 10 element array
    int sum = A[0] + A[9];  //add the first and the last element
}
I had some time on my hands, so here's a quick tutorial. It just covers the basics, and Darkmaster is right, if you already know what you want inside of the array and what order they should be in then you should initialize it the way he did.

Sorry about the bit with pointers, but it's good to get an idea that they're out there, they can be a little tough to wrap your head around and I don't really say anything important about them, I just show one example using them. I don't know, something to keep in mind I guess.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string wait;
	
	string sentence[10]; //create a string array of up to 10 sentences
	sentence[0] = "Hello world "; //arrays always start with [0]
	sentence[9] = " End of array"; //I initialized the array with 10 spots, so the last array number is [9]
	sentence[3] = " This was initialized third ";
	sentence[2] = " woohoo, ";

	cout<<"You treat an array variable like any other variable" <<endl
		<<"It doesn't matter what order you initialize them in, or when you read from them"<<endl
		<<"if you don't place a value in them then they are initialized as blank; \n"<<endl;
	cout<<sentence[0]<<sentence[3]<<sentence[2]<<sentence[9]<<endl;

	cout<<"Next we use a while loop to read your whole array; \n";
	int i = 0;
	while(i<=9)//It is important not to go past your last variable because you would get an error
	{
		cout<<sentence[i];//the place holder can be replaced with another variable (very handy)
		i++; //increase the value of your place-holder variable
	}

	cout<<"\n\nNow a while loop that puts the word \"NEW\" in all the array's variables that we left blank;"<<endl;
	 i = 0;
	while(i<10) //this is the same argument as the while loop above
	{
		if(sentence[i]=="") // if the variable was left blank...
		{
		sentence[i] = " NEW "; //then replace the value with the word "NEW"
		}
		i++; //increase the value of your place-holder variable
	}


	cout<<endl<<"\nThis is not important now, but here's a loop using pointers to arrays to show it works;"<<endl;
	//This might go beyond what you're ready for but just a quick look at pointers to arrays
	//normal variables require you to initialize pointers but arrays have them all ready to go
	i = 0;
	while(i<10)
	{
		cout<<*(sentence +i);
		i++;
	}
	cin>>wait;
	return 0;
}
Last edited on
check out the array tutorial: http://www.cplusplus.com/doc/tutorial/arrays/

and also have a look at vectors, they are more powerful
http://www.cplusplus.com/reference/vector/vector/
Topic archived. No new replies allowed.