Search⌘ K
AI Features

Solution: Physics Projectile Simulation

Explore how to build a physics projectile simulation in C# by using variables, loops, input validation, and mathematical formulas. Understand program flow control through infinite loops and break statements to create a responsive and accurate simulation.

We'll cover the following...
const double gravity = 9.8;
double time = 0;

Console.WriteLine("=== Projectile Simulation ===");
Console.Write("Enter initial velocity (m/s): ");

if (double.TryParse(Console.ReadLine(), out double velocity))
{
    Console.WriteLine("\nTime (s)\tHeight (m)");
    Console.WriteLine("--------------------------");

    while (true)
    {
        // Formula: h = (v * t) - (0.5 * g * t^2)
        double height = (velocity * time) - (0.5 * gravity * Math.Pow(time, 2));

        // Format negative height to 0 for the final impact print
        double displayHeight = height < 0 ? 0 : height;

        // Using concatenation as interpolation is not yet taught
        Console.WriteLine(time + "\t\t" + displayHeight);

        // Exit Strategy: Stop if we are past the start (t > 0) and hit the ground (h <= 0)
        if (time > 0 && height <= 0)
        {
            break;
        }

        time++;
    }

    Console.WriteLine("--------------------------");
    Console.WriteLine("The ball has hit the ground.");
}
else
{
    Console.WriteLine("Invalid input. Please enter a number.");
}
The complete solution for the projectile simulation exercise
...