Monday, January 27, 2014

ITERATING WITH FOR LOOPS

ITERATING WITH FOR LOOPS:
In previous post we understand basic execute anonymous and check the governor limits. The purpose of following example to understand for loop and if conditions

Example 1:
// Use a For loop to go through all the integers between 0 and 6
//  and output the name of the corresponding day of the week.
//  0 = 'Sunday', 1 = 'Monday', etc...
for(Integer dayNumber = 0; dayNumber <=6; dayNumber++){
 if(dayNumber==0){
   System.debug('Sunday');
 } else if(dayNumber==1){
   System.debug('Monday');
 } else if(dayNumber==2){
   System.debug('Tuesday');
 } else if(dayNumber==3){
   System.debug('Wednesday');
 } else if(dayNumber==4){
   System.debug('Thursday');
 } else if(dayNumber==5){
   System.debug('Friday');
 } else if(dayNumber==6){
   System.debug('Saturday');
 }
}

Example 2:
/* Fibonacci Sequence: The first two Fibonacci numbers are 0 and 1 and then the next Fibonacci number is found by adding the previous two together  */

// Setup the initial variables to hold the old number, current number, and fibonacci number
Integer oldNumber = 0;
Integer currentNumber = 1;
Integer fibonacciNumber = 0;

// use a loop to output all the fibonacci numbers between 0 and 100
while (fibonacciNumber < 100) {
     
      System.Debug(fibonacciNumber);  // output the Fibonacci number

      // calculate the next fibonacci number by adding the
      // current number to the old number
      fibonacciNumber= currentNumber + oldNumber;
     
      // now set the new values of the old and current numbers
      oldNumber = currentNumber;
      currentNumber = fibonacciNumber;
}

Example 3: This example shows calculating data with primitives
/* SNIPPET 1 */
Boolean b;
Boolean bIsNull;
if(b == null){
  bIsNull = true;
} else {
  bIsNull = false;
}
System.debug(bIsNull);


/* SNIPPET 2 */
// Declare a string = 'He'
String myString1 = 'He';

// Declare a string = 'llo'
String myString2 = 'llo';

// Add the two strings you declared above together into a variable named s
String s = myString1 + myString2;

Boolean b;
if(s=='hello'){
  b = true;
} else {
  b = false;
}
System.debug(b);


/* SNIPPET 3 */
Integer i = 1;
Integer j = 2;
while(i < 3){
  j=i*j;  // Set j equal to i multiplied by j
  i++;    // Increment the i variable by 1
}
System.debug('The integer j = ' + j);

No comments:

Post a Comment