Monday, January 13, 2014

For-Loop in Objective-C


So , I bought this book yesterday.

And what I plan on doing is once or twice a week blogging about a chapter or two whilst I relearn objective-c.  We basically covered the first* chapter last week with classes , objects and methods. Go us. So let us start on chapter 2.
*First chapter actually about code

----------------------------------------------------------------------------------------------------------------------------

*Recapping the previous chapter*

So last chapter we learned all about Data-types , objects , methods and classes.

Type float
float  floatingVar = 123.21;
Type int
int integerVar = 19;
Type double
double doubleVar = 2.923e+11
Type char
char charVar = ‘h’
Type id
id hannahObject;

*Recap Over*


So this chapter we are going to talk about looping in objective -c

     There are three different types of ways to loop in Objective-c
  • For Loop
  • While Loop
  • Do statement
But We are only covering For loops today.

----------------------------------------------------------------------------------------------------------------------------

Say we wanted to know the sum of all numbers to 150?
    ex. 1+2+3+4......+150

You could individually add all the numbers but that doesn't seem like it would be very efficient. As we are programmers and we are lazy and that's just wayyy tooo much typing.

This is how you would execute the different loops finding the sum of all numbers to 150.

For loop
#import<Fountdation/Foundation.h>

int main ( int argc , char * argv[])
{
  @autoreleasepool{
     int n , sumNumber;
sumNumber = 0;
for (n = 1; n<=150; n = n+1)
sumNumber += n;

NSLog(@”The sum of the numbers is %i” , sumNumber);

   }
return 0;
}
The format of a for loop is

for( init_expression ; loop_condition; loop_expression)
program statements

The three expressions inside of the parentheses are the expressions that control the for loop.

init_expression: used to set up values before the loop begins. (ex. N = 1; )
loop_condition: Used to state the conditions for the loop to execute. (ex. N<= 150;)
loop_expression: This is evaluated after each time the program statements have been executed. (n = n + 1;)

This is a very basic explanation of for loops. For Loops can be very powerful when used correctly. But you must be careful not to fall into the infamous infinite loop. This is when your loop condition is never met and causes the loop to run forever.

Tomorrow I will chat about While loop!

No comments:

Post a Comment