Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a class named Car.
C++
class [1] { public: int speed; };
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using a different class name that doesn't match the problem description.
Forgetting to write the class name after the 'class' keyword.
β Incorrect
The class is named Car, so the correct keyword after 'class' is 'Car'.
2fill in blank
mediumComplete the code to add a constructor that sets the speed of the Car.
C++
class Car { public: int speed; Car([1] s) { speed = s; } };
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using float or string instead of int for speed.
Forgetting to specify the type of the constructor parameter.
β Incorrect
The speed is an integer, so the constructor parameter should be of type int.
3fill in blank
hardFix the error in the method that increases the speed by a given amount.
C++
class Car { public: int speed; void accelerate(int amount) { speed [1] amount; } };
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using '-=' which decreases speed instead of increasing.
Using '*=' or '/=' which multiply or divide speed.
β Incorrect
To increase speed by amount, use the '+=' operator.
4fill in blank
hardFill both blanks to create a method that returns true if the car is moving.
C++
class Car { public: int speed; bool isMoving() { return speed [1] [2]; } };
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using '==' instead of '>' which only checks if speed equals zero.
Using '<' which checks if speed is less than zero, which is not correct here.
β Incorrect
The car is moving if speed is greater than 0, so use 'speed > 0'.
5fill in blank
hardFill all three blanks to create a method that sets the speed only if the new speed is valid (non-negative).
C++
class Car { public: int speed; void setSpeed(int newSpeed) { if (newSpeed [1] [2]) { speed [3] newSpeed; } } };
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using '>' instead of '>=' which excludes zero as valid speed.
Using '==' which checks equality instead of comparison.
Using '+=' instead of '=' which would add instead of set.
β Incorrect
We check if newSpeed is greater or equal to 0, then assign it to speed using '='.