Warm-up Exercises
-
Explain Boolean type
bool
and the meaning of logical operations AND (&&
), OR (||
) and negation (!
). Provide a small example.Solution
The Boolean data type holds either of the two values
true
orfalse
. The AND (&&
) and OR (||
) operators are used to evaluate multiple conditions. The AND (&&
) returnstrue
if all conditions are true, and the OR (||
) operator returnstrue
if at least one of them is true. The negation operator (!
) changes a Boolean value into its opposite.Example: ``` bool b1 = true, b2 = false;
Console.Write(b1 && !b2); // Displays true Console.Write(b1 || b2); // Displays true ```
-
Write a statement that declares a variable of type
int
and sits its value to 3.Solution
int num = 3;
Questions
-
Write a statement that initializes a variable named
myHeightInMeters
to your height in meters. What should be the datatype ofmyHeightInMeters
, and why?Solution
decimal myHeightInMeters = 1.74m;
The datatype should bedecimal
because a person’s height in meters most likely needs the precision afforded by the decimal type. -
What is wrong with the following? Will the error(s) appear at compilation time, or at execution time?
int age; Console.WriteLine("Please enter your age:"); age = Console.ReadLine();
Solution
Console.ReadLine()
returns a value of typestring
, which cannot be stored in an integer variable. This results in a compile time error. -
What is the difference, if any, between 3 and “3”?
Solution
3 is an integer value, and “3” is a string value.
Problems
-
Declare and initialize 3 variables:
- Each variable should have a different data type
- Choose an appropriate name and value for each variable
Then display the value of each variable on the screen.
Solution
int number = 5; string name = "Samuel"; float weight = 120.65f; Console.WriteLine($"number: {number}"); Console.WriteLine($"name: {name}"); Console.WriteLine($"weight: {weight} kg");