Subscribe to Invariance_Under_Translation        RSS Feed
-----

Arrays

Icon Leave Comment
Alright, my last entry went over some basic concepts you will see when learning to code. You are free to take that program and munipulate it, try to make it better :) You should have an idea about how to assign variables, how control structures can be used to effect the flow of a program and how sub functions can be used to isolate calculations and create a more error proof and easier to troublshoot program.

By the way, i would highly recommend using this website to assist in your learning. Great tutorial for introducing C++ to the new coder.

Anyways, on to my next subject, Arrays. I will start first by introducing the syntax of an array. This is similair to assigning variables, but arrays allow the assignment of multiple like parameters using a reference to an index in a sequential segment of memory. Here is an example below;

int array1[];



This is a simple declaration of an array. Arrays store data though, so lets first decide how large we would like our array to be.

int array[5];



This has assigned an array that can store five variables, but when we go to reference those variables we will start at 0.

int array1[0] = {21};



Therefore, when assigning values to an array or referencing those values we will only use 0 through 4 on an array that has been declared to store 5 variables.
This applies to any declaration of an array.

int array1[5];
int array1[0] = {5};
int array1[1] = {10};
int array1[2] = {15};
int array1[3] = {20};
int array1[4] = {25};



As you can see, we declared an array that contains five storable memory blocks. We start at zero when assigning variables to an array, and the same applies to referencing data within an array.

int array1[5] = {5, 10, 15, 20, 25};
cout<<array[2];



This will give us an output of 15, since we are referencing the third block in the array. Below is a complete use of an array in a program.

#include<iostream>

using namespace std;

int main()  {

int array1[5];

cout<<"Please enter five numbers you would like to store in an array."<<endl;

for (int n = 0; n < 5; n++) {
cin>>array1[n];
 }
cout<<endl;

cout<<"Here are the numbers that you stored: ";
for (int j = 0; j < 5; j++) {
cout<<array1[i];
}
cout<<endl;

cin.get();
}



We created an array of size 5, and we used a for-loop to allow the user to input a number into each of the five empty blocks in the array.
Try typing out your own array by statically assigning variables, and then modify it to dynamically assigning user input.

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

January 2018

S M T W T F S
 123456
78910111213
14151617181920
21 22 2324252627
28293031   

Tags

Recent Entries

Recent Comments

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)