C# - Calculate the Distance Based on Speed and Time

Here, we are going to learn how to calculate the traveled distance based on speed and time in C#? By Nidhi Last updated : April 15, 2023

Here we will read the value of speed and time then calculate the traveled distance and print the calculated distance on the console screen.

C# program to calculate the travelled distance based on speed and time

The source code to calculate the traveled distance based on speed and time is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to calculate the traveled distance 
//based on speed and time.

using System;

class Demo
{
    static int CalculatDistance(int speed, int time)
    {
        int distance = 0;

        distance = speed * time;

        return distance;
    }
    static void Main(string[] args)
    {
        int speed           =   0;
        int timeInHours     =   0;
        int distance        =   0;

        Console.Write("Enter time in hours: ");
        timeInHours = int.Parse(Console.ReadLine());

        Console.Write("Enter speed in km/hours: ");
        speed = int.Parse(Console.ReadLine());
        
        distance = CalculatDistance(speed, timeInHours);
        Console.WriteLine("Traveled distance in km: " + distance);
    }
}

Output

Enter time in hours: 2
Enter speed in km/hours: 60
Traveled distance in km: 120
Press any key to continue . . .

Explanation

Here, we created a Distance class that contains two methods CaclulatDistance() and Main().

In the CalculateDistance() method, we calculated traveled distance using the below formula,
distance = speed * time;

The Main() method is the entry point for the program, here we read the value of time and distance and then calculate the traveled distance using CalculateDistance() method and print the result on the console screen.

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.