Calculate the cost of a carpet.
Watch this video to learn about the new concepts shown in the program:
The new commands used in this program and others that may be useful. Select them below to learn more:
int x = Convert.ToInt32(y);Casts (converts) the string y into a 32-bit integer x. Integers are whole numbers, positive, negative or zero.
double x = Convert.ToDouble(y);Casts (changes) y into a decimal x. Decimals are also called doubles, floats or real numbers.
string x = Console.ReadLine();Assigns x to be an input from the keyboard. Print a prompt first with Console.WriteLine(y);.
return x;Returns the value x from a subprogram so that it can be used elsewhere in the program.
+ add
- subtract
* multiply
/ divide
$"..." string interpolationEmbeds variables in output strings. E.g. assuming name = "Dave" and age = 18, the statement
Console.WriteLine($"Hello {name}. You are {age} years old.");
outputs Hello Dave. You are 18 years old.. You can also join strings and variables with +, e.g. "Hello " + name.
Questions to think about with this program to check your understanding:
Explain the purpose of the Convert.ToInt32 command used to read the width, length and price.
Convert.ToInt32 converts the input from the keyboard, which is always text (a “string”), into a whole number (an “integer”) so that it can be used for mathematical calculations. This is known as “casting”.
Explain why a subprogram was used for carpet_cost instead of writing the code directly inside Main.
Breaking a program down into subprograms is called decomposition. It makes it easier to write different parts of the program a step at a time. It is easier to read the code. It allows a section of code to be reused more easily.
Change the program below so that it:
Enter the width of the room to nearest meter:
2
Enter the length of the room to nearest meter:
3
Enter the price of the carpet per m2:
2
The total cost is: £ 79.0
// Carpet cost program
using System;
class Submission
{
---
// -------------------------
// Subprograms
// -------------------------
static double carpet_cost(int width, int length, double price)
{
---
double carpet = width * length * price;
int underlay = width * length * 2;
---
int grippers = width + length;
int fitting = 50;
return carpet + underlay + grippers + fitting;
---
}
---
// -------------------------
// Main program
// -------------------------
public static void Main(string[] args)
{
---
Console.WriteLine("Enter the width of the room to nearest meter:");
int width = Convert.ToInt32(Console.ReadLine());
---
Console.WriteLine("Enter the length of the room to nearest meter:");
int length = Convert.ToInt32(Console.ReadLine());
---
Console.WriteLine("Enter the price of the carpet per m2:");
double price = Convert.ToDouble(Console.ReadLine());
---
Console.WriteLine("The total cost is: £ " + carpet_cost(width, length, price));
---
}
---
}