-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion3.cpp
More file actions
42 lines (35 loc) · 1.5 KB
/
question3.cpp
File metadata and controls
42 lines (35 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
* Using functions, write a program to compute the area and perimeter of a square.
* The program should ask the user to enter a number corresponding to the side length
* of the square and display the area and perimeter of the square
*/
#include <iostream>
// Function to calculate the perimeter of the square based on the length provided
double calculatePerimeter(double sideLength) {
return sideLength * 4;
}
// Function to calculate the area of the square based on the length provided
double calculateArea(double sideLength) {
return sideLength * sideLength;
}
int main() {
// Declaration of variables
double sideLength;
// Prompt the user to enter the side length of the square
std::cout << "Enter the length of the square: ";
std::cin >> sideLength;
if (std::cin.fail()) {
// Gracefully handle a case where the user enters a string.
std::cout << "Invalid input! Please enter a number.";
return 1;
} else if (sideLength < 0) {
// Gracefully handles a case where the side length entered is less than 0.
std::cout << "Side length cannot be negative!";
return 1;
} else {
// Display the perimeter and the area of the square
std::cout << "The perimeter of the square with length " << sideLength << " is " << calculatePerimeter(sideLength) << " units\n";
std::cout << "The area of the square with length " << sideLength << " is " << calculateArea(sideLength) << " square units" << std::endl;
return 0;
}
}