sizeof - Sum & Product Calculator

sizeof - sum & product calculator

Using the sizeof operator, make a program that prompts the user to fill an array in a loop.

The loop should run once for each element in the array.

When all the inputs are gathered define the variables float sum and float product. Use another for-loop to get the sum and product of the numbers in the array.

Print the results.

Test your program by changing the array size without modifying anything else to see if it still works.

Answer

#include <iostream>

int main() {

	float numbers[5];
	int array_size = sizeof(numbers) / sizeof(numbers[0]);

	for (int i = 0; i < array_size ; i++) {
		std::cout << "Enter a number: ";
		std::cin >> numbers[i];
	}

	float sum = 0;
	float product = 1;
	for (int i = 0; i < array_size; i++) {
		sum += numbers[i];
		product *= numbers[i];
	}

	std::cout << "Sum: " << sum << std::endl;
	std::cout << "Product: " << product << std::endl;
}

Both for-loops make use of i < sizeof(numbers) to run untill i is out of the range of possible indexes.

Questions