It looks like you're using an Ad Blocker.

Please white-list or disable AboveTopSecret.com in your ad-blocking tool.

Thank you.

 

Some features of ATS will be disabled while you continue to use an ad-blocker.

 

Programming Lessons Part III: Arrays and Loops

page: 1
2

log in

join
share:

posted on Sep, 5 2008 @ 04:08 PM
link   
Part III: Arrays and Loops
Alright, we've looked at dealing with "single" variables, now let's take a look at dealing with a list of variables -- arrays. Arrays are kind of different beasts, especially when you're just getting your feet wet with programming. No worries though; we'll get them figured out. As always, don't be afraid to ask questions if you don't understand something. We're start to get into some pretty different stuff now, and it's no big deal if you don't understand. Let's get started, shall we?

First off, let's look at declaring an array. This looks almost like your previous variable declaration, but with a slight twist:

int[] myNums;

See the '[]'? That tells the compiler that we're wanting to create an array of integers. Of course, as this stands right now, we don't really have an array, so let's create one:

int[] myNums = new int[5];

This line tells the compiler that we want to create an array that contains 5 integers. If we wanted an array of 20 integers, we'd replace the 5 with a 20; for 785 integers, we'd replace it with 785; for 36,769 integers, well ... you get the idea.

Okay, we've got our list of integers; how do we do something with them? Here's where it gets a little tricky. A long, long time ago, in a computer lab far, far away, some computer geek thought it'd be fun to screw with everyone's minds. Instead of accessing the items in an array using the number you'd expect -- 1 for the first element, 2 for the second, 3 for the third, so on ad nauseum -- he/she decided to make it nice and confusing by forcing us to access the items using one less than the number you'd expect. So, instead of using 1 for the first element, you use 0. For the second element, you use 1. For the third, you use 2. Got it? Yeah, took me a while too (still get mixed up sometimes, if I'm not thinking straight). Anyways, here's how you access the elements in an array:

int[] myNums = new int[5];
myNums[0] = 123;
myNums[1] = 234;
myNums[2] = 345;
myNums[3] = 456;
myNums[4] = 567;

(Of course, you can create arrays of any kind of data type -- strings, chars, bools, floats, and all the ones we haven't covered, too.)

Kinda simple, no? And, as you can see, the last element in the array is accessed using one less than the length we gave the array -- 4, instead of 5. Keep that in mind, because if you try to use 5 to access the array, you're actually trying to access the sixth element, which doesn't exist. That's generally frowned upon by the computer, and in some programming languages (not C#, thankfully), you can even mess up your program. Go ahead and try it and see what happens -- odds are better than even money you'll get what they call an exception (basically just an error -- for the most part, you don't want those, and the situations where you'll appreciate them are far away in your future). So, for future reference, always check to make sure that you know how long your array is and how you're trying to index it. In other words, don't take a long walk off a short array
(Okay, that was stupid, but programmers aren't exactly known for their biting wit...)

As a brief aside, the way that arrays are stored in memory, the "one-less" method of accessing them kinda makes sense. You see, the items are stored one after the other, and the variable name that you're using -- myNums in this example -- refers to the first element, element 0. When you use the number -- programmers call it an index, or an indexer -- you tell the compiler that you're trying to access the first element, but offset by the number you've given it. Offset by 0 items would be the original item; offset by 1 item would be the second item; offset by 2 would be the third. Make sense? Hope so; it's kinda hard to explain. (Also, I'm not 100% sure that C# really stores arrays in this manner, but the syntax is based on the grand-daddy of big-name programming languages, C, and C stores arrays in that way.)

Getting Loopy
When you start dealing with arrays, you're going to get pretty tired of writing out 20 lines for initialization for a 20-element array or 20 lines to process each item every time you want to do something with it. It gets old fast, believe me. Thankfully, there's a way to make things a little easier, and that's by using loops. Let's take a quick look at a "for" loop to see what we're talking about here:

for (int i = 0; i < 10; i++) [
Console.WriteLine(i);
]

That's a little cryptic, huh? It's not so bad when you break it down though, even though I snuck a new operator (++) in on you. Basically, this construct says the same as this:

1. Initialize a variable named 'i' to 0.
2. While 'i' is less than 10,
a. Print 'i' to the console.
b. Increment 'i'.

(The '++' operator is called a "post-fix increment" operator. Basically, it means to increase the value of the variable it's working with by 1. It's the same, in this case, as saying i = i + 1. There's a similar operator for subtraction, '--', which is the same as i = i - 1.)

Like I said, this is great when dealing with arrays. Check out the following code:

int[] myNums = new int[10];
for (int x = 0; x < 10; x++) [
myNums[x] = 2 * x;
]

for (int x = 9; x >= 0; x--) [
Console.WriteLine(myNums[x]);
]

Kinda cool, huh? Okay, we went backwards in the second loop there -- did you catch that? We started at 9, because we're using 'x' as our indexer, and starting at 10 would put us outside the array -- myNums[10] actually refers to the 11th element, which doesn't exist. Then we printed the value of myNums[x], and decreased (or, more formally, decremented) x. If x is bigger than or equal to 0, we repeat the process.

Make sense?

There's a couple of other loops I want to touch on briefly. I personally don't use them anywhere near as often as the for loop, but they're still worth more than their weight in gold when you need them. Here's the first:

bool myBool = true;
while (myBool) [
// do stuff
myBool = false;
]

This one is much easier to read than the for loop -- basically, what you're doing is repeating everything inside the body of the loop (between the '[]') while the value of myBool is true. When myBool is set to false, the loop will stop after it gets to the last ']' and the rest of your program will continue.

I also threw something else new at you -- the line that begins with '//' is called a comment. There's two kinds of comments in C#, but they both have the same purpose -- the compiler ignores the stuff that you "commented out". The one I used here is a single-line comment; from the // until the end of the line, the compiler doesn't care what I put there -- notes to other developers, suggestions for improvements, discussion of politics, whatever. Completely ignored. The other kind of comment is a block comment, and it's marked by /* */. It can span multiple lines, and everything in between /* and */ is ignored. Seriously, use them as much as possible to describe what it is you're doing. It's probably the best habit you can get into when you're learning to develop software (although I, and many developers much better than me, admittedly forget about them more often than not unfortunately...) Anyways...

The last loop I want to discuss is a variation on the while loop. If you look at the previous example, if I'd set myBool to false, nothing in the loop would've executed. Sometimes you don't want that -- sometimes you want the code to execute at least once, whether the condition is true or not -- maybe the code in the loop generates the condition or something. That's when you use the 'do-while' loop. Pretty simple:

bool myBool = false;
do [
int i = 5;
if (i > 10) [
myBool = true;
] else [
myBool = false;
]
] while (myBool);

See, here the code will execute once and stop. If you go in there and change i to 20, the code will just keep executing.

Okay, between lesson two and this one, I really am getting a bit loopy now, so I'm going to tie this one up. I'm available for any questions, just make sure not to spill the punch that's in the hallway as you mingle with your fellow classmates


Edit: unfortunately, in writing this, I forgot that [ i ] is bbCode for italics... Should be fixed now though.

[edit on 9/5/2008 by MCory1]

[edit on 9/5/2008 by MCory1]




posted on Sep, 10 2008 @ 08:52 AM
link   

Originally posted by MCory1
Part III: Arrays and Loops

int[] myNums = new int[5];
myNums[0] = 123;
myNums[1] = 234;
myNums[2] = 345;
myNums[3] = 456;
myNums[4] = 567;

(Of course, you can create arrays of any kind of data type -- strings, chars, bools, floats, and all the ones we haven't covered, too.)



Is it necessary to give array values to each location seperately cant it be given together,


Good job, keep it up.



posted on Sep, 10 2008 @ 10:03 AM
link   
Not exactly sure what you mean; could you elaborate a little bit? Like give an example of what you're expecting to be able to do?



posted on Sep, 11 2008 @ 01:11 AM
link   
Iam asking while assigning values to the array, can the values be given in one single input statement instead of having a seperate statement for each array variable.



posted on Sep, 11 2008 @ 04:18 PM
link   
reply to post by peacejet
 


Do you mean something like this?

myNums[0,1,2,3,4,] = 123,234,345,456,567;



posted on Sep, 11 2008 @ 07:28 PM
link   
Yes, I meant that only, but the values should be in this [], am I correct.



posted on Sep, 12 2008 @ 04:33 PM
link   
reply to post by peacejet
 


The quickest way of creating an array and assigning values is like this (at least according to Microsoft's documentation
)

int[] myNums = new int[5] [123, 234, 345, 456, 567];

It can be done in two steps.

int[] numbers;
numbers = new int[] [ 1, 2, 3, 4, 5 ];

I don't know if there is other way of doing it, I don't use C#, just tried it with Visual C# 2005 Express Edition and it worked.



posted on Sep, 12 2008 @ 05:39 PM
link   
Holy crap! A (Java?) programming lesson thread!? That's way cool. I am up to CS 301 (the third course in Java) at my college. Thanks for all your hard work!





posted on Sep, 12 2008 @ 07:49 PM
link   
Yes that what I meant I used that in Visual studio 2005 and it worked and even my C# book said that was the correct format



posted on Sep, 12 2008 @ 07:50 PM
link   
reply to post by they see ALL
 

This is not Java programming, it is actually C# the basic of Java, if you know C# then java will be a breeze for you.



posted on Sep, 13 2008 @ 05:33 AM
link   
reply to post by peacejet
 


The inverse is also true, if you know Java C# will be easy to learn.



new topics

top topics



 
2

log in

join