GIFT PROGRAMMING
GIFT PROGRAMMING
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF
Introduction
The C# programming language allows you to develop different types of applications, such as:
3. 2D and 3D Games
5. Cloud-based applications
6. Applications mobiles
Applications are all made up of many lines of code, which work together to complete a task. The best
way to learn to code is to write code. It is recommended that you write code alongside the exercises in
this module and the other modules in this learning path. By writing the code for each exercise yourself
and completing the small programming challenges, you'll accelerate your learning.
You'll also start learning the little fundamental concepts and use them to practice and explore
continuously.
4. Identify the various elements of C# syntax such as operators, classes, and methods.
By the end of this module, you will be able to write C# code to display a message in the standard output
of a console such as Windows Terminal. These lines of code will give you a first look at C# syntax and
provide valuable information right away.
In this first hands-on exercise, you'll use C# to display any programmer's consecrated phrase in the
standard output of a console.
There's a long-standing tradition among developers to display the phrase "Hello World!" in the
console's release window. As you'll see, you can learn more about programming and the C#
programming language from this simple exercise.
The .NET editor and output console provide a great in-browser experience, which is perfect for this
approach to the tutorial. The .NET editor is on the right side of this web page. The output console is
located underneath.
1. Enter exactly the following code in the .NET editor on the right:
Console.WriteLine("Hello World!");
We will soon explain how it works and how it works. But first, you need to see it run and verify that
you have entered it correctly. To do this, you'll run your code.
1. It compiles your code into an executable format that the computer can understand.
2. It runs your compiled application and, if the code is written correctly, generates "Hello
World!" at the exit.
1. In the output console, observe the result of your code. You should get the following output:
Hello World!
Writing C# code is an exercise in precision. If you type a single character incorrectly, you see an error
message in the output box when you run the code.
For example, if you incorrectly enter a lowercase "c" in the word console as follows:
console.WriteLine("Hello World!");
(1,1): error CS0103: The name 'console' does not exist in the current context
The first part (1,1) shows the row and column where the error occurred. But what does this error message
mean?
C# is a case-sensitive language, which means that the C# compiler considers the words console and
console as different as the words cat and dog. Sometimes, the error message can be a bit misleading.
You need to understand the real reason why the error exists, and for that, you need to get to know the
syntax of C# better.
Similarly, if you used single quotation marks (') to surround the literal string Hello World! as follows:
Console.WriteLine('Hello World!');
This time, the culprit is character 19 in line 1. This message can be used as a clue while investigating
the issue. But what does the error message mean? What exactly is a "character literal"? You'll learn more
about the literals of different data types (including character literals) a little later. For now, be careful
when entering code.
Fortunately, mistakes are never definitive. All you have to do is spot the error, fix it, and relaunch your
code.
If an error occurred while running your code, take the time to take a close look at it. Examine each
character and verify that you have entered that line of code exactly.
3. Forget double quotes or use single quotes to surround the phrase Hello World!
The Code Editor highlights precompilation errors, making it easy for you to identify and fix errors as
you develop your code. You can think of it as a spell checker that helps you correct grammar or spelling
mistakes in a document.
In this task, you'll comment out the previous line of code, and then add new lines of code in the .NET
editor to display a new message.
1. Edit the code you've written to precede it with a code comment with two slashes //:
// Console.WriteLine("Hello World!");
To create a code comment, precede the line of code with two slashes //. This prefix tells the compiler to
ignore all instructions in that line.
Code comments are useful when you're not yet ready to delete the code, but want to skip it for now. You
can also use code comments to add messages to your own attention or to the attention of others (who
might read the code later), reminding them of what the code does.
Console.Write(" ");
2. Press the green Run button again. This time, the following output should be displayed.
The three new lines of code you added showed the difference between the Console.WriteLine() and
Console.Write methods.
Console.WriteLine() prints a message to the output console. At the end of the line, it adds a line break,
as if pressing Enter or Return to create a new line.
To display content in the output console, but without adding a line break at the end, you use the second
technique, Console.Write(). Thus, the next call to Console.Write() displays another message on the same
line.
Update message
Console.WriteLine("Congratulations!");
2. Press the green Run button again. This time, the following output should be displayed.
Congratulations!
This code helps you illustrate the difference between the two methods. A new line is added by
Console.WriteLine() and Console.Write() prints the output to the current line.
To understand how your code works, you need to take a step back and think about what a programming
language is. You also need to think about how your code communicates your commands to the computer.
Programming languages such as C# allow you to write instructions that you want the computer to
execute. Each programming language has its own syntax. However, once you've learned your first
programming language and started learning another, you'll quickly realize that they share many
concepts. The purpose of a programming language is to allow human beings to express their intention
in a way that is understandable and readable by people. The instructions you write in a langage de
programmation sont appelées « code source » ou simplement « code ». Les développeurs écrivent du
code.
À ce stade, un développeur peut mettre à jour et modifier le code, mais l’ordinateur ne peut pas
comprendre le code. En effet, le code doit d’abord être compilé dans un format que l’ordinateur peut
comprendre.
Un programme spécial appelé compilateur convertit votre code source dans un autre format, que le
processeur de l’ordinateur peut exécuter. Lorsque vous avez utilisé le bouton vert Exécuter dans l’unité
précédente, le code que vous avez écrit a d’abord été compilé, puis exécuté.
Pourquoi le code doit-il être compilé ? Même si la plupart des langages de programmation semblent
énigmatiques à première vue, ils peuvent être plus facilement compris par des humains que le
langage privilégié par l’ordinateur. Le processeur comprend les instructions, qui sont exprimées par
l’activation ou la désactivation de milliers ou millions de minuscules commutateurs. Les compilateurs
font le lien entre ces deux mondes en traduisant vos instructions lisibles par un humain en instructions
compréhensibles par un ordinateur.
Les règles pour écrire du code C# sont appelées syntaxe. Tout comme les langages humains vis-à-vis de
la ponctuation et de la structure des phrases, les langages de programmation ont des règles. Ces règles
définissent les mots clés et les opérateurs en C# et la manière dont ils sont combinés pour former des
programmes.
Quand vous avez tapé du code dans l’éditeur .NET, vous avez peut-être remarqué que la couleur des
différents mots et symboles a légèrement changé. La coloration syntaxique est une fonctionnalité utile
que vous commencerez à utiliser pour repérer facilement les erreurs dans votre code qui ne sont pas
conformes aux règles de syntaxe de C#.
Regardons de plus près la ligne de code suivante que vous avez écrite :
Console.WriteLine("Hello World!");
Quand vous avez exécuté votre code, vous avez vu que le message Hello World! s’est affiché dans la
console de sortie. Lorsque la phrase est entourée de guillemets doubles dans votre code C#, elle est
appelée chaîne littérale. En d’autres termes, vous vouliez littéralement que les caractères H, e, l, l, o et
ainsi de suite, soient envoyés dans la sortie.
La partie Console s’appelle une classe. Les classes « possèdent » des méthodes. En d’autres termes, les
méthodes résident dans des classes. Pour accéder à la méthode, vous devez savoir dans quelle classe elle
se trouve. Pour l’instant, considérez une classe comme un moyen de représenter un objet. Dans le cas
présent, toutes les méthodes qui opèrent dans la console de sortie sont définies dans la classe Console.
Il y a aussi un point qui sépare le nom de la classe Console du nom de la méthode WriteLine(). Le point
est l’opérateur d’accès aux membres. En d’autres termes, le point est la façon dont vous « naviguez »
de la classe vers l’une de ses méthodes.
The WriteLine() part is called a method. It is always possible to identify a method by the fact that it is
followed by a set of parentheses. Each method has a specific task. The role of the WriteLine() method
is to write a row of data to the output console. The displayed data is sent between the opening and closing
parentheses as an input parameter. Some methods need input parameters, while others don't. If you want
to call a method, however, you should always use the parentheses after the method name. Parentheses
are called the method call operator.
Finally, the semicolon is the end of the declaration. A declaration is a complete statement in C#. The
semicolon tells the compiler that you have finished entering the command.
Don't worry if all of these ideas and terms don't make sense, for now, just remember that if you want to
display a message in the output console:
4. If you make a mistake, simply identify it, fix it, and then rerun your code
6. It's also important to understand the execution flow. This is because your code statements were
executed in order, one line at a time, until there were no more statements to execute. With some
instructions, the processor must wait before it can continue. You can use other statements to
change the execution flow.
7. Now, let's test what you've learned. Each module includes a simple challenge and, if you get
stuck, we will provide you with a solution. In the next unit, you'll have the option to write code
in C# yourself.
Exercise:
You learned how to display a message in a single line of code and how to display a message with
multiple lines of code. Use both techniques for this challenge. It doesn't matter what technique you apply
to each line and how many ways you use to split one of the messages into multiple lines of code. It's
your choice.
Regardless of which method you choose, your code must produce the specified output.
Chapter 1: Storing and Retrieving Data with Literal and Variable Values in C#
Learning Objectives
4. Allow the compiler to determine the data type of your variable during initialization
Prerequisite
Introduction
Most applications that you will create in C# will require you to work with data. Sometimes, this data
will be hard-coded into your application. Hardcoded values are values that remain constant and
unchanged throughout the execution of the program. For example, you may need to display a message
to the user when an operation succeeds. A "success" message will probably be the same every time the
application runs. This hard-coded value can also be called a constant or literal value.
Suppose you want to display a formatted message to the end user that contains different types of data.
The message will include hard-coded strings, combined with information collected by your app from
the user. To display a formatted message, you must create hard-coded values and define variables that
can store data of a certain type, whether numeric, alphanumeric, and so on.
In this module, you'll create literal values that contain different types of data. You'll create variables that
can contain certain types of data, set those variables with a value, and then retrieve those values later in
the code. Finally, you'll learn how you can simplify your code by allowing the compiler to do some of
the work.
By the end of this chapter, you'll be able to create literal values, as well as store and retrieve data in
variables.
Learning Objectives
4. Allow the compiler to determine the data type of your variable during initialization
Prerequisite
Done100 XP
1. 10 minutes
In this exercise, you view messages that contain other types of data and learn why data types are so
important in C#.
A literal value is a constant value that never changes. Previously, you displayed a literal string in the
output console. In other words, you literally wanted the alphanumeric string H, E, L, L, O, etc., to be
displayed in the output console.
Use the "string" data type whenever you have words, phrases, or alphanumeric data to present, not
calculate. What other kinds of literal data can you display in the output console?
There are many types of data in C#. But as you're just starting out, you only need to know five or six
types of data because they cover most scenarios. View a literal instance of a data type in the output
console.
If you want to display a single alphanumeric character, you can create a char literal by enclosing a
single alphanumeric character in single quotation marks. The term char is short for character. In C#,
this type of data is officially named "char", but is often referred to as a "character".
Note that the letter b is surrounded by single quotation marks 'b'. Single quotation marks create a
character-like literal. Remember that using double quotes creates a string data type.
2. Press the green "Run" button to run your code. You normally see the following output in the
output window:
b
Console.WriteLine('Hello World!');
Note the single quotation marks that surround Hello World!. When you use single quotes, the C#
compiler expects a single character. However, in this case, the syntax used is that of a character literal,
but 12 characters have been provided instead.
Just like the string data type, you use char whenever you have a single alphanumeric character for
presentation (not calculation).
If you want to display an integer numeric value (without fractions) in the output console, you can use
an int literal. The term int is short for "integer," which should remind you of your math classes. In C#,
this type of data is officially named "int", but is often referred to as "integer". An int literal type does
not require any additional operators such as string or char.
Console.WriteLine(123);
2. Press the green "Run" button to run your code. You normally see the following output in the
output console:
123
A floating-point number is a number that contains one decimal place, such as 3.14159. C# supports three
types of data to represent decimal numbers: float, double, and decimal. Each type supports varying
degrees of accuracy.
Float Type Precision
----------------------------
Here, precision reflects the number of digits after the decimal separator that are exact.
2. Press the green "Run" button to run your code. You normally see the following output in the
output console:
0.25
Note that the float data type is the least accurate. It is therefore recommended to reserve its use for fixed
fractional values to avoid unexpected calculation errors.
0.25
To create a double literal, simply enter a decimal number. The compiler defaults to a double literal when
a decimal number is entered without a literal suffix.
4. Press the green "Run" button to run your code. You normally see the following output in the
output window:
2.625
Console.WriteLine(12.39816m);
To create a decimal literal, add the letter m after the number. In this context, m is called a literal suffix.
The literal suffix tells the compiler that you want to use a decimal value. You can use a lowercase (m)
or uppercase (M) for the literal suffix of a decimal value.
6. Press the green "Run" button to run your code. You normally see the following output in the
output console:
12.39816
If you want to display a value representing true or false, you can use a bool literal.
The term bool is an abbreviation for Boolean. In C#, the official term is "bool", but developers often use
the term "Boolean".
Console.WriteLine(true);
Console.WriteLine(false);
2. Press the green "Run" button to run your code. You normally see the following output in the
output console:
True
False
Bool literals represent the idea of true and false. You'll use a lot of bool values when you start adding
decision logic to your apps. This is because you'll need to evaluate expressions to see if they're true or
false.
Data types play a central role in C#. In fact, the focus on data types is one of the key features that sets
C# apart from other languages such as JavaScript. C# designers believed that they could help developers
avoid common software bugs by applying data types. You'll learn about this concept as you learn C#.
Earlier, you saw that the string and char types are used for "presentation, not calculation". If you need
to perform a mathematical operation on numeric values, you must use int or decimal values. If you have
data that is only used for presentation or text manipulation purposes, you should use the string or char
data type.
Suppose you need to collect data from a user, such as a phone number or zip code. Depending on your
country/region of residence, this data may consist of numeric characters. However, since you rarely
perform mathematical calculations on phone numbers and zip codes, you should prefer to use a string
data type when manipulating them.
This also applies to bool values. If you need to work with the words "true" and "false" in your
application, you must use a string value. However, if you need to use the concept of true or false values
when you perform an evaluation, you use a bool value.
It's important to know that these values can look like their string literal equivalents. In other words, you
might think of the following statements as the same:
Console.WriteLine("123");
Console.WriteLine(123);
However, it's only the output displayed that looks similar. The thing is, the things you can do with the
Console.WriteLine("true");
underlying int or bool data types will be different from their string equivalent.
Console.WriteLine(true);
Summary
The main takeaway is that there are many different types of data, but you'll focus on a few for now:
1. string for words, phrases, or alphanumeric data intended for presentation, not calculation
A literal is literally a hard-coded value. Hardcoded values are values that remain constant and unchanged
throughout the execution of the program. However, most applications require you to use values that you
don't know much about at first. In other words, you will have to work with data from users, files, or the
network.
When you need to use data that is not hard-coded, you declare a variable.
What is a variable?
A variable is a container that stores a type of value. Variables are important because their values can
change, or vary, during the execution of a program. Variables can be assigned, read, and modified.
Variables allow you to store the values that you want to use in your code.
A variable name is a user-friendly label that the compiler assigns to a memory address. When you want
to store or change a value in this memory address, or retrieve the value stored there, you just need to use
the name of the variable you created.
Declaring a variable
To create a variable, you must first declare its data type and then give it a name.
string firstName;
In this case, you create a string variable called firstName. Now, this variable can only contain string
values.
You can choose any name, as long as it follows a few C# syntax rules for naming variables.
A software developer once famously said, "The hardest part of software development is giving things a
name." Not only should the name of a variable follow certain syntax rules, but it should also be used to
make the code more readable and understandable. That's a lot to ask of a single line of code!
1. Variable names can contain alphanumeric characters and the underscore. Special characters
such as the hash symbol # (also known as the number symbol or pound symbol) or the dollar
dollar sign are not allowed.
2. Variable names should begin with a letter of the alphabet or an underscore, not a number.
3. Variable names are case-sensitive. Thus, string Value; and string value; are two different
variables.
4. Variable names must not be a C# keyword. For example, you cannot use the following variable
declarations: decimal decimal; or string string;.
There are coding conventions that keep variables readable and easy to identify. As you develop larger
applications, these coding conventions can help you keep track of variables among other text elements.
1. Variable names must use mixed case. It is a writing style that uses a lowercase letter at the
beginning of the first word and an uppercase letter at the beginning of each subsequent word.
For example: string thisIsCamelCase;.
2. Variable names must begin with an alphabetic letter. Developers use the underscore for special
purposes. Therefore, try not to use them at the moment.
3. Variable names should be descriptive and self-explanatory in your app. Choose a name for your
variable that represents the type of data it will contain.
4. Variable names must be one or more whole words added to each other. Don't use contractions
or abbreviations, because the variable names (and thus, their purpose) may not make sense to
other users reading your code.
5. Variable names must not include the data type of the variable. You've probably seen a tip to use
a style like string strValue;. This advice is no longer valid.
L’exemple string firstName; suit toutes ces règles et conventions, en supposant que vous voulez utiliser
cette variable pour stocker des données qui représentent le prénom d’une personne.
Here are some examples of variable declarations using the data types you've discovered so far:
char userOption;
int gameScore;
decimal particlesPerMillion;
bool processedCustomer;
Summary
1. Variables are temporary values that you store in the computer's memory.
3. To declare a variable, you first select a data type that corresponds to the type of data you want
to store, and then give the variable a name that complies with the rules.
Now that you know how to declare a variable, you'll see how to set, retrieve, and initialize the value of
a variable.
Because variables are temporary storage containers for data, they are designed to be written and read.
You will have the option to perform both in the following exercise.
In this exercise, you'll declare a variable, assign it a value, retrieve its value, and more.
1. Select all the code in the .NET editor, and then tap Delete or Backspace to delete it.
string firstName;
firstName = "Bob";
To declare a variable, you enter the type of data you want to use, followed by a name for the variable.
To assign a value to a variable, you use the assignment operator, which is = (single equal character).
It is important to note that the value assignment is done from right to left. In other words, the C# compiler
must first understand the value to the right of the assignment operator. It can then proceed to assign to
the variable to the left of the assignment operator. If you reverse the order, you'll confuse the C#
compiler.
"Bob" = firstName;
2. Now, run the code. The following error is displayed in the output console:
(2,1): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
You have seen that C# was designed to apply types. When you work with variables, the application of
types does not allow you to assign a value of a particular data type to a variable that is declared to store
another data type.
firstName = "Bob";
2. Now, run the code. The following error is displayed in the output console:
The error message indicates what the C# compiler is trying to do in the background. He has attempted
to "implicitly convert" the string "Bob" to an int value, but this is impossible. Despite this, C# tried to
perform the conversion, but it failed, because there was no numerical equivalent for the word "Bob".
You'll learn more about implicit and explicit type conversion later. For now, keep in mind that a variable
can only contain values that match its declared data type.
To retrieve a value from a variable, you simply use the variable name. This example sets the value of a
variable, then retrieves that value and displays it in the console.
string firstName;
firstName = "Bob";
Console.WriteLine(firstName);
2. Now, run the code. The following error is displayed in the output console:
Bob
Retrieving a value from a variable is also called "getting the variable," or simply getting it.
As you write lines of code, the compiler checks your code for possible errors. The compiler is a great
tool to help you get code correct faster. Now that you are familiar with the different types of errors, you
can quickly correct the errors with the help of the compiler's error messages.
You can reuse and reassign the variable as many times as you want. This example illustrates this idea.
string firstName;
firstName = "Bob";
Console.WriteLine(firstName);
firstName = "Liem";
Console.WriteLine(firstName);
firstName = "Isabella";
Console.WriteLine(firstName);
firstName = "Yasmin";
Console.WriteLine(firstName);
2. Now, run the code. The following error is displayed in the output console:
Bob
Liem
Isabella
Yasmin
You must set a variable to a value before you can retrieve the value of the variable. Otherwise, an error
is displayed.
string firstName;
Console.WriteLine(firstName);
2. Now, run the code. The following error is displayed in the output console:
To avoid the risk of having an unassigned local variable, it is recommended that you set its value
immediately after declaring the variable.
In fact, you can do both declaring and setting the value of the variable in a single line of code. This
technique is called variable initialization.
Console.WriteLine(firstName);
2. Now, run the code. The following error is displayed in the output console:
Bob
Summary
1. You must assign (set) a value to a variable before you can retrieve (get) a value from it.
2. You can initialize a variable by assigning it a value at the time of declaring it.
5. To retrieve the value from the variable, you simply use the variable name.
The C# compiler runs in the background to help you write your code. It can infer the data type of your
variable based on its initialized value. In this unit, you'll learn about this feature, called implicitly typed
local variables.
An implicitly typed local variable is created with the var keyword followed by an initialization of the
variable. Like what:
In this example, a string variable was created with the var keyword instead of the string keyword.
The var keyword tells the C# compiler that the data type is implicit with respect to the assigned value.
Once the type is inferred, the variable works in the same way as if the actual data type had been used to
report it. The var keyword is used to record keystrokes when the types are long or the type is obvious
from the context.
In the example:
Because the message variable is immediately set to the string value "Hello World!", the C# compiler
understands the intent and treats each message instance as a string instance.
In fact, the message variable is typed to be a string value and can never be changed. For example,
consider the following code:
message = 10.703m;
If you run this code, you receive the following error message.
It's important to understand that the var keyword depends on the value you use to initialize the variable.
If you try to use the var keyword without initializing the variable, you get an error when you try to
compile your code.
var message;
If you attempt to run this code, when it is compiled, the following output is displayed:
The var keyword has been widely adopted in the C# community. In the code examples provided in the
manuals or online, you will often see the var keyword used instead of the name of the actual data type.
It is therefore important to understand the use of this keyword.
The var keyword is widely used in C#. Often, it is easy to determine the type of a variable based on its
initialization. In these cases, it is easier to use the var keyword. The var keyword can also be useful for
planning an application's code. When you start developing code for a task, you may not immediately
know what type of data to use. Using var can help you develop your solution more dynamically.
At first, it's a good idea to continue using the name of the actual data type when declaring variables,
until you're more comfortable with the code. Using the data type when declaring variables helps you be
determined at the time you write your code.
Summary
1. The var keyword tells the compiler to infer the data type of the variable based on the
initialization value.
2. You'll probably see the var keyword when you read other people's code. However, you should
use the data type when possible.
By the end of this chapter, you'll be able to write code that performs simple operations on the values of
literals and variables.
Learning Objectives
Prerequisite
4. Beginner-level experience with creating literal values and declaring variables of basic data types
such as string, int, and decimal
Introduction
The applications that you will build in C# require you to use both literal and variable numeric data.
Examples should include:
Suppose you want to perform a calculation that converts a value from one unit of measurement to
another. What if you needed to convert the temperature to current Fahrenheit to degrees Celsius, for
example? Once you have calculated the temperature in degrees Celsius, you must display this
information in a formatted message to the user. To do this, you need to learn how to use operators to act
on operands such as values of literals and variables.
In this module, you'll perform simple string and numeric operations on your data. As you'll see, the
compiler will perform different tasks depending on the data types of the values around the given
operator. Most importantly, you will get to understand how operators perform actions on operands.
Learning how to use operators and operands properly will make it easier for you to formulate explicit
instructions in your code.
You will often want to perform mathematical operations on numeric values. In this unit, you'll start with
addition, and then you'll see more operations in the next unit that includes an important lesson for
understanding how the C# compiler parses and interprets your code.
To add two numbers, you'll use the addition operator, which is the plus + symbol. Yes, the same plus +
symbol that you use for string concatenation is also used for addition. Reusing the same symbol for
multiple purposes is sometimes referred to as "operator overloading" and frequently occurs in C#.
In this case, the C# compiler understands what you're trying to do. The compiler parses your code and
sees that the + symbol (the operator) is surrounded by two numeric values (the operands). Based on the
data types of the variables (ints), it understands that you intend to add these two values.
int secondNumber = 7;
Console.WriteLine(firstNumber + secondNumber);
2. Run the code, and you'll see the following output in the output console:
19
int widgetsSold = 7;
2. Run the code, and you'll see the following output in the output console:
Here, the C# compiler understands that you want to use the + symbol to concatenate the two operands.
He comes to this conclusion because the + symbol is surrounded by operands of string and int data types.
Therefore, it attempts to implicitly convert the int, widgetsSold variable to a string temporarily so that
it can be concatenated with the rest of the string. The C# compiler tries to help you when it can, but
ideally, it's best to be explicit in your intentions.
II. Try a more advanced case of digit addition and string concatenation
1. Edit the code you wrote to match the following code:
int widgetsSold = 7;
2. Run the code, and you'll see the following output in the output console:
Instead of adding the int widgetsSold variable to the int7 literal, the compiler treats everything as a string
and concatenates them all together.
int widgetsSold = 7;
2. Run the code, and you'll see the following output in the output console:
The parentheses symbol () becomes another overloaded operator. In this case, the opening and closing
parentheses form the operator of the order of operations, just as you would use them in a mathematical
formula. You indicate that you want to resolve the innermost parentheses first, that is, the addition of
the intwidgetsSold values and the value 7. Once they are resolved, the result is implicitly converted to a
string so that it can be concatenated with the rest of the message.
Summary
2. String concatenation and additions use the + symbol. This is called an operator overhead, and
the compiler infers the appropriate usage based on the types of data it is operating on.
3. When it can, the C# compiler implicitly converts an int to a string if it is obvious that the
developer is trying to concatenate the string representation of a number for presentation
purposes.
4. Use parentheses to set an order of operations and explicitly tell the compiler that you want to
perform some operations before others.
1. Select all the code in the .NET editor, and then tap Delete or Backspace to delete it.
int sum = 7 + 5;
int difference = 7 - 5;
int product = 7 * 5;
int quotient = 7 / 5;
Sum: 12
Difference: 2
Product: 35
Quotient: 1
However, the quotient resulting from the split example may not be what you expected. Values after the
decimal place are truncated from the quotient because the latter is defined as int, and int cannot contain
values after the decimal place.
1. Remove the code from the previous steps and enter the following code in the .NET editor:
For this to work, the quotient (to the left of the assignment operator) must be of decimal type and at least
one of the divided numbers must also be of decimal type (both numbers can also be decimal type).
However, the following lines of code don't work (or give inaccurate results):
decimal decimalQuotient = 7 / 5;
VI. Add code to cast the results of the entire division
What if you don't use literal values? In other words, what if you need to split two variables of type int,
but you don't want a truncated result? In this case, you must perform a decimal int data type cast. Casting
is a type of data conversion that tells the compiler to temporarily treat a value as if it were another data
type.
To cast int to decimal, add the cast operator before the value. You use the name of the data type in
parentheses in front of the value to cast it. Here, you add (decimal) before the first and second variables.
1. Remove the code from the previous steps and enter the following code in the .NET editor:
int first = 7;
int second = 5;
Console.WriteLine(quotient);decimal decimalQuotient = 7 / 5;
2. Run the code. You should see the following output:
1.4
The modulo % operator gives you the remainder of an int division. What you really want to know here
is if one number is divisible by another. This can be useful for long operations when a loop is made on
hundreds or thousands of data records and you want to provide feedback to the end user for every 100
data records processed.
1. Remove the code from the previous steps and enter the following code in the .NET editor:
Console.WriteLine($"Modulus of 7 / 5 : {7 % 5}");
Console.WriteLine(quotient);
decimal decimalQuotient = 7 / 5;
Modulus of 200 / 5 : 0
Modulus of 7 / 5 : 2
When the modulo has a value of 0, it means that the dividend is divisible by the divisor.
In math, PEMDAS is an acronym that helps students memorize the order of operations. The order is as
follows:
2. Exhibitors
C# follows the same order as PEMDAS, except for the exhibitors. Although there is no exponent
operator in C#, you can use the System.Math.Pow method. The "Call .NET Class Library Methods with
C#" module introduces this and other methods.
1. Remove the code from the previous steps and enter the following code in the .NET editor:
int value1 = 3 + 4 * 5;
int value2 = (3 + 4) * 5;
Console.WriteLine(value1);
Console.WriteLine(value2);
Here, you see the difference when you do the same trades in a different order.
23
35
Summary
2. Dividing two int values causes the values to be truncated after the decimal point. To keep values
after the decimal point, you must first cast the divisor or dividend (or both) of int to a floating-
point number as a decimal, and then the quotient must be of the same floating-point type to
avoid truncation.
3. Perform a cast operation to temporarily treat a value as if it were of a different data type.
The last simple operations that you will discover here are the incrementing and decrement of values
using special operators which are combinations of symbols.
Often, you need to increment and/or decrement values, especially when you're writing loop logic or code
that interacts with a data structure.
The += operator adds and assigns the value to the right of the operator to the value to the left of the
operator. Thus, lines two and three in the following code snippet are the same:
The ++ operator increments the value of the variable by 1. Thus, lines two and three in the following
code snippet are the same:
These same techniques can be used for subtraction, multiplication, etc. The following steps of the
exercise highlight some of them.
int value = 1;
value = value + 1;
value += 1;
value++;
value = value - 1;
value -= 1;
value--;
First increment: 2
Second increment: 3
Third increment: 4
First decrement: 3
Second decrement: 2
Third decrement: 1
Increment and decrement operators have an interesting quality: depending on their position, they
perform their operation before or after retrieving their value. In other words, if you use the operator
before the value as in ++value, the increment occurs before the value is retrieved. Similarly, value++
increments the value after it has been retrieved.
int value = 1;
value++;
Console.WriteLine($"Second: {value++}");
First: 2
Second: 2
Third: 3
Fourth: 4
Console.WriteLine($"Second: {value++}");
1. Retrieve the current value of the value variable and use it in the string interpolation operation.
2. Increment value.
The following line of code confirms that the value was, in fact, incremented.
Here, the order of operations has changed because the ++ operator is placed before the value operand.
1. Increment value.
2. Retrieve the new incremented value of the value variable and use it in the string operation.
Although not strictly necessary, you have added parentheses around the expression (++value) to improve
readability. Seeing so many + operators one after the other could be misunderstood by other developers.
Stylistic decisions like these are subjective. However, since you'll be writing the code only once and
reading it very often, you should make readability a priority.
Summary
1. Use compound assignment operators such as +=, -=, *=, ++, and -- to perform a mathematical
operation such as an increment or decrement, and then assign the result to the original variable.
2. The increment and decrement operators work differently depending on whether they are before
or after the operand.
In this task, you'll write code that will use a formula to convert a temperature from Fahrenheit to degrees
Celsius. You'll display the result in a message formatted for the user.
3. To convert temperatures from Fahrenheit to degrees Celsius, you must first subtract 32 and then
multiply by five-ninths (5/9).
Combine the variables with literal strings passed in a series of Console.WriteLine() commands to form
the full message.
5. When you're done, the message should look like the following output:
The goal was to perform simple operations on chain and numeric data. For your programming challenge,
you converted a value from one unit of measurement (Fahrenheit) to another (Celsius) and displayed the
result in a formatted message.
You used different operators to perform simple chain and math operations. You've discovered how
certain symbols are reused (overloaded) as different operators, depending on the context. You've learned
how the data types of operands influence the meaning of operators. Finally, you learned how to change
the data type of a value using the cast operator.
À la fin de ce chapitre, vous serez en mesure d’écrire du code utilisant différents types de variables,
d’effectuer des calculs numériques et de présenter à l’utilisateur des données mises en forme.
Objectifs d’apprentissage
Prérequis
• Expérience de niveau débutant avec l’exécution d’opérations mathématiques sur des variables
Introduction
Les développeurs doivent répéter certaines tâches presque tous les jours. Par exemple, la déclaration de
variables de chaîne et numériques, l’affectation et l’extraction de valeurs, ou encore l’exécution de
calculs sont des tâches courantes, mais essentielles. La communication des résultats à l’utilisateur de
l’application est une tâche tout aussi importante. Ceci implique des compétences que chaque
développeur doit apprendre à maîtriser pour résoudre un problème donné.
Supposons que vous soyez l’assistant d’un enseignant dans une école. Vous êtes chargé de développer
une application qui automatise la notation des étudiants. L’application utilise tous les devoirs notés de
chaque étudiant afin de calculer leur note/score global actuel pour la classe. L’enseignant a également
fourni un format requis pour indiquer les notes des élèves.
Ce module vous guide tout au long des étapes requises pour développer votre application Student
Grading. Votre code déclare et affecte des valeurs à des variables en fonction des noms des étudiants,
effectue différents calculs numériques et affiche les résultats. Les calculs incluent la détermination de la
somme des scores de devoir et le calcul de la note actuelle pour chaque étudiant. Pour afficher les
résultats dans le format requis, vous allez utiliser Console.WriteLine(), ainsi que des séquences
d’échappement de caractères qui vous aideront à mettre en forme vos résultats.
A. Project overview
You develop a Student Grading app that automates the calculation of the current grades for each student
in a class. Your app settings include:
1. You have a short list of four students and their five assignment grades.
2. Each assignment grade is expressed as an integer value, ranging from 0 to 100, where 100 means
everything is correct.
3. The final scores are the average of the five assignment scores.
4. Your app must perform basic math operations to calculate each student's final grades.
5. Your app must generate/display each student's name and final score.
The Teacher Gradebook displays graded assignments for each student as follows:
The instructor requires that the calculated grades for each student be displayed as follows:
Student Grade
Sophia 94.6 A
Nicolas 83.6 B
Jeong 95.4 A
2. Copy the following code and paste it into the editor. These values represent each student's
graded assignments.
int currentAssignments = 5;
You are now ready to begin the guided project exercises. Good luck!
In this exercise, you'll use each student's assignment scores to calculate their current grade in the class.
To do this, you'll first add up their assignment score values, and then calculate their average score
(current grade). Start.
1. Make sure that the .NET editor is open and that variables are instantiated with each student's
assignment scores.
In the preparation unit for this guided project, the setup instructions prompt you to copy students'
assignment scores to the editor. If necessary, go back to the setup instructions and follow them.
3. To declare an integer variable for each student so that you can add up their scores, enter the
following code:
int sophiaSum = 0;
int nicolasSum = 0;
int zahirahSum = 0;
int jeongSum = 0;
4. Notice that variables are assigned 0 as part of the declaration statement. In other words, variables
are initialized to 0. Even though assigning value isn't necessary when declaring variables, it can
make your code more efficient. The next step is to display the output, and since this output
includes a reference to these variables, they must be initialized.
5. To create Console.WriteLine() statements that display the student's name and the value of their
summed assignment scores, enter the following code:
The goal is to display the student's current overall grade, but for now, let's use these Console.WriteLine()
statements to display the value of your sum calculations. This way, you can check if your code is
working properly at each stage of the development process.
1. In the .NET editor, to run your code, select the green Run button.
Note that you have no problem displaying your integer values, which are all 0 for now, using the
WriteLine() method that displays string literals (student names).
The current numeric value is retrieved automatically by referencing the variable name.
With the Console.WriteLine() statements needed to display your results ready, let's start adding the code
that performs your calculations.
You'll write the code that calculates the sum value for each student. First, you'll add the students'
assignment scores, and then assign the value to the "Sum" variables. Let's start with Sophia. Remember
that Sophia's scores are stored in the following code:
Your output should now show that Sophia's sum is equal to 473. The others remain equal to 0. You'll
add similar sum calculations for the rest of the students.
1. From the blank line of code you just created, enter the following code:
int currentAssignments = 5;
3. Review your output and verify that the sums of the assignment scores are correct:
Sophia: 473
Nicolas: 418
Zahirah: 417
Jeong: 477
If your code shows different results, you should review it to find your error and make updates. Run the
code again to see if you have fixed the problem. Keep updating and running your code until it produces
the expected results.
1. In the .NET editor, find the Console.WriteLine() statements used to display each student's
summed scores.
3. In the blank code line you created, to declare the decimal variables that will be used for students'
current scores, enter the following code:
decimal sophiaScore;
decimal nicolasScore;
decimal zahirahScore;
decimal jeongScore;
Note that you only declare the decimal variables; You don't initialize them. You chose the decimal type
because you represented an average grade and you wanted to include a decimal place that wouldn't be
available if you were using an integer. This way, if you see that a student scored 89.9, you can give them
an A instead of a B.
In the previous exercise, you initialized the integer variables so that you can use them immediately in
your console output. In this case, these decimal variables will be initialized in the next step by means of
calculations with your existing data, starting with the Sophia score.
4. To assign the current Sophia score in the class to the sophiaScore decimal variable, update the
variable with the following code:
To calculate a student's current score for the class, you divide the sum of the assignment scores by the
total number of assignments. Each student in the class has five assignments, represented by
currentAssignments, that you initialized during setup.
5. To affect the rest of the student scores, enter the following code:
Ultimately, you want to view each student's grades in this app. In the next step, you'll change the code
to show each student's score rather than the sum of their assignments.
1. To view each student's current score, replace the sum variables in the display instructions with
the score variables:
Breaking down a problem into small chunks is an important skill for developers. Incrementally
generating your code and frequently reviewing your work allows you to quickly develop reliable
applications. In this case, you can reassign Console.WriteLine() to verify that your calculations are
correct at the end of each step in the process.
3. To view the values for each student's current grade, select Run.
Sophia: 94
Nicolas: 83
Zahirah: 83
When you want the result of a split to be a decimal value, the dividend, divisor, or both must be of
decimal type. When using integer variables in the calculation, you must apply a cast technique to
"convert" an integer to a decimal.
For the calculation of the score, you can get a decimal result by casting the sum variable or
currentAssignments as a decimal type. In this case, you'll cast the sum as a decimal place.
5. In your split operations, to cast an integer variable as a decimal, update your code as follows:
6. It is sufficient for the dividend or divisor to be of a decimal type for the division to result in a
decimal value. Here, you cast only the variable of the sum used as a dividend.
7. Review the following grading scale that the teacher uses to assign grades in a letter format:
97 - 100 A+
93 - 96 A
90 - 92 A-
87 - 89 B+
The next step is to include a letter grade for each student based on their total score. Adding the note as
83 - 86 Bdecimal jeongScore = (decimal) jeongSum / currentAssignments;Jeong:
a letter to the output displayed is a manual process.
95Console.WriteLine("Jeong: " + jeongScore);
8. To determine the value of each student's current grade, select Run.
Use each student's current grade to determine the grade in the appropriate letter format, rounding up or
down as necessary.
9. To add a letter grade after each student's numeric score, update your code as follows:
The goal was to create an app that, based on the assignment scores of students in a class, calculates their
grade and displays the results.
To do this, you declared and assigned values to variables of different data types, performed numeric
operations, and used casting to get accurate results. You also used Console.WriteLine() and character
escape sequences and to format the output.
By subdividing the problem, you were able to create a solution using the skills you learned in the
previous modules. Congratulations on the development of a structured app!
By the end of this chapter, you'll be able to write code using different types of variables, perform
numerical calculations, and present the user with formatted data.
Learning Objectives
Prerequisite
4. Beginner-level experience with creating literal values and declaring variables of basic data types
such as string, int, and decimal
Introduction
Developers have to repeat certain tasks almost every day. For example, declaring string and numeric
variables, assigning and extracting values, or performing calculations are not only common, but
essential. Communicating the results to the app user is an equally important task. These tasks are all
skills that every developer must master and be able to apply to solve a given problem.
Suppose you are a teacher's assistant at a university. You are responsible for developing an application
to calculate the cumulative grade point average of students. The app uses students' grades and credit
hours to calculate their CGPA (grade point average). In addition, you must present the CGPA of students
following a specific formatting.
This module walks you through the steps required to develop your MPC calculator application. Your
code declares variables and assigns values to them based on course information, performs various
numerical calculations, and then formats and displays the results. Calculations include the sum of points
earned and total credit hours. In order to display the results with the necessary formatting, you must
manipulate a decimal value to display a total of three digits. You'll also use Console.WriteLine()
methods and escape character sequences to format your results.
A. Project overview
You develop a student GPA calculator to calculate their grade point average. Your app settings include:
2. Each class is assigned a name, the student's grade, and the corresponding number of credit hours.
3. Your app must perform basic math operations to calculate the student's CGPA.
4. Your app must generate/display the student's name, class information, and GPA.
You are provided with the following sample (course information and a student's CGPA):
English 101 4 3
Algebra 101 3 3
Biology 101 3 4
Computer Science I 3 4
Psychology 101 4 3
C. Programme d’installation
Use the following steps to prepare the guided project exercises:
2. Copy the following code and paste it into the .NET editor. These values represent the student's
name and course information.
int course1Credit = 3;
int course2Credit = 3;
int course3Credit = 4;
int course4Credit = 4;
int course5Credit = 3;
In this exercise, you'll begin to set up the variables needed to calculate a student's GPA. Start.
In this task, you'll identify the numerical equivalents of the grade (in the form of a letter) that the student
earned. You'll then declare variables to store the numeric grade value for each class. Because numeric
equivalents are represented as integers, you'll use the Integer data type to store the values.
1. Verify that the .NET editor is open and that variables are prepared with the student's name,
course names, and credit hours.
In the preparation unit for this guided project, the setup instructions prompt you to copy the student's
course information into the editor. If necessary, go back to the setup instructions and follow them.
1. Review the numerical values for the letter notes: A = 4 points B = 3 points
3. To declare an Integer variable for each numeric grade value, enter the following code:
int gradeA = 4;
int gradeB = 3;
Note that fixed values are used to represent numeric notes. This technique makes it easier to understand
your code and helps avoid typos if you need to enter different notes in succession. The values for grades
C, D and F are omitted at this time as they are not used.
Course Grade
English 101 A
Algebra 101 B
Biology 101 B
Computer Science I B
Psychology 101 A
You'll use this information to create variables that store the numeric grade values for each course.
5. To create variables that store grades for each course, enter the following code:
6. To view course names with the numeric grade, enter the following code:
Console.WriteLine($"{course1Name} {course1Grade}");
Console.WriteLine($"{course2Name} {course2Grade}");
Console.WriteLine($"{course3Name} {course3Grade}");
Console.WriteLine($"{course4Name} {course4Grade}");
Console.WriteLine($"{course5Name} {course5Grade}");
7. In the .NET editor, to run your code, select the green Run button.
English 101 4
Algebra 101 3
Biology 101 3
Computer Science I 3
Psychology 101 4
8. Take a moment to think about the current and final output of your app.
You want the final output of your app to feature the class name, grade, and credit hours. This is the time
to add credit hours to the exit instructions.
9. To add the credit hours for each class to the exit instructions, update your code as follows:
Remember that to calculate a student's CGPA, you need the total number of credit hours and the total
number of points earned. Points earned for a course are the product of the number of credit hours for
that course and the numerical grade value obtained. Like what:
Course Credit Credit Hours Grade Points
English 101 4 3 12
In this task, you'll create the variables that store the values needed to calculate the GPA. You'll create
one variable to store the total amount of credit hours for each course, and another variable to store the
sum of the points the student earned for each course.
1. In the .NET editor, find the Console.WriteLine() statements used to display course information.
3. In the blank code line that you created, to create a variable that stores the total number of credit
hours, enter the following code:
int totalCreditHours = 0;
Note that the total is initialized to 0. This initialization allows you to increment the sum while keeping
your code organized.
4. To increment the sum to represent the total number of credit hours, enter the following code:
totalCreditHours += course1Credit;
totalCreditHours += course2Credit;
totalCreditHours += course3Credit;
totalCreditHours += course4Credit;
totalCreditHours += course5Credit;
Remember that the += operator is a shorthand notation for adding value to a variable. Using these lines
of code is like adding each courseCredit variable to a single line, for example:
5. To create a variable that stores the total number of points earned for each course, enter the
following code:
int totalGradePoints = 0;
6. To increment the sum of the number of points earned for the first class, enter the following code:
Remember that the points earned for a course are the product of the number of credit hours for that
course and the grade obtained. In this line of code, you use the compound assignment operator to add
the product of course1Credit * course1Grade to totalGradePoints.
7. To increment the sum of the number of points earned for the rest of the courses, enter the
following code:
Note that the code you wrote breaks down the problem into manageable pieces: it's not trying to calculate
the MPC with a single large operation. First, you initialized and calculated the value of totalCreditHours.
Next, you initialized and calculated the value of totalGradePoints. You will then use these values in your
final calculation.
Your code now calculates a value for totalGradePoints and we'll verify that your calculations are correct
before proceeding. It is important to stop and check your work regularly. Checking your work early in
the development process makes it easier to identify and fix errors in your code.
9. To view the values for totalGradePoints and totalCreditHours, enter the following code:
Console.WriteLine($"{totalGradePoints} {totalCreditHours}");
You will delete this WriteLine() statement later, as it is not needed for the final output.
1. In the .NET editor, find the Console.WriteLine() statements used to display course information.
Console.WriteLine($"{totalGradePoints} {totalCreditHours}");
You've verified that your values are correct, so this line is no longer needed.
4. On the blank line of code you created, to initialize a variable that stores the final MPC, enter the
following code:
When you want the result of a split to be a decimal value, the dividend, divisor, or both must be of
decimal type. When using integer variables in the calculation, you must use the cast operator to
temporarily convert an integer to a decimal value.
6. To get a decimal value from the division, update your code as follows:
7. Go to the last Console.WriteLine() statement and create a blank line of code below it.
English 101 4 3
Algebra 101 3 3
Biology 101 3 4
Computer Science I 3 4
Psychology 101 4 3
In the end, you want to display the first digit of the GPA, a decimal point, and the first two digits after
the decimal place. You can achieve this formatting by using variables to store the start and end digits
respectively, and then displaying them together with the Console.WriteLine() command. You can use
learned math operations to extract the beginning and ending digits.
3. On the blank code line you created, to initialize a variable that stores the starting digit of the
MPC, enter the following code:
Note that to extract the beginning digit from the decimal place, you cast it as an integer value. This is a
simple and reliable method, as casting a fractional value never rounds the result. This means that if the
GPA is 2.99, the cast of the decimal value into an integer value generates the value 2.
4. To initialize a variable that stores the first two digits after the decimal place, enter the following
code:
In the first half of this operation, you move the decimal place to the right and cast it to an integer. In the
second half, you use the remainder operator, or modulo, to get the remainder of a division by 10 that
isolates the last digit from the integer. Here's an example:
For example, for gradePointAverage = 2.994573, performing the operation on these values results in the
following steps:
int firstDigit = 9;
Then you apply the same operation to retrieve the second digit.
In this line, you move the comma two positions and use the modulo operator to retrieve the last digit.
2. To correct the final MPC output, update the latest Console.WriteLine() statement as follows:
The goal was to create an app that takes a student's course information, calculates the general GPA, and
displays the results.
To do this, you declared variables of different data types and assigned values to them, performed
numeric operations, and used casting to get accurate results. You also used the WriteLine() method and
escape character sequences to format the output.