Exercises
May 22, 2024 (01:30:36 PM)
Homework #1
Part I — Questions
List five pieces of software, and three hardware components of a computer.
List four programming languages.
What is a GUI?
What is a CLI?
What, if any, is the difference between a compiler and an assembler?
Is machine code (or the machine language program) is made of circuits, binary numbers, classes, or compilers?
Give a specific characteristic of C# compared to other programming languages.
What happens when the source code you are giving to the compiler has a syntax error?
Is the C# compiler case-sensitive?
Suppose I replace every empty space in your source code with two empty spaces. Will your program still compile? Why, or why not?
Give three 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.
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.
What is the limitation, if any, to the number of methods you can have per class? Why is the method called
Mainspecial?What is the difference between a “rule” and a “convention” in programming language?
What is a namespace?
In a C# program, can comments start with
\\(double backslash) or with//(double (forward) slash)? Do they have to end with a;(semicolon)?Which of the following, if any, are keywords?
Welcome1 public apples int "I’m a string"Which of the following are programmer-defined names (or identifiers)?
BankAccount class apples int itemPerCapita statementWhy are variables called “variables”?
What is string interpolation?
What is the difference, if any, between
12, and"12"?What is the difference, if any, between the
WriteLineandWritemethods?Write a statement that would display the following on the screen:
Hi Mom!↵ How 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}");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}.");Which of the following are correct identifier names?
$myHome3 class my%variable ANewHope _train _ThisIsAVariable statementIs the namemyVariablethe same asmyvariable? If not, why?Which of the following are correct identifier names?
myClass _Exo_1 Lab3-Exo1 My.Lab.Variable using Lab3_Part1Which of the following are keywords?
myClass static Lab3-Exo1 “Hello World” using Lab3_Part1Which of the following are correct identifier names?
12_Dec_2019 Lab3-Exo1 MyClass2 My.Lab.Variable string My_VarWhich one(s) of the following, if any, is a correct assignment (assuming that
variable,xandappleshave been declared asintvariables)?5 => variable;x=5;apples= 23x <= 23;variable =1,890;Write a statement that assigns the value 23 to a variable
myAgeof typeint. You do not need to re-declare that variable.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
usingstatements ].” - “An identifier can contain [ only lower-case letters | 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!"); }
Homework #2
Part I — Questions
In C#, what is the “escape character”? Why is it useful?
Write a statement that initializes a variable named
myHeightInMetersto your height in meters. What should be the datatype ofmyHeightInMeters?Suppose you replace every
*in your program with the!symbol. Are you completely sure that your program would still compile? Why or why not?Give the values of
aandbafter the following four instructions have been executed.int a, b; a = 2; b = a * 2 + 1; a -= 1;Give the values of
aandbafter the following four instructions have been executed.int a, b; a = 4; b = a * 3 + 1; a /= 2;Give the values of
canddafter the following four instructions have been executed.int c = 3, d; d = 2 + c; c = d * 2; d += 2;Is there an error in the following code? Explain the error or give the value of
bafter the second statement is executed.float a = 3.7f; int b = (int)a;Is there an error in the following code? Explain the error or give the value of
bafter the second statement is executed.decimal a = 1.6M; int b = (int)a + a;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
bvariable.decimal a = 2.5M; int b = a / 2;If one of the operator’s operands is of type
floatand the other is of typeint, what will be the type of the result of the operation?What is the return type of the operation
12.4 * 3?Write an explicit conversion from a
doublevariablemyDoubleVarto anintvariable calledmyIntVar. You do not need to re-declare those variables. AssumingmyDoubleVar’s value is 5.89, what value would be stored inmyIntVar?Write a statement that performs an implicit conversion between two different numeric datatypes.
Assuming that
myLastNameandmyFirstNameare twostringvariables that have been initialized, write a statement that concatenates them with a space and a comma in-between, and assign the resultingstringto a variable namedfullName. For instance, if the value ofmyLastNameis"Holbertonand", and the value ofmyFirstNameis"Betty", then the value offullNameafter your operation should be"Holbertonand, Betty".In C#, what is the name of the method used to read input from the user?
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();Will those statements, if placed in a proper
Mainmethod, compile? Could this program crash at execution time? Justify your answer.int myAge; Console.WriteLine("Please enter your age:"); myAge = int.Parse(Console.ReadLine());Write a series of statements that: a) Declare an
intvariable 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 theuserAgevariable. You can add statement(s) performing intermediate steps if you want.Write a series of statements that: a) Declare an
stringvariable 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 thefavoriteColorvariable. 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.
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 + 7Subtraction -x − 7 myVar - 7Multiplication *x × 7 myVar * 7Division /x/7, or x ÷ 7 myVar / 7Remainder (a.k.a. modulo) %x mod 7 myVar % 7Computing operations involving one of them is straightforward:
Operation Result 3 + 473 - 4-13 * 4126 / 236 % 42But things can get complicated when multiple operators are used, but no parenthesis are indicated. For instance, should
7 / 2 - 4 * 8 % 3be 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 * 8will 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 * 8will be evaluated as (4 ÷ 2) × 8 = 16 and
4 - 2 + 8will 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 * 7x * (3 % 5) - y * 7(x * 3) % 5 - y * 7x * 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 + 512 + -23 / 12 % 390 * 23 / 34 - 12 - 1312 % 83 - 2 * 3
(Optional) Check your answers using your IDE. You can use a statement of the form:
Console.WriteLine($"8 - 39 * 1 / 12 + 5 is {8 - 39 * 1 / 12 + 5}");
Write down, on a piece of paper, a fully compilable program that initializes an
intvariable namedpersonswith the value 5, anintvariable namedbottleswith the value 3, and adoublevariable namedliterPerBottlewith the value 1.5. What should be the type of theliterPerPersonvariable 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.
Write down, on a piece of paper, a program that:
- Declares a
stringvariable nameduserName. - Displays on the screen “Please enter your name, followed by enter:”.
- Reads a
stringvalue from the keyboard and assigns the value to theuserNamevariable. - Declares an
intvariable namednumber. - Displays on the screen “Please enter your number:”.
- Reads an
intvalue from the keyboard and assigns the value to thenumbervariable. - Declares a
stringvariable namedidand initializes it with the string referenced by theuserNamevariable, 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
idvariable.
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”?
Fill in the blanks: “A class asserts that every objects created using it should have ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ (i.e.,”data”) and ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ (i.e., “operations”).”
Give two access modifiers.
What, if any, is the difference between a parameter and an argument?
Write a statement that creates a new object from the
Rectangleclass.What is the purpose of the keyword
new?Do different objects from the same class share their instance variables?
Briefly explain the difference between a local variable and an instance variable.
Suppose we have a
Circleclass containingpublic void SetRadius(double radiusArgument) { radius = radiusArgument; }Write a statement that create a
Circleobject, and one statement that sets its radius to 3.5.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 - 23 % 2 + 32 - 3 + 3 * 22 + 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
ToStringmethod. 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.What does the keyword
returndo?Write a get method for an instance variable named
totalof typeint.Write a getter for an attribute of type
stringnamedmyName.Write a setter for an attribute of type
intnamedmyAge.Assuming
nameis astringinstance variable, there is problem with the following setter. Fix it.public int SetName(string val){ name = val; }Assume we have an instance of the
Rectangleclass namedmyRectand an instance of theCircleclass namedmyCircle. Write statement(s) that will make the radius ofmyCircleequal to the width ofmyRect.Briefly describe what a format specifier is. Write a statement that uses one.
Write a statement that uses a format specifier.
Write a method for the
Rectangleclass that divides the length and width of the calling object by a factor given as a parameter.Draw the UML diagram of a class named “Student” with a single attribute, “name”, of type
string, and two methods,SetNameandGetName.Write a
ToStringmethod for aAccountclass with two attributes, astringattribute callednameand adecimalattribute calledamount.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?
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
Mainmethod?Is it possible to have more than one constructor defined for a class? If yes, how can C# know which one is called?
What is the name of a constructor method? What is the return type of a constructor?
Write a constructor for a
Sodaclass with onestringattribute calledname.Assume we have a
Polygonclass, that have only one attribute, anintcallednumberOfSides. Write a constructor for that class.What is the “default” constructor? Do we always have the possibility of using it?
What is the return type of a
ToStringmethod? How many arguments does it usually take?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
Bookobject. - Write a “getter” and a “setter” for the
titleattribute. - Write a constructor for the
Bookclass taking at least one argument (you are free to decide which one(s)).
- 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
titleattribute. - Write a constructor for the
DVDclass that takes two arguments. - Write a method called
Discountthat decreases thepriceattribute by 20.55%. - Write a (good, informative)
ToStringmethod for the class. - Write statements that ask the user to enter a price and then create
a
DVDobject with apriceattribute equal to the price the user entered. (The object’stitleattribute 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.
- Write a “setter” for the
Consider the following partial class definition:
class Book { private string title; private decimal price; }- Write a “getter” for the
titleattribute. - Write a constructor for the
Bookclass that takes two arguments. - Write a method called
AddTaxesthat increases thepriceattribute by 6.35%. - Write a (good, informative)
ToStringmethod for that class. - Write statements that ask the user to enter a price and then create
a
Bookobject with apriceattribute equal to the price the user entered. (The object’stitleattribute 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.
- Write a “getter” for the
Assume that my
Petclass contains one custom constructor:public Pet(string nameP, char genderP){ name = nameP; gender = genderP; }What is the problem with the following statement?
Pet myPet = new Pet('M', "Bob");Why would one want to define a constructor for a class?
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 twodoubleattributes,angle1andangle2. We want to define several methods:- a no-arg constructor that sets the value of
angle1to 60.0 and the value ofangle2to 60.0, - another constructor, that takes two arguments, and assigns to
angle1the value of the first argument, and assigns toangle2the value of the second argument, - getters for
angle1andangle2, - 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
Triangleclass. - Write the full, compilable implementation of the
Triangleclass.
- a no-arg constructor that sets the value of
Homework #4
Part I — Questions
What is sequential processing?
What is a decision structure?
Decide if the following boolean expressions will evaluate to
trueorfalse:3 > 2.0 && false(4 != 3) || false'A' == 'b' && ! false(! false) == (true || 4 == 3)
Decide if the following Boolean expressions will evaluate to
trueorfalse:3 > 2.0 || true(4 != 3) && false'A' == 'b' || ! false(! true) == (true || 4 != 3)
For each of the following Boolean expressions, decide if it will evaluate to
trueorfalse:('y' == 'Y') && true6 + 2 < 8 || 3 > 4(true && 4 == 3) == false4 > 4 && !false
For each of the following Boolean expressions, decide if it will evaluate to
trueorfalse:('y' != 'Y') && true6 + 2 < 12 || 3 > 4(true && 4 >= 3) == false13 <= 4 * 3 || !false
What relational operator is used to determine whenever two values are different?
How do you store the result of a Boolean expression?
Give three relational operators, and then two logical operators.
What would be displayed on the screen by the following code?
if (false) { Console.WriteLine("Hello!"); } Console.WriteLine("Hi!");Is there a simpler way to write the expression
over21 == true, assuming thatover21is a Boolean variable?Assume that
xandyare twointvariables that have already been initialized (i.e., declared and assigned), write anifstatement that assigns 10 toxifyis (strictly) greater than 5.In C#, is there a difference between
=and==? Write a statement that uses=.Assuming a
namestring was declared and initialized with a value given by the user, write anifstatement that displays “I have the same name!” ifnamecontains your first name.Is the following statement correct, i.e., would it compile, assuming
myFlagis aboolvariable, andmyAgeis an initializedintvariable?if ( myAge > 20 ) { myFlag = true };If we write a statement that begins with
if(false), then the IDE returns a warning, “Unreachable code detected”. What does it mean?Write an
ifstatement that prints “Bonjour !” if the value of thecharvariablelangis'f'.For each of the following boolean expressions, decide if it will evaluate to
trueorfalsewhen the boolean variablesx,yandzare 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.Write a
booleanexpression that evaluates totrueif a variablexis between 3 (excluded) and 5 (included).Write an
if-elsestatement that assigns 0.1 tozifyis greater or equal than 0, and that assigns −0.1 tozotherwise.Write an
if-elsestatement that assigns"Minor"to an already declaredstringvariablelegalStatusifageis strictly less than 18, and that assigns"Major"tolegalStatusotherwise.Write an
if-elsestatement that displays “It’s free for you!” if anintvariableageis between 0 and 18, and “It’s $5.00.” otherwise.Assume we initialized an
intvariable calledcourseNumberand astringvariable calledcourseCode. Write a series of statements that will display:- “I’m taking this class!” if
courseNumberis1301andcourseCodeisCSCI; - “That’s my major!” if
courseCodeisCSCI; - “Is that an elective?” if
courseNumberis greater than 3000; or - “Is it a good class?” otherwise.
Your program should display exactly one message.
- “I’m taking this class!” if
Assume we previously initialized an
intvariable calledgraduationYearand astringvariable calledgraduationSemester. Write a series of statements that will display:- “I will graduate at the same time!” if
graduationYearis2023andgraduationSemesterisFall; - “I love this season.” if
graduationSemesterisSpring; - “That is in a long time!” if
graduationYearis greater than 2025; or - “I hope you’ll have an in-person ceremony!” otherwise.
Your program should display exactly one message.
- “I will graduate at the same time!” if
Assume we previously initialized a
charvariable 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.
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;} Console.WriteLine($"x is {x}, y is {y}, and z is {z}.");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;} y -= 4; Console.WriteLine($"x is {x}, y is {y}, and z is {z}.");(We’ll use the 24-hour clock, sometimes called “military time”.) Assuming that an
intvariablehourhas been initialized, write part of a program that would display on the screen “Good morning” ifhoursis less than or equal to 12, and “Hello” otherwise.Assuming that
myStringis a string variable, write a statement that prints “Hello, Melody!” if the value ofmyStringis equal toMelody, and nothing otherwise.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;}} Console.WriteLine($"x is {x}, y is {y}, and z is {z}.");Rewrite, if possible, the three following
if-else-ifstatements asswitchstatements:if (myLang == 'f') { Console.WriteLine("Vous parlez Français ?"); } else if (myLang == 'e') { Console.WriteLine("Do you speak English?"); } else if (myLang == 'd') { Console.WriteLine("Sprechen Sie Deutsch?"); } else { Console.WriteLine("I do not know your language!"); }if (myCity == "Augusta") { Console.WriteLine("I also live here!"); } else if (myCity == "Ithaca" || myCity == "Providence") { Console.WriteLine("I used to live there!"); } else { Console.WriteLine("I never lived there."); }if (temp == 100.0) { Console.WriteLine("It's ready!"); } else if (temp >= 90.0) { Console.WriteLine("Almost ready!"); } else { Console.WriteLine("You have to wait."); }If you think it is not possible or not feasible, explain why.
Give an example of an
ifstatement that could not be rewritten as aswitch.
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-ifstatements, the other usingswitch?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!
Homework #5
Part I — Questions
Assume you are given an un-assigned
stringvariableletterGrade, and an already assignedfloatvariablenumberGrade. Write a small program that assigns"A"toletterGradeifnumberGradeis between 100 and 90 (both included),"B"toletterGradeifnumberGradeis between 90 (excluded) and 80 (included), etc., and"Invalid data"ifnumberGradeis strictly lower than 0 or strictly greater than 100. Should you use aswitchstatement or aif…else if…else?Given an
intvariablecounter, write three statements to decrement its value by 1.What will be displayed on the screen?
int x = 3, y = 7; Console.WriteLine (x++ +" and "+ --y);What will be displayed on the screen by the following program?
int counter = 2; while (counter != 5) { Console.Write(counter + "\n"); counter++; }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--; Console.Write(counter + "\n"); if (counter == 7) { Console.WriteLine("Bingo"); } }What will be displayed on the screen by the following program?
int counter = 10; while (counter != 5) ; Console.Write(counter + "\n"); counter--;What will be displayed on the screen by the following program?
int counter = 7; while (counter != 2) Console.Write(counter + "\n"); counter--;What is input validation? Name a control structure that can be used to perform it. Why is it important?
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?
What is a sentinel value?
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.
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.
Write a program containing a
whileloop that would display the numbers between -100 and 100 (both included) with a space between them when executed.Assume you are given an initialized
stringvariablename, and astringvariablefield. Write a small program that assigns tofield- “CS” if
nameis “Turing” or “Liskov”, - “Math.” if
nameis “Aryabhata” or “Noether”, - “Unknown” otherwise.
- “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.
Part II – Problems
Write a
switchstatement that calculates the number of days in a particular month. You should assume that you are given already assignedmonthandyearintvariables, and that your program should set an already declaredintnumberOfDaysvariable to 28, 29, 30 or 31 depending on the month / year combination. Your program should start with aswitchmatchingmonthagainst certain values, and, ifmonthis 2, uses anifstatement to decide whenever the number of days is 28 or 29. You can use something likeswitch (month) { … case (2): if … … break; … }
Homework #6
Part I — Questions
Write a statement that creates a 10-element
intarray namednumbers.In the following, what is the value of the size declarator? What is the value of the index?
int[] numbers; numbers = new int[8]; numbers[4] = 9;What is wrong with the following array declaration?
int[] books = new int[-1];Draw the content of the
scoresarray once those statements have been executed.int[] scores = new int[3]; scores[0] = 13; scores[2] = 25;What will be displayed on the screen by the following program?
for (int num = 3 ; num <= 5 ; num++) Console.Write(num + " ");Write a ‘for’ loop that displays on the screen the sequence “1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ”.
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).
Write a ‘for’ loop that displays on the screen the sequence “1 3 5 7 9 ”.
Given an
intvariablemyVarinitialized with a positive value, write a loop that sums the integers between 0 andmyVar(i.e., 0 + 1 + ⋯ + (myVar − 1) + myVar).Consider the following code:
for (int y = 1; y <= 3; y++) { for (int z = 1; z < 5; z++) Console.Write("Scene " + y + ", take " + z + ". " ); Console.WriteLine(); }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)?
Which of the following are pre-test loops?
do while,switch,while,forandif-else-if.What will be displayed on the screen by the following code?
int[] values = new int[6]; for (int i = 0 ; i < 6 ; i++) values[i] = (i*2); foreach (int j in values) Console.WriteLine(j);Suppose we are given an
intarraydailyPushUpwith 7 elements. Write a piece of code that display the value of the elements stored in the arraydailyPushUp.What is “array bounds checking”? When does it happen?
What would be the size of the
testarray after the following statement has been executed?int[] test = {3, 5, 7, 0, 9};What is the difference, if any, between the following two statements?
int[] num, scores; int num[], scores;Write a statement that creates and initializes a
doublearray with the values 12.5, 89.0 and 3.24.What is the value of
countand the content ofnumberonce the following has been executed?int count=2; int[] number={3, 5, 7}; number[count--] = 8; number[count]--;Suppose we have an array named
tempthat has been declared and initialized. How can we get the number of elements in this array?Describe what the following code would do.
int[] record = { 3, 8, 11 }; int accumulator = 0; foreach (int i in record) accumulator += i;Assuming we have two
intarrays of the same size,firstAandsecondA, write a program that copies the content offirstAintosecondA.Assuming we are given an
intarray namedarrayF, write a program that adds one to each of its elements. That is, ifarrayFcontains 3, 5, 7 and -2 before your program is executed, it should then contain 4, 6, 8 and -1 after your program was executed.Assuming we are given an
intarray namedarrayF, write a program that displays the product of its elements. That is, ifarrayFcontains 2, 3 and -1, then your program should display -6.Write a static method (header included) that takes as argument an
intarray, and display on the screen the value of each element of that array.Write a static method (header included) that takes as argument an
intarray, and stores the value 10 in each element of that array.
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.
(4pts) Circle the correct identifiers:
%Ratestaticmy-variableUser.InputYoUrNaMe21test_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. (4 pts) Write a statement that would display, “Hi Mom!” (with the quotes) followed by a new line on the screen.
(5 pts) Write a series of statements that would
- declare an
intvariable 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.
- declare an
(Bonus) Give examples of situations where the adage “Spaces and new lines do not matter in programs” is actually erroneous.
Quiz 2
(2 pts) What is the relational operator used to determine whenever two values are equal?
(2 pts) Write a
booleanexpression that evaluates totrueif a variableyourNameis different from"Marc"and"Mark".(5pts) Write a
booleanexpression that evaluates totrueif a variablexis between -10 (excluded) and 10 (included).(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;} Console.WriteLine($"x is {x}, y is {y}, and z is {z}.");(8 pts) Assume we initialized a
stringvariable namedmonthand adoublevariable namedtemperature. Write a series of statements that will display exactly one of the following messages: “What a nice summer day!” ifmonthis “July” andtemperatureis less than 90 (included); “Better wear a jacket” iftemperatureis between 45 and 60 (both included); “Happy holidays!” ifmonthis “December”; or “Have a nice day” otherwise.(Bonus) Give a program that displays “Leap year” if a
yearvariable 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.
Quiz 3
(7 pts) Write a
switchstatement that sets adecimalpricevariable to 1.50 if a string variableiceCreamFlavorcontains"vanilla", 1.75 if it contains"chocolate"or"mint", and -1 otherwise.(2 pts) Write a statement that applies the increment operator in prefix position to a variable
test.(3 pts) What will be displayed on the screen by the following program?
int x = 10; x--; while(x > 0){ Console.Write(x); }(8 pts) Write a
whileloop that displays “1 2 3 4 5 6 7 8 9 10 11 12 13” (spaces included!) at the screen.(+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.