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.
Program:
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.
Output:
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.