Pages

Thursday, August 18, 2016

Java: sum of the first N positive odd integer numbers

Write a fragment of code that will compute the sum of the first n positive
odd integers. For example, if n is 5, you should compute 1 +3 + 5 +7 + 9.

For doing so write the following code:


public static void sumNPositiveOddIntegers() {
 System.out.println("Escriba un numero entero...");
 Scanner kb = new Scanner(System.in);
 int n = kb.nextInt();

 int x = 1;
 int sum = 0;
 for (int i = 0; i < n; i++)
 {
  sum += x;
  x += 2;
  System.out.println(x);
 }
 System.out.println("The sum of first " + n + " positive odd integers is: " + sum);

}


Code explanation:

public static void sumNPositiveOddIntegers(): As we are printing the result we use void.

Scanner kb = new Scanner(System.in): Here we declare the variable kb with the method Scanner in order to read from the keyboard.

int n = kb.nextInt(): Assign to the variable n the integer value from the keyboard.

 int x = 1, sum = 0: Initialize the variables x and sum.

 for(int i = 0; i < n; i++): This loop initializes the variable I with value 0. Then it states: while i is less than n, then the i's variable value will be increasing.

sum += x: the variable sum will be storing the value of x during the loop.

x += 2: x will be increasing in pairs in order to sort the odd numbers. That's way we initialize it with value 1.

System.out.println(x): Prints out the x's value that will be the positive odd integer numbers.

Finally, the last line of code will print the sum of the previous numbers.







PHP: Reverse words

This program is going to read sentences from an archive and then reverse the order of the sentence written on it. Create an archive called input.txt where you will write different sentences and a PHP file index.php were you will write the following code:


<?php
$fh = fopen("input.txt", "r");
while (!feof($fh)) {
 
$test = trim(fgets($fh));
 echo (nl2br(reversed($test) . "\n"));
     if (empty($test) == true) {
            break;      
    }
}
function reversed($test) {

$words = explode(" ", $test);
$reversed = array_reverse($words);
return $testResult = implode(" ", $reversed);
}
fclose($fh);
?>

The above code is going to give you the following results:

Input
Hello world!

Output
world! Hello