Array And For Loop Practice

by Devansh


Posted on 22 Oct 2018 07:10:07 (1 month ago)




In coding world, data structures and for loop practice are very important. If you have a good commands in loop and arrays than you can master any logics.

In this section there are some basic array questions which commonly asked in interview. I am using PHP to show the logics. I will update this post regularly. If you have any array or loop questions than post in comment i will update that question to this post.

/****************************************************************************************************
 * End Point Subtraction
 ****************************************************************************************************
 *
 *             +-----------------+
 *             |   +---------+   |
 *             |   |   +-+   |   |
 *             |   |   | |   |   |
 *     $arr = [1,2,3,4,5,6,7,8,9,0] => $arr = [1,-7,-5,-3,-1]
 *               |   |     |   |
 *               |   +-----+   |
 *               +-------------+
 *
 ****************************************************************************************************/
function arrayPractice1($arr) {
	$totalElements = count($arr);
	for ($i=0; $i<$totalElements; $i++) {
		if ($i < $totalElements/2) {
			$arr[$i] = $arr[$i] - $arr[$totalElements-1-$i];
		} else {
			array_pop($arr);
		}
	}
	return $arr;
}
/****************************************************************************************************
 * Alternate Addition
 ****************************************************************************************************
 * 
 *             +---+---+---+---+
 *             |   |   |   |   |
 *     $arr = [1,2,3,4,5,6,7,8,9,0] => $arr = [25,20]
 *               |   |   |   |   |
 *               +---+---+---+---+
 *
 ****************************************************************************************************/
function arrayPractice2($arr) {
	$totalElements = count($arr);
	$lastIndex = count($arr)-1;
	$arr[$lastIndex+1] = 0;
	$arr[$lastIndex+2] = 0;
	for ($i=0; $i<$totalElements; $i++) {
		if ($i%2 == 0) {
			$arr[$lastIndex+1] = $arr[$lastIndex+1] + $arr[$i];
		} else {
			$arr[$lastIndex+2] = $arr[$lastIndex+2] + $arr[$i];
		}
	}
	for ($i=0; $i<$totalElements; $i++) {
		array_shift($arr);
	}
	return $arr;
}