Skip to content

Loops

Basic Loops

Below are two example problems involving loops. Note that there may be more valid solutions than those provided. Ensure you understand the solutions, then write programs to solve the remaining problems.

Problem 1

Write a program that:

  1. Prompts the user to enter an integer N.
  2. Prompts the user to enter N floating-point numbers (i.e., values of type double).
  3. Calculates and prints the average of the entered numbers.

To calculate the average, use the formula:

Average=Sum of valuesNumber of values\text{Average} = \frac{\text{Sum of values}}{\text{Number of values}}

Here, “Sum of values” refers to the total of all floating-point numbers entered by the user, and “Number of values” refers to N.

Problem 2

Write a program that:

  1. Prompts the user to enter an integer.
  2. Checks if the entered integer is a prime number.
  3. Prints:
    • “That number is prime!” if the number is prime.
    • “That number is composite!” if the number is not prime.

An integer XX is considered prime if it is only divisible by 1 and itself. Examples of prime numbers include: 1, 2, 3, 5, 7, 11, 13, 17, and 19.

A composite number (non-prime) is divisible by other integers besides 1 and itself. Examples:

  • 9 is composite because it is divisible by 3.
  • 15 is composite because it is divisible by 3 and 5.
  • All even numbers greater than 2 are composite because they are divisible by 2.

To check divisibility of an integer aa by another integer bb , use the following boolean expression:

a % b == 0

This expression evaluates to true if a is divisible by b.

You only need to check divisors smaller than XX . Numbers cannot be divisible by integers larger than themselves.

Problem 3

Write a program that:

  1. Prompts the user to enter 10 integers.
  2. For each entered integer, computes and prints its factorial.

he factorial of a number nn is represented in mathematics as n!n! (this exclamation point denotes the factorial operator).

The factorial of nn is defined as the product of all positive integers less than or equal to nn :

n!=n×(n1)×(n2)××2×1n!=n×(n1)!\begin{align*} n! &= n \times (n-1) \times (n-2) \times \dots \times 2 \times 1 \\ n! &= n \times (n-1)! \end{align*}

For example, 5!=5×4!=5×4×3×2×1=1205! = 5 \times 4! = 5 \times 4 \times 3 \times 2 \times 1 = 120 . The value of 0!0! is 11 .

Use a loop to perform the multiplication required to compute the factorial for each number.

Approximating Pi

Imagine a unit circle (a circle with a radius of 1) inscribed within a square. The setup looks like this:

The area AA of a circle with radius rr is calculated using the formula A=πr2A = \pi r^2 . For a unit circle, this becomes: A=π(1)2=πA = \pi (1)^2 = \pi

Since the radius of the circle is 1, the side length of the square that encloses the circle must be 2. The area of the square is: 22=42^2 = 4

Let P represent the ratio of the area of the circle to the area of the square. For this scenario:

P=π4P = \frac{\pi}{4}

By rearranging the equation algebraically, we get:

π=4P\pi = 4P

This relationship shows that if we can approximate PP , we can multiply it by 4 to approximate π\pi .

Monte Carlo Methods

Monte Carlo methods are a class of computational algorithms that rely on random sampling to approximate solutions. In this case, our goal is to approximate P using a Monte Carlo method.

Here’s the approach:

  • If we randomly sample Cartesian points within the square, some proportion of these points will also fall inside the circle.
  • If the sampling is uniform (i.e., every point within the square is equally likely to be chosen), then the probability of a point landing inside the circle is exactly equal to PP .
  • To approximate PP , we simply need to sample many points within the square and calculate the proportion of those points that fall inside the circle.

Coordinates of the Square and Circle

  • The circle is centered at the origin (0,0)(0, 0) .
  • The square has a side length of 2, with its corners at the following coordinates:
    • Top-left: (1,1)(-1, 1)
    • Top-right: (1,1)(1, 1)
    • Bottom-right: (1,1)(1, -1)
    • Bottom-left: (1,1)(-1, -1)

Sampling Points

To randomly sample a point within the square:

  • Generate an X-coordinate within the range [1,1][-1, 1]
  • Generate a Y-coordinate within the range [1,1][-1, 1]
  • Together, these values form the sampled point (X,Y)(X, Y)

Checking if a Point is Inside the Circle

A point (X,Y)(X, Y) lies inside the circle if it satisfies the circle’s equation:

X2+Y21X^2 + Y^2 \leq 1

Implementation

Implement the Monte Carlo method described above to approximate PP and π\pi .

Use the Monte Carlo method to sample 100,000 random points within the square. This provides a sufficiently large number of samples for an accurate approximation. Determine the proportion of sampled points that fall inside the circle. This proportion represents PP . Multiply PP by 4 to calculate an approximation of π\pi . Print the calculated value of PP to the standard output. Print the approximation of π\pi to the standard output.

Avoid using integers to sample coordinates, as truncation would lead to a highly inaccurate approximation. Instead, use floating-point values (e.g., double).

To randomly sample a floating-point value within a specific interval [a,b][a, b] , use the following expression:

(static_cast<double>(rand()) / RAND_MAX) * (b - a) + a