Exercises (with solutions)
May 22, 2024 (01:30:37 PM)
Homework #1
Part I — Questions
- List five pieces of software, and three hardware components of a
computer.
Solution
Accept operating system as a software, cellphone is not a component of a computer. Examples of hardware components are random access memory (RAM), central processing unit (CPU), keyboard, mouse, graphical processing unit (GPU). A comprehensive list can be found at https://www.wikiwand.com/en/Computer_hardware. - List four programming languages.
Solution
C, C++, C#, Java, JavaScript, Python, Haskell, Swift, RWBY, etc (Note: HTML is a “Markup Language” and SQL is a “Query Language”, which would technically be incorrect) - What is a GUI?
Solution
Graphical User Interface. - What is a CLI?
Solution
Command-Line Interface. - What, if any, is the difference between a compiler and an assembler?
Solution
The compiler goes from High-level language to Machine language, the assembler goes from Assembly language to Machine language. - Is machine code (or the machine language program) is made of
circuits, binary numbers, classes, or compilers?
Solution
Binary numbers. - Give a specific characteristic of C# compared to other programming
languages.
Solution
It’s a compiled language, it has automatic garbage collection, it’s object-oriented, it enforces .NET common language specification, etc. - What happens when the source code you are giving to the compiler has
a syntax error?
Solution
The compiler returns an error and fails to compile your code. - Is the C# compiler case-sensitive?
Solution
Yes, the C# compiler is case-sensitive (meaning that the IDE differentiates between capital and lowercase letters). - Suppose I replace every empty space in your source code with two
empty spaces. Will your program still compile? Why, or why not?
Solution
Yes, because compilers do not care about empty spaces. - Give three keywords.
Solution
You can consult the “official” list of keywords as https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/. Are valid answers:int
,using
,static
,public
, etc. Note thatmain
orSystem
are not keywords. - Write a statement that would display, “Hi Mom!” (without the quotes)
followed by a new line on the screen, once inserted in a proper method,
compiled, and executed.
Solution
Console.WriteLine("Hi Mom!");
- Write a statement that would display, “Hello!” (without the quotes)
followed by a new line on the screen, once inserted in a proper method,
compiled, and executed.
Solution
Console.WriteLine("Hello!");
- What is the limitation, if any, to the number of methods you can
have per class? Why is the method called
Main
special?Solution
A class usually has one or more methods. No limitation, really. It is special because it is the first one to be executed, it is the entry point. - What is the difference between a “rule” and a “convention” in
programming language?
Solution
A rule is required by the programming language and enforced by the compiler. A convention is only a recommendation to make your program easier for other humans to read; you can break it and your code will still work. - What is a namespace?
Solution
A named collection of related library code. - In a C# program, can comments start with
\\
(double backslash) or with//
(double (forward) slash)? Do they have to end with a;
(semicolon)?Solution
With//
, no. - Which of the following, if any, are keywords?
Welcome1 public apples int "I’m a string"
Solution
public
,int
- Which of the following are programmer-defined names (or
identifiers)?
BankAccount class apples int itemPerCapita statement
Solution
BankAccount
,apples
,itemPerCapita
,statement
. - Why are variables called “variables”?
Solution
Because their value may change during the program’s execution. - What is string interpolation?
Solution
The action of inserting a variable into a string that is displayed at the screen. - What is the difference, if any, between
12
, and"12"
?Solution
The first one is an integer, the second is a string. - What is the difference, if any, between the
WriteLine
andWrite
methods?Solution
TheWrite
method does not advance the cursor to the next line after the message is displayed at the screen. - Write a statement that would display the following on the screen:
Hi Mom!↵ How are you doing?
Solution
Console.Write("Hi Mom!\nHow are you doing?");
- Assume we have a variable whose name is
myVariable
, type isstring
, and value is"My message"
. What would be displayed on the screen by the following statement?Console.WriteLine($"Here is my variable: {myVariable}");
Solution
{text} Here is my variable: My message
- Assume we have a variable whose name is
level
, whose type isstring
, and whose value is"Easy"
. What would be displayed at the screen by the following statement?Console.WriteLine($"You set the difficulty to {level}.");
Solution
{text} You set the difficulty to Easy.
- Which of the following are correct identifier names?
$myHome3 class my%variable ANewHope _train _ThisIsAVariable statement
Is the namemyVariable
the same asmyvariable
? If not, why?Solution
$myHome3
is correct, but not recommended,ANewHope
,_ThisIsAVariable
,statement
are also correct (but, of course, this latter is weird). The namesmyVariable
andmyvariable
are treated differently by C#, because it is case-sensitive. - Which of the following are correct identifier names?
myClass _Exo_1 Lab3-Exo1 My.Lab.Variable using Lab3_Part1
Solution
Identifiers:myClass
,Lab3_Part1
- Which of the following are keywords?
myClass static Lab3-Exo1 “Hello World” using Lab3_Part1
Solution
Keywords:static
,using
- Which of the following are correct identifier names?
12_Dec_2019 Lab3-Exo1 MyClass2 My.Lab.Variable string My_Var
Solution
OK: MyClass2, My_Var Not OK: 12_Dec_2019, Lab3-Exo1, My.Lab.Variable, string
- Which one(s) of the following, if any, is a correct assignment
(assuming that
variable
,x
andapples
have been declared asint
variables)?5 => variable;
x=5;
apples= 23
x <= 23;
variable =1,890;
Solution
Onlyx=5;
is correct. For instance,apples= 23
is not correct because a;
is missing: since an assignment is a statement, it must ends with a;
- Write a statement that assigns the value 23 to a variable
myAge
of typeint
. You do not need to re-declare that variable.Solution
myAge = 23;
- Cross out the wrong answer in the following sentences, [
like this (incorrect)| like this (correct) ]:- “If the code does not obey the [ rules | conventions ] of C#, then the compiler will complain.”
- “Every statement needs to end with [ a forward slash
/
| a semi-colon;
].” - “C# is a [ object-oriented | functional ] programming language.”
- “A class is made up of [ a body and a header | multiple
using
statements ].” - “An identifier can contain [ only lower-case letters | letters and digits ].”
Solution
- If the code does not obey the rules of C#, then the compiler will complain.
- Every statement needs to end with a semi-colon
;
. - C# is an object-oriented programming language.
- A class is made up of a body and a header.
- An identifier can contain letters and digits.
Part II – Problems
There are 4 errors in the following code that will prevent it from compiling. Can you spot them all?
// My first attempt. using System class Wel { static void Main(); { ConsoleWriteLine("Welcome \n to the lab!"); }
Solution
- Missing
;
afterusing System
- superfluous
;
afterstatic void Main()
- missing
.
betweenConsole
andWriteLine
- missing closing
}
forclass Wel
- Missing
Homework #2
Part I — Questions
- In C#, what is the “escape character”? Why is it useful?
Solution
\
, to print “special characters”, like new line, tabulation, quotations mark, etc. - Write a statement that initializes a variable named
myHeightInMeters
to your height in meters. What should be the datatype ofmyHeightInMeters
?Solution
float myHeightInMeters = 1.68f
The datatype should be any floating-point datatype. - Suppose you replace every
*
in your program with the!
symbol. Are you completely sure that your program would still compile? Why or why not?Solution
No, because/*
will be transformed into/!
. - Give the values of
a
andb
after the following four instructions have been executed.int a, b; a = 2; b = a * 2 + 1; a -= 1;
Solution
a
is1
,b
is5
. - Give the values of
a
andb
after the following four instructions have been executed.int a, b; a = 4; b = a * 3 + 1; a /= 2;
Solution
a
is2
,b
is13
. - Give the values of
c
andd
after the following four instructions have been executed.int c = 3, d; d = 2 + c; c = d * 2; d += 2;
Solution
c
is10
,d
is7
. - Is there an error in the following code? Explain the error or give
the value of
b
after the second statement is executed.float a = 3.7f; int b = (int)a;
Solution
No error; 3 - Is there an error in the following code? Explain the error or give
the value of
b
after the second statement is executed.decimal a = 1.6M; int b = (int)a + a;
Solution
Error, the result type of the operation is a decimal, and cannot be stored in an int. - There is an error in the following code, at the second line. Explain
the error, and how you could fix this second line using a cast operator,
without changing the datatype of the
b
variable.decimal a = 2.5M; int b = a / 2;
Solution
The result of the expressiona / 2
is of typedecimal
, so it cannot be stored in an int. This can be fixed by adding an(int)
cast to the variablea
before dividing it by 2, so that the expression’s result type isint
, like this:int b = (int)a / 2;
- If one of the operator’s operands is of type
float
and the other is of typeint
, what will be the type of the result of the operation?Solution
float
- What is the return type of the operation
12.4 * 3
?Solution
double
- Write an explicit conversion from a
double
variablemyDoubleVar
to anint
variable calledmyIntVar
. You do not need to re-declare those variables. AssumingmyDoubleVar
’s value is 5.89, what value would be stored inmyIntVar
?Solution
myIntVar = (int)myDoubleVar;
, the value stored inmyIntVar
would be 5. - Write a statement that performs an implicit conversion between two
different numeric datatypes.
Solution
float m = 3;
- Assuming that
myLastName
andmyFirstName
are twostring
variables that have been initialized, write a statement that concatenates them with a space and a comma in-between, and assign the resultingstring
to a variable namedfullName
. For instance, if the value ofmyLastName
is"Holbertonand"
, and the value ofmyFirstName
is"Betty"
, then the value offullName
after your operation should be"Holbertonand, Betty"
.Solution
string fullName = myLastName + ", " + myFirstName;
- In C#, what is the name of the method used to read input from the
user?
Solution
ReadLine()
. - What is wrong with the following code? Will the error(s) appear at
compilation time or at execution time?
int age; Console.WriteLine("Please enter your age:"); age = Console.ReadLine();
Solution
The problem is that we are trying to store astring
value (what theConsole.ReadLine()
will return) into anint
variable. This will trigger an error at compilation time. - Will those statements, if placed in a proper
Main
method, compile? Could this program crash at execution time? Justify your answer.int myAge; Console.WriteLine("Please enter your age:"); myAge = int.Parse(Console.ReadLine());
Solution
The code will compile, but can crash at execution time if the end user inputs a non-integer value (for instance, “This is a test”). - Write a series of statements that: a) Declare an
int
variable nameduserAge
, b) Display on the screen a message asking the user to enter his or her age, c) Read the value entered by the user and store it in theuserAge
variable. You can add statement(s) performing intermediate steps if you want.Solution
int userAge; Console.WriteLine("Please enter your age."); userAge = int.Parse(Console.ReadLine());
Note: This is not the only solution, but the most optimal. - Write a series of statements that: a) Declare an
string
variable namedfavoriteColor
; b) Display on the screen a message asking the user to enter his or her favorite color; c) Read the value entered by the user and store it in thefavoriteColor
variable. You can combine some of the statement(s) if you want, but do not display at the screen any information that was not explicitely asked.Solution
string favoriteColor; Console.WriteLine("Please enter your favorite color."); favoriteColor = Console.ReadLine();
Note: This is not the only solution, but the most optimal.
Part II – Problems
The following three exercises do not require a computer. Make sure you feel ready before starting them, try to do them with limited time and without notes, and, if you want, check your answer using your IDE.
This problem restates the content of the Order of Operations section of the lecture notes and ask you to answer various problems.
There are 5 different arithmetic operations available in C#:
Operation Arithmetic Operator Algebraic Expression Expression Addition +
x + 7 myVar + 7
Subtraction -
x − 7 myVar - 7
Multiplication *
x × 7 myVar * 7
Division /
x/7, or x ÷ 7 myVar / 7
Remainder (a.k.a. modulo) %
x mod 7 myVar % 7
Computing operations involving one of them is straightforward:
Operation Result 3 + 4
7
3 - 4
-1
3 * 4
12
6 / 2
3
6 % 4
2
But things can get complicated when multiple operators are used, but no parenthesis are indicated. For instance, should
7 / 2 - 4 * 8 % 3
be read as
(7 ÷ 2) − ((4 × 8) mod 3) = 3.5 − (32 mod 3) = 3.5 − 2 = 1.5 or as
(7 ÷ (2 − 4)) × (8 mod 3) = (7 ÷ (−2)) × 2 = (−3.5) × 2 = −7 Certainly, the result is not the same and there are other possibile ways this calculation may be performed!
Actually, C# uses the following three rules:
*
,/
, and%
, called the “multiplicative operations,” are always evaluated before+
and-
, called the “additive operations.” So that, for instance,2 - 4 * 8
will be evaluated as 2 − (4 * 8) = −30.
If there are multiple operations of the same type, they are evaluated from left to right. For instance,
4 / 2 * 8
will be evaluated as (4 ÷ 2) × 8 = 16 and
4 - 2 + 8
will be evaluated as (4 − 2) + 8 = 10.
Parenthesis can be used to force a particular order of evaluation, so that
2 * (3 + 4)
will be evaluated as 2 × (3 + 4) = 2 × 7 = 14, not as (2 × 3) + 4 = 6 + 4 = 10 as it would without the parenthesis.
Answer the following:
Which of the following operation(s) compute the arithmetic expression (x × (3 mod 5)) − (y × 7)?
x * 3 % 5 - y * 7
x * (3 % 5) - y * 7
(x * 3) % 5 - y * 7
x * 3 % (5 - y * 7)
(x * 3 % 5) - (y * 7)
(x * ((3 % 5) - (y * 7))
State the order of evaluation of the operators in each of the following operations, and compute the resulting value:
8 - 39 * 1 / 12 + 5
12 + -23 / 12 % 3
90 * 23 / 34 - 12 - 13
12 % 83 - 2 * 3
(Optional) Check your answers using your IDE. You can use a statement of the form:
.WriteLine($"8 - 39 * 1 / 12 + 5 is {8 - 39 * 1 / 12 + 5}"); Console
Solution
No solution is offered for this problem: please, try to process the information and to figure out the answers on your own. As suggested, using your IDE will be an excellent way of making sure that your calculations were correct.
Write down, on a piece of paper, a fully compilable program that initializes an
int
variable namedpersons
with the value 5, anint
variable namedbottles
with the value 3, and adouble
variable namedliterPerBottle
with the value 1.5. What should be the type of theliterPerPerson
variable to be able to be assigned the number of liters every person is going to get, if split equitably? Write the correct initialization of that variable and a statement that displays its value.Place a delimited comment with a your name and the time at which you wrote the program at the top of the program.
Solution
/* This is my code, by Clément Aubert, 31st of January 2024, around 13:15.*/ using System; public class Program { public static void Main(string[] args) { int persons = 5; int bottles = 3; double literPerBottle = 1.5; double literPerPerson = (bottles * literPerBottle) / persons; // Note that since literPerBottle is a double, we are using double product and division. .WriteLine(bottles +" bottles of " + literPerBottle + " liter, split equitably between " Console+ persons +" persons gives " + literPerPerson + " liter / person."); } }
Write down, on a piece of paper, a program that:
- Declares a
string
variable nameduserName
. - Displays on the screen “Please enter your name, followed by enter:”.
- Reads a
string
value from the keyboard and assigns the value to theuserName
variable. - Declares an
int
variable namednumber
. - Displays on the screen “Please enter your number:”.
- Reads an
int
value from the keyboard and assigns the value to thenumber
variable. - Declares a
string
variable namedid
and initializes it with the string referenced by theuserName
variable, followed by the number entered by the user (you can concatenate a string and an int using the + sign). - Displays on the screen, “Your id is” and the content of the
id
variable.
Here is an example of execution, where the user input is underlined, and hitting “enter” is represented by ↵:
{text} Please enter your name, followed by enter. J͟a͟y͟l͟a͟h͟↵͟ Please enter your area code, followed by enter. 4͟9͟3͟9͟1͟↵͟ Your id is Jaylah49391 Press any key to continue . . .
- Declares a
Homework #3
Part I – Questions
What is “an instance of a class”?
Solution
An object.
Fill in the blanks: “A class asserts that every objects created using it should have ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ (i.e.,”data”) and ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ (i.e., “operations”).”
Solution
Attributes and methods.
Give two access modifiers.
Solution
public
andprivate
.What, if any, is the difference between a parameter and an argument?
Solution
“Parameters” are called “formal parameters” and are used when defining the method, while “arguments” are called “actual parameters” and are used when calling the method. A method has parameters and takes arguments.
Write a statement that creates a new object from the
Rectangle
class.Solution
Rectangle myRec = new Rectangle();
What is the purpose of the keyword
new
?Solution
To create objects, to instantiate classes.
Do different objects from the same class share their instance variables?
Solution
No, there is one instance variable per object.
Briefly explain the difference between a local variable and an instance variable.
Solution
A local variable exists only within a single method; instance variables are available/accessible to all methods in a class.
Suppose we have a
Circle
class containingpublic void SetRadius(double radiusArgument) { = radiusArgument; radius }
Write a statement that create a
Circle
object, and one statement that sets its radius to 3.5.Solution
= new Circle(); Circle theCircle .SetRadius(3.5); theCircle
Indicate the order of evaluation of the operators in each of the following C# operations by adding parenthesis or developping the expression one step at a time, and compute the resulting value:
3 * 4 - 2
3 % 2 + 3
2 - 3 + 3 * 2
2 + 2 * 1 - 4
Write the complete implementation of a class that contains two attributes (with different data types), a setter for one attribute, a getter for the other attribute, a custom constructor, and a
ToString
method. You can re-use an example from a lecture or a lab, as long as it satisfies those conditions, or you can invent one. No need to write an application program.Solution
Note: In this solution, the Rectangle class from the lab was used, but any class fulfilling the requirements will work.
class Rectangle { private int length; private int width; public Rectangle(int lengthP, int widthP) { = lengthP; length = widthP; width } public void SetLength(int lengthParameter) { = lengthParameter; length } public int GetWidth() { return width; } public override string ToString() { return "Length: " + length + ", Width: " + width; } }
What does the keyword
return
do?Solution
It is used by a method to return a value to the environment that called it.
Write a get method for an instance variable named
total
of typeint
.Solution
public int GetTotal() { return total; }
Write a getter for an attribute of type
string
namedmyName
.Solution
public string GetMyName() { return myName; }
Write a setter for an attribute of type
int
namedmyAge
.Solution
public void SetMyAge(int paramMyAge) { myAge = paramMyAge; }
Assuming
name
is astring
instance variable, there is problem with the following setter. Fix it.public int SetName(string val){ = val; name }
Solution
It has the wrong return type, because it does not (and should not) return a value, i.e., replace
int
withvoid
.Assume we have an instance of the
Rectangle
class namedmyRect
and an instance of theCircle
class namedmyCircle
. Write statement(s) that will make the radius ofmyCircle
equal to the width ofmyRect
.Solution
myCircle.SetRadius(myRect.GetWidth());
Briefly describe what a format specifier is. Write a statement that uses one.
Solution
An indication to format a numerical value in a special way in a string. For example,
Console.WriteLine($"{65536:N");}
will display “65,536.00” on the screen after applying the:N
format specifier to the value 65536.Write a statement that uses a format specifier.
Solution
Console.WriteLine($"myInt:C");
Write a method for the
Rectangle
class that divides the length and width of the calling object by a factor given as a parameter.Solution
public void DivideBy(int factor) { length /= factor; width /= factor; }
Draw the UML diagram of a class named “Student” with a single attribute, “name”, of type
string
, and two methods,SetName
andGetName
.Solution
Student - name: string + SetName(arg: string) + GetName(): string Write a
ToString
method for aAccount
class with two attributes, astring
attribute calledname
and adecimal
attribute calledamount
.Solution
public override string ToString() { return $"Account Name: {name}\nAccount Balance: {amount}"; }
Consider the following UML diagram:
Circle - radius : float + setRadius(radiusParam : float) : void + getRadius(): float + getArea(): float What is the name of the class, what are the methods and attributes of the class?
Solution
The class is named Circle, it has a single attribute (radius) and three methods (setRadius, getRadius and getArea).
What does it mean to say that instance variables have a default initial value? How is that different from the variables we have been manipulating in the
Main
method?Solution
When we create an object, the instance variable get a default value. When we declare a variable, it is unassigned.
Is it possible to have more than one constructor defined for a class? If yes, how can C# know which one is called?
Solution
Yes, by looking at the signature.
What is the name of a constructor method? What is the return type of a constructor?
Solution
The name of the class. It does not have a return type, not even
void
.Write a constructor for a
Soda
class with onestring
attribute calledname
.Solution
public Soda() { name = "Generic"; }
Assume we have a
Polygon
class, that have only one attribute, anint
callednumberOfSides
. Write a constructor for that class.Solution
public Polygon (int numberOfSidesParam) { numberOfSides = numberOfSidesParam; }
What is the “default” constructor? Do we always have the possibility of using it?
Solution
The constructor provided with the class by default, that set all the attributes to their default values. If we define our own constructor, this one disappears.
What is the return type of a
ToString
method? How many arguments does it usually take?Solution
string
; 0.Consider the following partial class definition:
public class Book { private string title; private string author; private string publisher; private int copiesSold; }
- Write a statement that would create a
Book
object. - Write a “getter” and a “setter” for the
title
attribute. - Write a constructor for the
Book
class taking at least one argument (you are free to decide which one(s)).
Solution
Book myBook = new Book();
2 and 3.
public string GetTitle() { return title; } public void SetTitle(string titleP) { = titleP; title } public Book (string titleP, string authorP, string pubP, int copiesP) { = titleP; title = authorP; author = pubP; publisher = copiesP copiesSold }
- Write a statement that would create a
Consider the following partial class definition:
class DVD { private string title; private decimal price; }
- Write a “setter” for the
title
attribute. - Write a constructor for the
DVD
class that takes two arguments. - Write a method called
Discount
that decreases theprice
attribute by 20.55%. - Write a (good, informative)
ToString
method for the class. - Write statements that ask the user to enter a price and then create
a
DVD
object with aprice
attribute equal to the price the user entered. (The object’stitle
attribute can be anything you choose). - Draw the UML class diagram for the class you obtained by adding the above four methods to our original class definition.
Solution
class DVD { private string title; private decimal price; public void SetTitle(string titleP) { = titleP; title } public DVD(string titleP, decimal priceP) { = titleP; title = priceP; price } public void Discount() { -= price * 0.2055 price } public override string ToString() { return $"DVD Title: {title}\nDVD Price: {price}" } } //program.cs .WriteLine("What should the price be for the movie "Ender's Game?"); Console= new DVD("Ender's Game", decimal.Parse(Console.ReadLine())); DVD myDVD
DVD - title : string - price : decimal + SetTitle(titleP : string) : void + < > DVD(titleP : string, priceP : double) + Discount() : void + ToString() : string Note: This is not the only answer, but is the most optimal.
- Write a “setter” for the
Consider the following partial class definition:
class Book { private string title; private decimal price; }
- Write a “getter” for the
title
attribute. - Write a constructor for the
Book
class that takes two arguments. - Write a method called
AddTaxes
that increases theprice
attribute by 6.35%. - Write a (good, informative)
ToString
method for that class. - Write statements that ask the user to enter a price and then create
a
Book
object with aprice
attribute equal to the price the user entered. (The object’stitle
attribute can be anything you choose). - Draw the UML class diagram for the class you obtained by adding the above four methods to our original class definition.
Solution
class Book { private string title; private decimal price; public string GetTitle() { return title; } public Book(string titleP, decimal priceP) { = titleP; title = priceP; price } public void AddTaxes() { *= 1.0635m; price } public override string ToString() { return $"Book Title: {title}, Price: {price}."; } } //program.cs .WriteLine("What should the price be for the book "Ender's Game?"); Console= new Book("Ender's Game", decimal.Parse(Console.ReadLine())); Book myBook
Book - title : string - price : decimal + GetTitle() : string + < > Book(titleP : string, priceP : double + AddTaxes() : void + ToString() : string Note: This is not the only answer, but is the most optimal.
- Write a “getter” for the
Assume that my
Pet
class contains one custom constructor:public Pet(string nameP, char genderP){ = nameP; name = genderP; gender }
What is the problem with the following statement?
= new Pet('M', "Bob"); Pet myPet
Solution
The method has for parameters a
string
and achar
, but the problematic statement calls it with achar
and astring
: the order of the arguments is wrong, it should bePet myPet = new Pet("Bob", 'M');
.Why would one want to define a constructor for a class?
Solution
To be able to set the instance variables directly when creating the objects.
Part II – Problems
There is only one problem this time, and it is harder than what you’ll be asked to do during the exam. Being able to solve it is an excellent sign that you are ready.
You are going to design a class named
Triangle
. A triangle has three angles, but knowing the value of only two angles is sufficient to determine the value of the third, since they always add up to 180°. Hence, it is sufficient to have only twodouble
attributes,angle1
andangle2
. We want to define several methods:- a no-arg constructor that sets the value of
angle1
to 60.0 and the value ofangle2
to 60.0, - another constructor, that takes two arguments, and assigns to
angle1
the value of the first argument, and assigns toangle2
the value of the second argument, - getters for
angle1
andangle2
, - a method that computes and returns the value of the third angle,
that we name
ComputeAngle3
, - a method that rotate the triangle: the value of the first angle should be replaced with the value of the second angle, and the value of the second angle should be replaced with the value of the third angle.
- Write the UML diagram for the
Triangle
class. - Write the full, compilable implementation of the
Triangle
class.
Solution
Triangle - angle1: double - angle2: double + Triangle() + Triangle(angle1P: double, angle2P : double) + GetAngle1(): double + GetAngle2(): double + ComputeAngle3(): double + Rotate(): void class Triangle { private double angle1; private double angle2; public Triangle() { = 60; angle1 = 60; angle2 } public Triangle(double angle1Param, double angle2Param) { = angle1Param; angle1 = angle2Param; angle2 } public double GetAngle1() { return angle1; } public double GetAngle2() { return angle2; } public double ComputeAngle3() { return 180 - angle1 - angle2; } public void Rotate() { double oldAngle3 = ComputeAngle3(); = angle2; angle1 = oldAngle3; angle2 } }
- a no-arg constructor that sets the value of
Homework #4
Part I — Questions
What is sequential processing?
Solution
When the code is executed sequentially, without any branching. It implies that the code is processed in the order in which it is presented in the source code: the statement at line n will always be executed after the statement at line n − 1 and before the statement at line n + 1.
What is a decision structure?
Solution
A decision structure is a test and one or multiple statement blocks that may or may not be executed based on the outcome of the test. Selection and iteration are two examples of decision structures: in the first one, a statement block can be “skipped over” if the test evaluates to false, in the second one, a statement block can be repeated multiple times, as long as the test evaluates to true. A decision structure makes it possible to have portions of the code executed conditionally.
Decide if the following boolean expressions will evaluate to
true
orfalse
:3 > 2.0 && false
(4 != 3) || false
'A' == 'b' && ! false
(! false) == (true || 4 == 3)
Solution
false
true
false
true
Decide if the following Boolean expressions will evaluate to
true
orfalse
:3 > 2.0 || true
(4 != 3) && false
'A' == 'b' || ! false
(! true) == (true || 4 != 3)
Solution
true
false
true
false
For each of the following Boolean expressions, decide if it will evaluate to
true
orfalse
:('y' == 'Y') && true
6 + 2 < 8 || 3 > 4
(true && 4 == 3) == false
4 > 4 && !false
Solution
false
false
true
false
For each of the following Boolean expressions, decide if it will evaluate to
true
orfalse
:('y' != 'Y') && true
6 + 2 < 12 || 3 > 4
(true && 4 >= 3) == false
13 <= 4 * 3 || !false
Solution
true
true
false
true
What relational operator is used to determine whenever two values are different?
Solution
!=
How do you store the result of a Boolean expression?
Solution
In a variable of type
bool
. Its two possible values aretrue
andfalse
.Give three relational operators, and then two logical operators.
Solution
Possible answers:
<=
,>=
,==
,!=
,>
,<
and!
,&&
,||
What would be displayed on the screen by the following code?
if (false) { .WriteLine("Hello!"); Console} .WriteLine("Hi!"); Console
Solution
“Hi!”
Is there a simpler way to write the expression
over21 == true
, assuming thatover21
is a Boolean variable?Solution
We can simply write
over21
, which will always evaluate to the same value asover21 == true
.Assume that
x
andy
are twoint
variables that have already been initialized (i.e., declared and assigned), write anif
statement that assigns 10 tox
ify
is (strictly) greater than 5.Solution
if (y > 5) x = 10;
In C#, is there a difference between
=
and==
? Write a statement that uses=
.Solution
Yes, one equal sign serves to write assignment operator, and two equal signs serve to compare. An example of statement that uses comparison first and assignment second could be:
if (x == 9)x = 12;
Assuming a
name
string was declared and initialized with a value given by the user, write anif
statement that displays “I have the same name!” ifname
contains your first name.Solution
if(name=="Clément") .WriteLine("I have the same name!"); Console
Is the following statement correct, i.e., would it compile, assuming
myFlag
is abool
variable, andmyAge
is an initializedint
variable?if ( myAge > 20 ) { = true myFlag };
Solution
No, the semi-colon should come before the closing brace.
If we write a statement that begins with
if(false)
, then the IDE returns a warning, “Unreachable code detected”. What does it mean?Solution
The IDE is warning us that the statements in the block will never be executed.
Write an
if
statement that prints “Bonjour !” if the value of thechar
variablelang
is'f'
.Solution
if (lang == 'f') .WriteLine("Bonjour !"); Console
For each of the following boolean expressions, decide if it will evaluate to
true
orfalse
when the boolean variablesx
,y
andz
are all set totrue
:x || y && z
!x || y && z
!(x || y) && (z && y)
(!x && x) || (!x || x)
Do the same when they are all set to
false
.Solution
For each expression, we give first the value if all the variables are set to
true
, then the value if all the variables are set tofalse
.true
,false
true
,true
false
,false
true
,true
You can check the answer using for instance the following code.
using System; class MainClass { public static void Main (string[] args) { bool x, y, z; = true; x = true; y = true; z .WriteLine(x || y && z); Console.WriteLine(!x || y && z); Console.WriteLine(!(x || y) && (z && y)); Console.WriteLine ((!x && x) || (!x || x)); Console= false; x = false; y = false; z .WriteLine(x || y && z); Console.WriteLine(!x || y && z); Console.WriteLine(!(x || y) && (z && y)); Console.WriteLine ((!x && x) || (!x || x)); Console} }
Write a
boolean
expression that evaluates totrue
if a variablex
is between 3 (excluded) and 5 (included).Solution
x>3 && 5>=x
Write an
if-else
statement that assigns 0.1 toz
ify
is greater or equal than 0, and that assigns −0.1 toz
otherwise.Solution
if(y >= 0){ z = 0.1; } else{ z = -0.1; }
Write an
if-else
statement that assigns"Minor"
to an already declaredstring
variablelegalStatus
ifage
is strictly less than 18, and that assigns"Major"
tolegalStatus
otherwise.Solution
if(age < 18){ legalStatus = "Minor"; } else{ legalStatus = "Major"; }
Write an
if-else
statement that displays “It’s free for you!” if anint
variableage
is between 0 and 18, and “It’s $5.00.” otherwise.Solution
if(age <= 18 && age >= 0){ Console.WriteLine("It's free for you!"); } else{ Console.WriteLine($"It's {5M:C}."); }
Assume we initialized an
int
variable calledcourseNumber
and astring
variable calledcourseCode
. Write a series of statements that will display:- “I’m taking this class!” if
courseNumber
is1301
andcourseCode
isCSCI
; - “That’s my major!” if
courseCode
isCSCI
; - “Is that an elective?” if
courseNumber
is greater than 3000; or - “Is it a good class?” otherwise.
Your program should display exactly one message.
Solution
if(courseNumber == 1301 && courseCode == "CSCI") { .WriteLine("I'm taking this class!"); Console} else if(courseCode == "CSCI") { .WriteLine("That's my major!"); Console} else if(courseNumber > 3000) { .WriteLine("Is that an elective?"); Console} else { .WriteLine("Is it a good class?"); Console}
- “I’m taking this class!” if
Assume we previously initialized an
int
variable calledgraduationYear
and astring
variable calledgraduationSemester
. Write a series of statements that will display:- “I will graduate at the same time!” if
graduationYear
is2023
andgraduationSemester
isFall
; - “I love this season.” if
graduationSemester
isSpring
; - “That is in a long time!” if
graduationYear
is greater than 2025; or - “I hope you’ll have an in-person ceremony!” otherwise.
Your program should display exactly one message.
Solution
if(graduationYear == 2023 && graduationSemester == "Fall") { .WriteLine("I will graduate at the same time!"); Console} else if(graduationSemester == "Spring") { .WriteLine("I love this season."); Console} else if(graduationSemester > 2025) { .WriteLine("That's in a long time!"); Console} else { .WriteLine("I hope you'll have an in-person ceremony!"); Console}
- “I will graduate at the same time!” if
Assume we previously initialized a
char
variable calledmyChar
. Write a series of statements that will display if the character is…- Uppercase
- Lowercase
- A number
- or none of those.
Your program should display exactly one message. Bonus: Make your message also display the ASCII value of the character.
Solution
if ((myChar >= 'a') && (myChar <= 'z')) { .WriteLine($"Your character ({(int)myChar}) is lower-case!"); Console} else if ((myChar >= 'A') && (myChar <= 'Z')) { .WriteLine($"Your character ({(int)myChar}) is upper-case!"); Console} else if ((myChar >= '0') && (myChar <= '9')) { .WriteLine($"Your character ({(int)myChar}) is a number!"); Console} else { .WriteLine($"Your character ({(int)myChar}) is not a letter or number!"); Console}
What will be displayed on the screen by the following program?
int x = 3, y = 2, z = 4; if (x > y) {z += y;} if (x > z) {y -= 4;} .WriteLine($"x is {x}, y is {y}, and z is {z}."); Console
Solution
“x is 3, y is 2, and z is 6.”
What will be displayed on the screen by the following program?
int x = 3, y = 2, z = 4; if (x >= z) {z += y;} else if (x != y) {z *= y;} -= 4; y .WriteLine($"x is {x}, y is {y}, and z is {z}."); Console
Solution
“x is 3, y is -2, and z is 8.”
(We’ll use the 24-hour clock, sometimes called “military time”.) Assuming that an
int
variablehour
has been initialized, write part of a program that would display on the screen “Good morning” ifhours
is less than or equal to 12, and “Hello” otherwise.Solution
if (hours <= 12) { .WriteLine("Good morning!"); Console} else { .WriteLine("Hello"); Console}
Assuming that
myString
is a string variable, write a statement that prints “Hello, Melody!” if the value ofmyString
is equal toMelody
, and nothing otherwise.Solution
if (myString == "Melody") { .WriteLine("Hello, Melody!"); Console}
What will be displayed on the screen by the following program?
int x = 3, y = 2, z = 4; if (y >= z) {z += y;} else if (x != y) { if (false) {z -= 3;} else {z += x;}} .WriteLine($"x is {x}, y is {y}, and z is {z}."); Console
Solution
x is 3, y is 2, and z is 7.
Rewrite, if possible, the three following
if-else-if
statements asswitch
statements:if (myLang == 'f') { .WriteLine("Vous parlez Français ?"); Console} else if (myLang == 'e') { .WriteLine("Do you speak English?"); Console} else if (myLang == 'd') { .WriteLine("Sprechen Sie Deutsch?"); Console} else { .WriteLine("I do not know your language!"); Console}
if (myCity == "Augusta") { .WriteLine("I also live here!"); Console} else if (myCity == "Ithaca" || myCity == "Providence") { .WriteLine("I used to live there!"); Console} else { .WriteLine("I never lived there."); Console}
if (temp == 100.0) { .WriteLine("It's ready!"); Console} else if (temp >= 90.0) { .WriteLine("Almost ready!"); Console} else { .WriteLine("You have to wait."); Console}
If you think it is not possible or not feasible, explain why.
Solution
switch (myLang) { case 'f': .WriteLine("Vous parlez Français ?"); Consolebreak; case 'e': .WriteLine("Do you speak English?"); Consolebreak; case 'd': .WriteLine("Sprechen Sie Deutsch?"); Consolebreak; default: .WriteLine("I do not know your language!"); Consolebreak; }
switch (myCity) { case "Augusta": .WriteLine("I also live here!"); Consolebreak; case "Ithaca": case "Providence": .WriteLine("I used to live there!"); Consolebreak; default: .WriteLine("I never lived there."); Consolebreak; }
The last one is impossible, since we cannot write ‘switch’ statements comparing all the possible
float
values!Give an example of an
if
statement that could not be rewritten as aswitch
.Solution
Any condition not making a simple comparison is a good attempt. For instance, trying to convert
if(age % 2 == 0){Console.WriteLine("Your age is even.");
. into aswitch
would require to list all the even values, which is not realistic.Write a
switch
statement that sets adouble
discount
variable to0.5
if a stringday
variable contains"Monday"
or"Wednesday"
,0.25
ifday
contains"Saturday"
, and0.5
otherwise.Solution
switch (day) { case "Saturday": { = 0.25; discount break; } default: { = 0.5; discount break; } }
Part II – Problems
This time, the two exercises do not require a computer, and are here to craft on your problem-solving skills. Make sure you feel ready before starting them, try to do them with a limited amount of time and without notes, and check your answer using your IDE.
Write a program that asks the user to write a country name and stores the user’s input into a string variable. Then, compare that string with
"france"
: if it is equal, then display at the screen"Bienvenue en France !"
. Then, compare that string with"usa"
: if it is equal, then display at the screen"Welcome to the US!"
. If the string is different from both"france"
and"usa"
, then display at the screen"Welcome to"
followed by the name of the country the user typed in. Can you think of two ways to implement this program, one usingif-else-if
statements, the other usingswitch
?Solution
A possible solution using
switch
is:.WriteLine("Please, enter a country name?"); Consolestring country_answered = Console.ReadLine(); switch (country_answered) { case "usa": .WriteLine("Welcome to the US!"); Consolebreak; case "fr": .Write("Bienvenue en France!"); Consolebreak; default: .WriteLine($"Welcome to {country_answered}"); Consolebreak; }
You want to write a small program for an on-line printing company. Your program should ask the user to chose a format (10 × 15 centimeters, or 8 × 11 inches), ask if it is the first time the customer order through your company, and a number of copies. Then, calculate the total cost of printing those pictures, knowing that
- Printing a 10 × 15 centimeters picture costs $0.20, printing a 8 × 11 inches picture costs $0.25,
- A new customer gets a $3 coupon if the order is more than $5,
- A 10% discount is given if more than 50 copies were ordered,
- The two previous offers can be cumulated.
Display on the screen a message starting by “Welcome!”, then a new line, then “We cherish our new customers” if it is the first time the user uses your company, “, so we’re giving you a $3 discount!” if the user is allowed to get the coupon, then print the total and “You had a 10% discount!” if the user ordered more than 50 copies. See below for examples of execution, where the user input is underlined, and hitting carriage return is represented by ↵.
Enter 'c' for 10x15cm, anything else for 8x11in. c͟ ↵ Is this your first time here? Type 'y' for 'yes'. y͟ ↵ Enter a number of copies. 9͟0͟ ↵ Welcome! We cherish our new customers, so we are giving you a $3 discount! Your total is $13.50. You had a 10% discount!
Enter 'c' for 10x15cm, anything else for 8x11in. p͟ ↵ Is this your first time here? Type 'y' for 'yes'. N͟o͟t͟ ͟a͟t͟ ͟a͟l͟l͟↵ Enter a number of copies. 1͟2͟0͟ ↵ Your total is $27.00. You had a 10% discount!
Solution
.WriteLine("Enter 'c' for 10x15cm, anything else for 8x11in"); Consolechar sizeChoice = char.Parse(Console.ReadLine()); .WriteLine("Is this your first time here? Type 'y' for 'yes'."); Consolechar firstTime = char.Parse(Console.ReadLine()); .WriteLine("Enter a number of copies"); Consoleint copies = int.Parse(Console.ReadLine()); // The following statement is explained below. decimal totalCost = sizeChoice == 'c' ? copies * 0.2m : copies * 0.25m; if(firstTime == 'y') { .WriteLine("Welcome!"); Consolestring message = "We cherish our new customers"; if(totalCost > 5m) { -= 3m; totalCost += ", so we're giving you a $3 discount!"; message } .WriteLine(message); Console} if(copies > 50) { -= totalCost * 0.1m; totalCost .WriteLine($"Your total is {totalCost:C}. You had a 10% discount!"); Console} else { .WriteLine($"Your total is {totalCost:C}."); Console}
The
decimal totalCost = sizeChoice == 'c' ? copies * 0.2m : copies * 0.25m;
statement uses the conditional operator. This particular statement is a shorter way of writingdecimal totalCost; if(sizeChoice == 'c'){ = copies * 0.2m; totalCost } else{ = copies * 0.25m; totalCost }
Homework #5
Part I — Questions
Assume you are given an un-assigned
string
variableletterGrade
, and an already assignedfloat
variablenumberGrade
. Write a small program that assigns"A"
toletterGrade
ifnumberGrade
is between 100 and 90 (both included),"B"
toletterGrade
ifnumberGrade
is between 90 (excluded) and 80 (included), etc., and"Invalid data"
ifnumberGrade
is strictly lower than 0 or strictly greater than 100. Should you use aswitch
statement or aif
…else if
…else
?Solution
An
if
…else if
…else
is the right structure for this task:float numberGrade; string letterGrade; = -60; // This is just an example, feel free to change it. numberGrade if(numberGrade > 100 || numberGrade < 0) { // It's actually easier to get rid of the "invalid" cases first. = "Invalid Data"; letterGrade } else if (numberGrade >= 90) { = "A"; letterGrade } else if(numberGrade >= 80) { = "B"; letterGrade } else if(numberGrade >= 70) { = "C"; letterGrade } else if(numberGrade >= 60) { = "D"; letterGrade } else { // We know the value is greater than 0 but strictly lower than 60. = "F"; letterGrade } .WriteLine(numberGrade + " corresponds to " + letterGrade); Console
Given an
int
variablecounter
, write three statements to decrement its value by 1.Solution
We actually know four ways to do that:
= counter - 1; counter -= 1; counter --; counter--counter;
What will be displayed on the screen?
int x = 3, y = 7; .WriteLine (x++ +" and "+ --y); Console
Solution
“3 and 6”
What will be displayed on the screen by the following program?
int counter = 2; while (counter != 5) { .Write(counter + "\n"); Console++; counter}
Solution
2 3 4
What will be displayed on the screen by the following program? Write the spaces and new line explicitly.
int counter = 10; while (counter > 5) { --; counter.Write(counter + "\n"); Consoleif (counter == 7) { .WriteLine("Bingo"); Console} }
Solution
9 8 7 Bingo 6 5
What will be displayed on the screen by the following program?
int counter = 10; while (counter != 5) ; .Write(counter + "\n"); Console--; counter
Solution
Nothing, and it will loop forever.
What will be displayed on the screen by the following program?
int counter = 7; while (counter != 2) .Write(counter + "\n"); Console--; counter
Solution
7 infinitely many times.
What is input validation? Name a control structure that can be used to perform it. Why is it important?
Solution
Making sure the user’s input is valid. The
while
loop. Because we cannot trust the user.What do we name a variable that is increased by some value at every iteration of a loop, i.e., that keeps the running total?
Solution
An accumulator.
What is a sentinel value?
Solution
It’s a value that will trigger an exit from a loop. It is a value that was agreed on, and that signifies “I now want to exit the loop.”.
Write a program that asks the user to enter a value between 0 and 10, and asks again as long as the user enters integers outside that range.
Solution
int answer; do{ .WriteLine("Enter a value between 0 and 10 (both included)."); Console= int.Parse(Console.ReadLine()); answer }while(answer > 10 || answer < 0);
Write a small program that asks the user for an integer, and displays “It is positive” if the number entered is positive, “It is negative” if the number entered is negative, and “Not a number” if the user entered a string that is not an integer.
Solution
int answer; .WriteLine("Enter an integer"); Consoleif(!int.TryParse(Console.ReadLine(), out answer)){ .WriteLine("Not a number"); Console} else if (answer > 0){ .WriteLine("Positive"); Console} else{ .WriteLine("Negative"); Console}
Write a program containing a
while
loop that would display the numbers between -100 and 100 (both included) with a space between them when executed.Solution
int counter = -100; while(counter <= 100){ .Write(counter++ + " "); Console}
Assume you are given an initialized
string
variablename
, and astring
variablefield
. Write a small program that assigns tofield
- “CS” if
name
is “Turing” or “Liskov”, - “Math.” if
name
is “Aryabhata” or “Noether”, - “Unknown” otherwise.
Solution
string name; = "Turing"; // Value given as an example, change it to test. name string field; switch(name){ case("Turing"): case("Liskov"): = "CS"; field break; case("Aryabhata"): case("Noether"): = "Math."; field break; default: = "Unknown"; field break; } .WriteLine(name + " worked in " + field + "."); Console
- “CS” if
Write a program that asks the user to enter a value between 1900 and 1999 (both included), and asks again as long as the user enters integers outside that range.
Solution
int answer; do{ .WriteLine("Enter a value between 1900 and 1999 (both included)."); Console= int.Parse(Console.ReadLine()); answer }while(answer < 1900 || answer > 1999);
Part II – Problems
Write a
switch
statement that calculates the number of days in a particular month. You should assume that you are given already assignedmonth
andyear
int
variables, and that your program should set an already declaredint
numberOfDays
variable to 28, 29, 30 or 31 depending on the month / year combination. Your program should start with aswitch
matchingmonth
against certain values, and, ifmonth
is 2, uses anif
statement to decide whenever the number of days is 28 or 29. You can use something likeswitch (month) { …case (2): if … …break; …}
Solution
int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: = 31; numDays break; case 4: case 6: case 9: case 11: = 30; numDays break; case 2: if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0)) = 29; numDays else = 28; numDays break; default: .WriteLine("Invalid month."); Consolebreak; } .WriteLine("Number of Days = " + numDays); Console
Homework #6
Part I — Questions
Write a statement that creates a 10-element
int
array namednumbers
.Solution
int[] numbers = new int[10];
In the following, what is the value of the size declarator? What is the value of the index?
int[] numbers; = new int[8]; numbers [4] = 9; numbers
Solution
The size declarator is 8, the subscript, or index, is 4.
What is wrong with the following array declaration?
int[] books = new int[-1];
Solution
The size declarator cannot be negative.
Draw the content of the
scores
array once those statements have been executed.int[] scores = new int[3]; [0] = 13; scores[2] = 25; scores
Solution
index 0 1 2 value 13 0 25 What will be displayed on the screen by the following program?
for (int num = 3 ; num <= 5 ; num++) .Write(num + " "); Console
Solution
3 4 5
Write a ‘for’ loop that displays on the screen the sequence “1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ”.
Solution
for (int x = 1 ; x <= 10 ; x ++) .Write(x + ", "); Console
Write a ‘for’ loop that displays on the screen the sequence “1, 2, 3, 4, 5, 6, 7, 8, 9, 10”, (note that there is no comma after 10).
Solution
for (int x = 1 ; x <= 10 ; x ++) { .Write(x); Consoleif (x < 10) Console.Write(" ,"); }
Write a ‘for’ loop that displays on the screen the sequence “1 3 5 7 9 ”.
Solution
for (int x = 1 ; x <= 10 ; x+= 2) .Write(x + " "); Console
Given an
int
variablemyVar
initialized with a positive value, write a loop that sums the integers between 0 andmyVar
(i.e., 0 + 1 + ⋯ + (myVar − 1) + myVar).Solution
int sum = 0; for (int x = 1 ; x <= myVar ; x++) += x; sum
Consider the following code:
for (int y = 1; y <= 3; y++) { for (int z = 1; z < 5; z++) .Write("Scene " + y + ", take " + z + ". " ); Console.WriteLine(); Console}
How many times does the outer loop iterate (i.e., how many scenes are shot)? How many times does the inner loop iterate (i.e., how many takes for each scene)? Finally, what is the total number of iterations of the nested loops (i.e., how many takes are made, total)?
Solution
3, 4, 12.
Which of the following are pre-test loops?
do while
,switch
,while
,for
andif-else-if
.Solution
for
andwhile
are pretest loops.What will be displayed on the screen by the following code?
int[] values = new int[6]; for (int i = 0 ; i < 6 ; i++) [i] = (i*2); valuesforeach (int j in values) .WriteLine(j); Console
Solution
0 2 4 6 8 10
Suppose we are given an
int
arraydailyPushUp
with 7 elements. Write a piece of code that display the value of the elements stored in the arraydailyPushUp
.Solution
for (int j = 0 ; j < 7 ; j++) .WriteLine(dailyPushUp[j]); Console
What is “array bounds checking”? When does it happen?
Solution
It is C# making sure that you are not using a subscript outside the allowed range. It happens at run-time.
Is there an error with the following code? If you think there is one, explain it, otherwise draw the content of the
myIncomes
array once those statements have been executed.double[] myIncomes = new double[5]; [1] = 3.5; myIncomes// No income on day two. [3] = 5.8; myIncomes[4] = 0.5; myIncomes[5] = 1.5; myIncomes
Solution
The subscripts are off, they should go from 0 to 4:
myIncomes[5] = 1.5;
will casue an error.What would be the size of the
test
array after the following statement has been executed?int[] test = {3, 5, 7, 0, 9};
Solution
5
What is the difference, if any, between the following two statements?
int[] num, scores; int num[], scores;
Solution
In the second one, only
num
is a reference to anint
array, andscores
is just anint
.Write a statement that creates and initializes a
double
array with the values 12.5, 89.0 and 3.24.Solution
double[] question = {12.5, 89.0, 3.24};
What is the value of
count
and the content ofnumber
once the following has been executed?int count=2; int[] number={3, 5, 7}; [count--] = 8; number[count]--; number
Solution
count is 1. numbers is 3, 4, 8.
Suppose we have an array named
temp
that has been declared and initialized. How can we get the number of elements in this array?Solution
By using the
Length
field:temp.Length
.Describe what the following code would do.
int[] record = { 3, 8, 11 }; int accumulator = 0; foreach (int i in record) += i; accumulator
Solution
Declare and initialize an
int
array with the values 3, 8 and 11, and then sum those values in an accumulator variable.Assuming we have two
int
arrays of the same size,firstA
andsecondA
, write a program that copies the content offirstA
intosecondA
.Solution
for (int k = 0 ; k < firstA.Length ; k++) [k] = firstA[k]; secondA
Assuming we are given an
int
array namedarrayF
, write a program that adds one to each of its elements. That is, ifarrayF
contains 3, 5, 7 and -2 before your program is executed, it should then contain 4, 6, 8 and -1 after your program was executed.Solution
for (int k = 0 ; k < arrayF.Length ; k++) [k] += 1; arrayF
Assuming we are given an
int
array namedarrayF
, write a program that displays the product of its elements. That is, ifarrayF
contains 2, 3 and -1, then your program should display -6.Solution
int prod = 1; for (int k = 0 ; k < arrayF.Length ; k++) *= arrayF[k]; prod .WriteLine(prod); Console
Write a static method (header included) that takes as argument an
int
array, and display on the screen the value of each element of that array.Solution
public static void p(int[] a){ foreach (int k in a)Console.WriteLine(k); }
Write a static method (header included) that takes as argument an
int
array, and stores the value 10 in each element of that array.Solution
public static void z(int[] a){ for (int j = 0 ; j < a.length ; j++) a[j]=10; }
Quizzes
Those quizzes are given as examples, to help you practise. They were given at week 4 and 7.
Quiz 1
(3 pts) List three keywords.
Solution
Keywords are words that have special meanings and cannot be used as identifiers in your program. Examples of C# Keywords include
int, string, if, while, void, else, bool
etc.(4pts) Circle the correct identifiers:
%Rate
static
my-variable
User.Input
YoUrNaMe21
test_train
_myIdentifier
Solution
Valid identifiers can not include reserved words, can not start with a number, and must contain only numbers, letters, and/or the underscore character. The identifiers below follow these rules.
my-variable YoUrNaMe21 test_train _myIdentifier
(4 pts) For each of the following, indicate if they are a “rule” of C# or a “convention” between programers by ticking the appropriate column. The first answer is given as an example.
Statement Rule Convention Code should be commented. ✓ Case matters. Variable names should be descriptive. Keywords cannot be used as identifiers. Each “.cs” file should contain exactly one class. Solution
Statement Rule Convention Case matters. ✓ Variable names should be descriptive. ✓ Keywords cannot be used as identifiers. ✓ Each “.cs” file should contain exactly one class. ✓ (4 pts) Write a statement that would display, “Hi Mom!” (with the quotes) followed by a new line on the screen.
Solution
The key is to escpae the
"
character:Console.Write("\"Hi Mom!\"\n")
. Note that we could have usedConsole.WriteLine
instead of inserting the new line using the escpae sequence\n
.(5 pts) Write a series of statements that would
- declare an
int
variable called “myAge”, - assign your age to that variable,
- display “My age is”, the value of the “myAge” variable, a period, and finally a new line.
Solution
int myAge; = 21; myAge .Write("My age is " + myAge + ".\n"); Console
- declare an
(Bonus) Give examples of situations where the adage “Spaces and new lines do not matter in programs” is actually erroneous.
Solution
Spaces and newlines matter when they are used in
string
data, as blank space in strings is formatted exactly how it is typed. Blank spaces also matters in between words: words in C# must have at least one space between them in order to be compiled correctly (e.g.,static void Main()
andint days = 7;
). If there were no spaces in either of the examples, neither of them would compile. They also matter for in-line comments.// My comment int x; = 10; x
If you remove the first newline, the program would not compile. Last but not least, new lines and space matter for readability purposes.
Quiz 2
(2 pts) What is the relational operator used to determine whenever two values are equal?
Solution
The operator is two equal signs,
==
, not to be confused with a single equal sign,=
, used for assignment.(2 pts) Write a
boolean
expression that evaluates totrue
if a variableyourName
is different from"Marc"
and"Mark"
.Solution
A possible solution is:
yourName != "Marc" && yourName != "Mark"
. Note that there was no need to write anif
statement or a complete statement: only the expression was required.(5pts) Write a
boolean
expression that evaluates totrue
if a variablex
is between -10 (excluded) and 10 (included).Solution
A possible solution is:
x > -10 && x < 10
Note that there was no need to write an
if
statement or a complete statement: onyl the expression was required.(3 pts) What will be displayed on the screen by the following program?
int x = 5, y = 1, z = 2; if (x != z || y < z ) {x += y;} if (z > y) {if (z % 2 == 0) {z -= 3;} else {z += x;}} else {x = y + z;} .WriteLine($"x is {x}, y is {y}, and z is {z}."); Console
Solution
This program would display:
```{text} x is 6, y is 1, and z is -1.
Press any key to continue… ```
(8 pts) Assume we initialized a
string
variable namedmonth
and adouble
variable namedtemperature
. Write a series of statements that will display exactly one of the following messages: “What a nice summer day!” ifmonth
is “July” andtemperature
is less than 90 (included); “Better wear a jacket” iftemperature
is between 45 and 60 (both included); “Happy holidays!” ifmonth
is “December”; or “Have a nice day” otherwise.Solution
if(month=="July" && temperature<=90) Console.WriteLine("What a nice summer day!"); else if (temperature >= 45 && temperature <= 60) Console.WriteLine("Better wear a jacket!"); else if (month == "December") Console.WriteLine("Happy Holidays!"); else Console.WriteLine("Have a nice day!")
(Bonus) Give a program that displays “Leap year” if a
year
variable is- divisible by 4; and
- not divisible by 100, unless it is also divisible by 400.
Your program should correctly identify 2000 and 2400 as leap years, and 1800, 1900, 2100, 2200, 2300, or 2500 as not leap years.
Solution
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { .WriteLine("The year " + year + " is a leap year."); Console} else { .WriteLine("The year " + year + " is not a leap year."); Console}
Quiz 3
(7 pts) Write a
switch
statement that sets adecimal
price
variable to 1.50 if a string variableiceCreamFlavor
contains"vanilla"
, 1.75 if it contains"chocolate"
or"mint"
, and -1 otherwise.Solution
switch(iceCreamFlavor) { case "vanilla": = 1.50m; price break; case "chocolate": case "mint": = 1.75m; price break; default: = -1; price break; }
(2 pts) Write a statement that applies the increment operator in prefix position to a variable
test
.Solution
The increment operator (
++
) in prefix position (that is, applied before anything else) applied to the variabletest
gives:++test;
.(3 pts) What will be displayed on the screen by the following program?
int x = 10; --; xwhile(x > 0){ .Write(x); Console}
Solution
This would display
9
(without new line or space) forever.(8 pts) Write a
while
loop that displays “1 2 3 4 5 6 7 8 9 10 11 12 13” (spaces included!) at the screen.Solution
There are numerous different ways of writing such a program. A compact one could be:
int num = 1; while(num <= 13)Console.Write($"{num++} ");
while a more verbose could be:
int num = 1; while(num <= 13){ .Write($"{num} "); Console++; num}
(+3+2 pt, bonus) Give a program that displays every multiple of 3 between 0 and 10,000 (that is, “0 3 6 9 12 … 9999”). Bonus (again!): display how many such numbers there are in total.
Solution
We can either
Display the counter only if it is a multiple of three:
int counter = 0; while(counter <= 1000){ if (counter % 3 == 0){Console.Write(counter + " ");} ++; counter}
Increment the counter 3 by 3:
int counter = 0; while(counter <= 1000){ .Write(counter + " "); Console+=3; counter}
To answer the “bonus within the bonus”, we need two counters:
int threeCtr = 0; // Counter for the multiple of 3. int multipleCtr = 0; // Counter that sum the number of values displayed while(threeCtr < 10000) { .Write($"{threeCtr} "); Console+= 3; // We move to the next multiple of 3. threeCtr ++; // We increment the number of values displayed. multipleCtr} .WriteLine($"\nThere are {multipleCtr} multiples of 3 from 0 to 10,000."); Console