0% found this document useful (0 votes)
4 views51 pages

GIFT PROGRAMMING

Uploaded by

joelnjidjou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views51 pages

GIFT PROGRAMMING

Uploaded by

joelnjidjou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

L’INSTITUT SUPERIEUR DADA

24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

Introduction

The C# programming language allows you to develop different types of applications, such as:

1. Business applications to capture, analyze, and process data

2. Dynamic web applications accessible from a web browser

3. 2D and 3D Games

4. Financial and scientific applications

5. Cloud-based applications

6. Applications mobiles

But how do you start writing an app?

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.

In this module, you will:

1. Write your first few lines of C# code.

2. Use two different techniques to display a message as output

3. Diagnose errors when code is incorrect

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.

Exercise - Writing Your First Lines of Code

In this first hands-on exercise, you'll use C# to display any programmer's consecrated phrase in the
standard output of a console.

Write your first line of code

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.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

Enter code in the .NET editor

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.

Run your first few lines of code

1. Press the green Run button

The green Run button performs two tasks:

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.

Review your results

1. In the output console, observe the result of your code. You should get the following output:
Hello World!

What to do if you see an error message

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!");

The following error message is displayed:

(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:

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

Console.WriteLine('Hello World!');

The following error message is displayed:

(1,19): error CS1012: Too many characters in character literal

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.

Common mistakes beginner programmers make:

1. Enter lowercase letters instead of uppercase C in Console, or the letters W or L in WriteLine.

2. Enter a comma instead of a period between Console and WriteLine.

3. Forget double quotes or use single quotes to surround the phrase Hello World!

4. Forget a semicolon at the end of the command.

Each of these errors prevents your code from compiling successfully.

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.

View a new message

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.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

1. Add new lines of code to get the following code snippet:


Console.Write("Congratulations!");

Console.Write(" ");

Console.Write("You wrote your first lines of code.");


1.

2. Press the green Run button again. This time, the following output should be displayed.

Congratulations! You wrote your first lines of code.

Difference Between Console.Write and Console.WriteLine

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

1. Update your code to match the following code snippet:

Console.WriteLine("Congratulations!");

Console.Write("You wrote your first lines of code.");

2. Press the green Run button again. This time, the following output should be displayed.

Congratulations!

You wrote your first lines of code.

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.

Understand how code works

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.

What is a programming language?

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

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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.

Qu’est-ce que la compilation ?

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.

Qu’est-ce que la syntaxe ?

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#.

Comment votre code a fonctionné ?

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

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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:

1. Utilisez Console.WriteLine("Your message here");.

2. Capitalize Console, Write, and Line

3. Use proper punctuation, as it has a special role in C#

4. If you make a mistake, simply identify it, fix it, and then rerun your code

5. Understanding the Execution Flow

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:

1. What is the difference between Console.Write and Console.WriteLine?

Console.Write displays the output on a new line.

Console.WriteLine displays the output on a new line.

Console.WriteLine adds a new line after output.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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

Upon completion of this module, you will be able to:

1. Create literal values for five basic data types

2. Declaring and initializing variables

3. Retrieve and set values in variables

4. Allow the compiler to determine the data type of your variable during initialization

Prerequisite

1. Must understand basic C# syntax rules

2. Must understand how to use Console.WriteLine().

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.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

Learning Objectives

In this module, you will:

1. Create literal values for five basic data types

2. Declaring and initializing variables

3. Retrieve and set values in variables

4. Allow the compiler to determine the data type of your variable during initialization

Prerequisite

1. Must understand basic C# syntax rules

2. How to use Console.WriteLine()

3. Have beginner-level experience with a .NET editor

Exercise: Display Literal Values

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#.

What is a literal value?

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?

Exercise: Displaying different types of literal data

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.

Use character literals

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".

1. Add the following line of code in the code editor:


Console.WriteLine('b');

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

1. Look at the code you entered.

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

If you enter the following code:

Console.WriteLine('Hello World!');

You get the following error:

(1,19): error CS1012: Too many characters in character literal

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).

Use integer type literals

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.

1. Add the following line of code in the code editor:

Console.WriteLine(123);

2. Press the green "Run" button to run your code. You normally see the following output in the
output console:
123

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

Use floating-point literals

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

----------------------------

float ~6-9 digits

double ~15-17 digits

decimal 28-29 digits

Here, precision reflects the number of digits after the decimal separator that are exact.

1. Add the following line of code in the code editor:

To create a float literal, add the letter FConsole.WriteLine(0.25F);


after the number. In this context, F is called a literal suffix. The
literal suffix tells the compiler that you want to use a float value. You can use a lowercase (f) or
uppercase (F) for the literal suffix of a float value.

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.

3. Add the following line of code in the code editor:

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

5. Add the following line of code in the code editor:

Console.WriteLine(12.39816m);

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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

Use Boolean literals

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".

1. Add the following lines of code to the code editor:

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.

Why focus on data types?

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#.

Data types define capabilities

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.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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

2. char for a single alphanumeric character

3. int for an integer

4. decimal for a number with a fractional component

5. bool for true/false

Chapter 2: Reporting Variables

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;

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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.

Rules and conventions 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!

Here are some important considerations for variable names:

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.

Here are some coding conventions that apply to variables:

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.

Exemples de noms de variables

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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

Here's what you've learned about variables at this point:

1. Variables are temporary values that you store in the computer's memory.

2. Before you can use a variable, you must declare it.

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.

Exercise: Defining and Obtaining Values from Variables

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.

Exercise - Using Variables

In this exercise, you'll declare a variable, assign it a value, retrieve its value, and more.

Create your first variable

1. Select all the code in the .NET editor, and then tap Delete or Backspace to delete it.

2. Enter the following code in the code editor:

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).

Incorrectly assign a value to a variable

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

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

the variable to the left of the assignment operator. If you reverse the order, you'll confuse the C#
compiler.

1. Edit the code you wrote to match the following code:


string firstName;

"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

Incorrectly assign a value of the wrong data type to the variable

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.

1. Edit the code you wrote to match the following code:


int firstName;

firstName = "Bob";

2. Now, run the code. The following error is displayed in the output console:

(2,9): error CS0029: Cannot implicitly convert type 'string' to 'int'

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.

Retrieve a value that you stored in the variable

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.

1. Edit the code you wrote to match the following code:

string firstName;

firstName = "Bob";

Console.WriteLine(firstName);

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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.

Reassign the value of a variable

You can reuse and reassign the variable as many times as you want. This example illustrates this idea.

1. Edit the code you wrote to match the following code:

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

Initialize the variable

You must set a variable to a value before you can retrieve the value of the variable. Otherwise, an error
is displayed.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

1. Edit the code you wrote to match the following code:

string firstName;

Console.WriteLine(firstName);

2. Now, run the code. The following error is displayed in the output console:

(2,19): error CS0165: Use of unassigned local variable 'firstName'

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.

1. Edit the code you wrote to match the following code:

string firstName = "Bob";

Console.WriteLine(firstName);

2. Now, run the code. The following error is displayed in the output console:

Bob

Summary

Here's what you've learned about working with variables so far:

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.

3. The assignment is from right to left.

4. You use a single equal character as the assignment operator.

5. To retrieve the value from the variable, you simply use the variable name.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

Chapter 3: Declaring implicitly typed local variables

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.

What are implicitly typed local variables?

An implicitly typed local variable is created with the var keyword followed by an initialization of the
variable. Like what:

var message = "Hello world!";

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:

var message = "Hello world!";

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:

var message = "Hello World!";

message = 10.703m;

If you run this code, you receive the following error message.

(2,11): error CS0029: Cannot implicitly convert type 'decimal' to 'string'

Variables using the var keyword must be initialized

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;

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

If you attempt to run this code, when it is compiled, the following output is displayed:

(1,5): error CS0818: Implicitly-typed variables must be initialized

Why use the var keyword?

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

Here's what you've learned about the var keyword so far:

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.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

Chapter 4: Performing Simple Operations on Numbers in C#

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

In this module, you will:

1. Perform mathematical operations on numeric values

2. Observe implicit type conversion between strings and numeric values

3. Temporarily convert one data type to another

Prerequisite

1. Beginner-level experience with a .NET editor

2. Beginner-level experience with basic C# syntax rules

3. Beginner-level experience with displaying a message in a console using the Console.WriteLine


and Console.Write methods

4. Beginner-level experience with creating literal values and declaring variables of basic data types
such as string, int, and decimal

5. Beginner-level experience with string concatenation and string interpolation

Introduction
The applications that you will build in C# require you to use both literal and variable numeric data.
Examples should include:

1. Perform simple mathematical operations, including addition, subtraction, multiplication, and


division

2. Performing multi-step operations that must be performed in a certain order

3. Determination of the remainder after division

4. Incrementing or decrementing a value, and so on

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.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

Learning how to use operators and operands properly will make it easier for you to formulate explicit
instructions in your code.

1. Perform Addition with Implicit Data Conversion

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.

Add two numerical values

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.

1. Enter the following code in the .NET editor:

int firstNumber = 12;

int secondNumber = 7;

Console.WriteLine(firstNumber + secondNumber);

2. Run the code, and you'll see the following output in the output console:

19

I. Combine data types to force implicit conversions


What happens if you try to use the + symbol with both string and int values?

1. Edit the code you wrote to match the following code:

string firstName = "Bob";

int widgetsSold = 7;

Console.WriteLine(firstName + " sold " + widgetsSold + " widgets.");

2. Run the code, and you'll see the following output in the output console:

Bob sold 7 widgets.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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:

string firstName = "Bob";

int widgetsSold = 7;

Console.WriteLine(firstName + " sold " + widgetsSold + 7 + " widgets.");

2. Run the code, and you'll see the following output in the output console:

Bob sold 77 widgets.

Instead of adding the int widgetsSold variable to the int7 literal, the compiler treats everything as a string
and concatenates them all together.

III. Add parentheses to clarify your intent for the compiler


1. Edit the code you wrote to match the following code:

string firstName = "Bob";

int widgetsSold = 7;

Console.WriteLine(firstName + " sold " + (widgetsSold + 7) + " widgets.");

2. Run the code, and you'll see the following output in the output console:

Bob sold 14 widgets.

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.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

Summary

Here's what you've learned so far about math operations in C#:

1. You can perform mathematical operations such as adding to numbers.

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.

IV. Perform mathematical operations


Now that you've understood the basics of addition and, more importantly, implicit type conversion
between numeric and string data types, let's take a look at several other common math operations on
numeric data.

1. Perform simple mathematical operations

Write code to do addition, subtraction, multiplication, and division with integers

1. Select all the code in the .NET editor, and then tap Delete or Backspace to delete it.

2. Enter the following code in the .NET Editor:

int sum = 7 + 5;

int difference = 7 - 5;

int product = 7 * 5;

int quotient = 7 / 5;

Console.WriteLine("Sum: " + sum);

Console.WriteLine("Difference: " + difference);

Console.WriteLine("Product: " + product);

Console.WriteLine("Quotient: " + quotient);

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

3. Run the code. You should see the following output:

Sum: 12

Difference: 2

Product: 35

Quotient: 1

As you can see:

1. + is the addition operator

2. - is the subtraction operator

3. * is the multiplication operator

4. / is the division operator

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.

V. Add code to make a division using literal decimal data


For splitting to work, you must use a data type that supports decimal digits after the decimal point as
decimal.

1. Remove the code from the previous steps and enter the following code in the .NET editor:

decimal decimalQuotient = 7.0m / 5;

Console.WriteLine($"Decimal quotient: {decimalQuotient}");

2. Run the code. You should see the following output:

Decimal quotient : 1.4

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).

Here are two more examples that work just as well:

decimal decimalQuotient = 7 / 5.0m;

decimal decimalQuotient = 7.0m / 5.0m;

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

However, the following lines of code don't work (or give inaccurate results):

int decimalQuotient = 7 / 5.0m;

int decimalQuotient = 7.0m / 5;

int decimalQuotient = 7.0m / 5.0m;

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;

decimal quotient = (decimal)first / (decimal)second;

Console.WriteLine(quotient);decimal decimalQuotient = 7 / 5;
2. Run the code. You should see the following output:

1.4

VII. Write code to determine the remainder after an integer division

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 200 / 5 : {200 % 5}");

Console.WriteLine($"Modulus of 7 / 5 : {7 % 5}");

Console.WriteLine(quotient);

decimal decimalQuotient = 7 / 5;

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

2. Run the code. You should see the following output:

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.

VIII. Order of operations


As you learned in the previous exercise, you can use the symbols () as operators for the order of
operations. However, this is not the only way to determine the order of operations.

In math, PEMDAS is an acronym that helps students memorize the order of operations. The order is as
follows:

1. Parentheses (anything in parentheses is executed first)

2. Exhibitors

3. Multiplication and Division (from left to right)

4. Addition and Subtraction (Left to Right)

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.

Write code to enforce the order of operations of C#

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.

1. Run the code. You should see the following output:

23

35

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

Summary

Here's what you've learned so far about math operations in C#:

1. Use operators like +, -, *, and / to perform simple mathematical operations.

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.

4. Use the % operator to capture the rest after splitting.

5. The order of operations follows the rules of the acronym PEMDAS.

1. Increment and Decrement Values

The last simple operations that you will discover here are the incrementing and decrement of values
using special operators which are combinations of symbols.

1. Increment and Decrement

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:

int value = 0; // value is now 0.

value = value + 5; // value is now 5.

value += 5; // value is now 10.

The ++ operator increments the value of the variable by 1. Thus, lines two and three in the following
code snippet are the same:

int value = 0; // value is now 0.

value = value + 1; // value is now 1.

value++; // value is now 2.

These same techniques can be used for subtraction, multiplication, etc. The following steps of the
exercise highlight some of them.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

➢ Write code to increment and decrement a value


1. Select all the code in the .NET editor, and then tap Delete or Backspace to delete it.

2. Enter the following code in the .NET Editor:

int value = 1;

value = value + 1;

Console.WriteLine("First increment: " + value);

value += 1;

Console.WriteLine("Second increment: " + value);

value++;

Console.WriteLine("Third increment: " + value);

value = value - 1;

Console.WriteLine("First decrement: " + value);

value -= 1;

Console.WriteLine("Second decrement: " + value);

value--;

Console.WriteLine("Third decrement: " + value);

3. Run the code. You should see the following output:

First increment: 2

Second increment: 3

Third increment: 4

First decrement: 3

Second decrement: 2

Third decrement: 1

4. Position increment and decrement operators

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

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

before the value as in ++value, the increment occurs before the value is retrieved. Similarly, value++
increments the value after it has been retrieved.

➢ Use the increment operator before and after the value


1. Remove the code from the previous steps and enter the following code in the .NET editor:

int value = 1;

value++;

Console.WriteLine("First: " + value);

Console.WriteLine($"Second: {value++}");

Console.WriteLine("Third: " + value);

Console.WriteLine("Fourth: " + (++value));

2. Run the code. You should see the following output:

First: 2

Second: 2

Third: 3

Fourth: 4

Notice this line of code:

Console.WriteLine($"Second: {value++}");

There are two steps in this line:

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.

Console.WriteLine("Third: " + value);

In contrast, look at the last line of code:

Console.WriteLine("Fourth: " + (++value));

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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

Here's what you've learned so far about math operations in C#:

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.

➢ Converting Fahrenheit to Celsius

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.

✓ Calculate Temperature in Degrees Celsius Based on Current Temperature in


Fahrenheit
1. Select all the code in the .NET editor, and then tap Delete or Backspace to delete it.

2. Enter the following code in the .NET Editor:

int fahrenheit = 94;

3. To convert temperatures from Fahrenheit to degrees Celsius, you must first subtract 32 and then
multiply by five-ninths (5/9).

4. Display the result of the temperature conversion in a formatted message

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 temperature is 34.444444444444444444444444447 Celsius.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

✓ Solution to convert Fahrenheit to Celsius

int fahrenheit = 94;

decimal celsius = (fahrenheit - 32m) * (5m / 9m);

Console.WriteLine("The temperature is " + celsius + " Celsius.");

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.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

Chapitre 5 : Projet guidé - Calculer et imprimer les notes des étudiants

À 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

Dans ce chapitre, vous allez vous entraîner aux tâches suivantes :

• Utiliser des variables pour stocker et récupérer des données

• Effectuer des opérations mathématiques simples

• Mettre en forme des chaînes pour présenter les résultats

Prérequis

• Expérience de niveau débutant avec un éditeur .NET

• Expérience niveau débutant avec les règles de syntaxe C# de base

• Expérience de niveau débutant avec l’exécution d’opérations mathématiques sur des variables

• Expérience niveau débutant avec la création de valeurs littérales et la déclaration de variables


des types de données de base comme string, int et decimal

• Expérience niveau débutant avec la concaténation de chaînes et l’interpolation de chaînes

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.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

I. Prepare the guided project


You'll use the .NET editor as your code development environment. You'll write code that uses string
and numeric variables, performs calculations, and displays the results in a console.

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:

Sophia: 93, 87, 98, 95, 100

Nicolas: 80, 83, 82, 88, 85

Zahirah: 84, 96, 73, 85, 79

Jeong: 90, 92, 98, 100, 97

The instructor requires that the calculated grades for each student be displayed as follows:

Student Grade

Sophia 94.6 A

Nicolas 83.6 B

➢ Programme d’installation Zahirah 83.4 B

Jeong 95.4 A

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

Use the following steps to prepare the guided project exercises:

1. Open the programming environment, in this case, the .NET editor.

2. Copy the following code and paste it into the editor. These values represent each student's
graded assignments.

// initialize variables - graded assignments

int currentAssignments = 5;

int sophia1 = 93;

int sophia2 = 87;

int sophia3 = 98;

int sophia4 = 95;

int sophia5 = 100;

int nicolas1 = 80;

int nicolas2 = 83;

int nicolas3 = 82;

int nicolas4 = 88;

int nicolas5 = 85;

int zahirah1 = 84;

int zahirah2 = 96;

int zahirah3 = 73;

int zahirah4 = 85;

int zahirah5 = 79;

int jeong1 = 90;

int jeong2 = 92;

int jeong3 = 98;

int jeong4 = 100;

int jeong5 = 97;

You are now ready to begin the guided project exercises. Good luck!

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

1. Calculate the sum of each student's assignment scores

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.

➢ Creates variables to store the sum


In this task, you'll create a variable for each student that will represent the sum of their assignment
scores. You'll also display the student's sum and name in the console output. Because assignment scores
are represented as integers, you'll create integer variables to store the sums.

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.

2. At the bottom of your code, create a blank line of code.

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:

Console.WriteLine("Sophia: " + sophiaSum);

Console.WriteLine("Nicolas: " + nicolasSum);

Console.WriteLine("Zahirah: " + zahirahSum);

Console.WriteLine("Jeong: " + jeongSum);

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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.

2. Look for the following line of code: int sophiaSum = 0;

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:

int sophia1 = 93;

int sophia2 = 87;

int sophia3 = 98;

int sophia4 = 95;

int sophia5 = 100;


1. Update the line of code as follows:

int sophiaSum = sophia1 + sophia2 + sophia3 + sophia4 + sophia5;int sophia5 = 100;

2. In the .NET editor, select Run.

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 nicolasSum = nicolas1 + nicolas2 + nicolas3 + nicolas4 + nicolas5;

int zahirahSum = zahirah1 + zahirah2 + zahirah3 + zahirah4 + zahirah5;

int jeongSum = jeong1 + jeong2 + jeong3 + jeong4 + jeong5;int sophia5 = 100;

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

➢ Verify your work


In this task, you'll run the code and verify that the output is correct.

1. Compare your code to the following:

int currentAssignments = 5;

int sophia1 = 93;

int sophia2 = 87;

int sophia3 = 98;

int sophia4 = 95;

int sophia5 = 100;

int nicolas1 = 80;

int nicolas2 = 83;

int nicolas3 = 82;

int nicolas4 = 88;

int nicolas5 = 85;

int zahirah1 = 84;

int zahirah2 = 96;

int zahirah3 = 73;

int zahirah4 = 85;

int zahirah5 = 79;

int jeong1 = 90;

int jeong2 = 92;

int jeong3 = 98;

int jeong4 = 100;

int jeong5 = 97;

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

int sophiaSum = sophia1 + sophia2 + sophia3 + sophia4 + sophia5;

int nicolasSum = nicolas1 + nicolas2 + nicolas3 + nicolas4 + nicolas5;

int zahirahSum = zahirah1 + zahirah2 + zahirah3 + zahirah4 + zahirah5;

int jeongSum = jeong1 + jeong2 + jeong3 + jeong4 + jeong5;

Console.WriteLine("Sophia: " + sophiaSum);

Console.WriteLine("Nicolas: " + nicolasSum);

Console.WriteLine("Zahirah: " + zahirahSum);

Console.WriteLine("Jeong: " + jeongSum);

2. In the .NET editor, select Run.

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.

➢ Calculate the average of the student's assignment scores


In this exercise, you'll calculate and store the average of each student's assignment scores. Because you
know the number of graded assignments for each student, the average is calculated by dividing the sum
of the assignment scores by the number of assignments. To store the averages, you'll use the Decimal
data type.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

✓ Creates variables to store the average


In this task, you'll create a variable for each student that can be used to store the average score of their
graded assignments.

1. In the .NET editor, find the Console.WriteLine() statements used to display each student's
summed scores.

2. Create a blank line of code above the Console.WriteLine() statements.

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:

decimal sophiaScore = sophiaSum / currentAssignments;

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:

decimal nicolasScore = nicolasSum / currentAssignments;

decimal zahirahScore = zahirahSum / currentAssignments;

decimal jeongScore = jeongSum / currentAssignments;

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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:

Console.WriteLine("Sophia: " + sophiaScore);

Console.WriteLine("Nicolas: " + nicolasScore);

Console.WriteLine("Zahirah: " + zahirahScore);

Console.WriteLine("Jeong: " + jeongScore);


2. Take a few minutes to think about the incremental approach you're using to develop this app.

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.

You should normally see the next output.

Sophia: 94

Nicolas: 83

Zahirah: 83

Jeong: 95Console.WriteLine("Jeong: " + jeongScore);


4. Note that scores are displayed as integers rather than decimals.

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:

decimal sophiaScore = (decimal) sophiaSum / currentAssignments;

decimal nicolasScore = (decimal) nicolasSum / currentAssignments;

decimal zahirahScore = (decimal) zahirahSum / currentAssignments;

decimal jeongScore = (decimal) jeongSum / currentAssignments;Jeong:


95Console.WriteLine("Jeong: " + jeongScore);

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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:

Console.WriteLine("Sophia: " + sophiaScore + " A");

Console.WriteLine("Nicolas: " + nicolasScore + " B");

Console.WriteLine("Zahirah: " + zahirahScore + " B");

Console.WriteLine("Jeong: " + jeongScore + " A");

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!

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

Chapter 6: Calculating the final average grade

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

In this chapter, you'll practice the following tasks:

1. Use variables to store and retrieve data

2. Perform simple mathematical operations

3. Format strings to present results

Prerequisite

1. Beginner-level experience with a .NET editor

2. Beginner-level experience with basic C# syntax rules

3. Beginner-level experience with performing mathematical operations on variables

4. Beginner-level experience with creating literal values and declaring variables of basic data types
such as string, int, and decimal

5. Beginner-level experience with string concatenation and string interpolation

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.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

I. Prepare the guided project


You'll use the .NET editor as your code development environment. You'll write code that uses string
and numeric variables, perform calculations, and then format and display the results in a console.

A. Project overview
You develop a student GPA calculator to calculate their grade point average. Your app settings include:

1. The student's name and class information are provided to you.

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.

B. To calculate the GPA:


1. Multiply the grade value of a course by the number of credit hours for that course.

2. Do this for each course, and then add up those results.

3. Divide the resulting sum by the total number of credit hours.

You are provided with the following sample (course information and a student's CGPA):

Student: Sophia Johnson

Course Grade Credit Hours

English 101 4 3

Algebra 101 3 3

Biology 101 3 4

Computer Science I 3 4

Psychology 101 4 3

Final GPA: 3.35

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

C. Programme d’installation
Use the following steps to prepare the guided project exercises:

1. Open the programming environment, in this case, the .NET editor.

2. Copy the following code and paste it into the .NET editor. These values represent the student's
name and course information.

string studentName = "Sophia Johnson";

string course1Name = "English 101";

string course2Name = "Algebra 101";

string course3Name = "Biology 101";

string course4Name = "Computer Science I";

string course5Name = "Psychology 101";

int course1Credit = 3;

int course2Credit = 3;

int course3Credit = 4;

int course4Credit = 4;

int course5Credit = 3;

You are now ready to begin the guided project exercises.

1. Store numeric grade values for each course

In this exercise, you'll begin to set up the variables needed to calculate a student's GPA. Start.

2. Create variables to store grade values

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

2. Scroll to the bottom of your code and create a blank line.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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.

4. Review the student's grades for each course

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:

int course1Grade = gradeA;

int course2Grade = gradeB;

int course3Grade = gradeB;

int course4Grade = gradeB;

int course5Grade = gradeA;

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}");

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

7. In the .NET editor, to run your code, select the green Run button.

Your app's output should be as follows:

English 101 4

Algebra 101 3

Biology 101 3

Computer Science I 3

Psychology 101 4

If not, be sure to check your variable names.

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:

Console.WriteLine($"{course1Name} {course1Grade} {course1Credit}");

Console.WriteLine($"{course2Name} {course2Grade} {course2Credit}");

Console.WriteLine($"{course3Name} {course3Grade} {course3Credit}");

Console.WriteLine($"{course4Name} {course4Grade} {course4Credit}");

Console.WriteLine($"{course5Name} {course5Grade} {course5Credit}");

D. Calculate credit hours and points


In this exercise, you'll calculate and store the total number of credit hours and the total points earned for
each course. These values will be used later to calculate the MBM. Because credit hours and grade
values are represented as integers, you'll store sums with an Integer data type.

1. Create variables to store the average

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

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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.

2. Create a blank line of code above the Console.WriteLine() statements.

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;

totalCreditHours = course1Credit + course2Credit + course3Credit + course4Credit +


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:

totalGradePoints += course1Credit * course1Grade;

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.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

7. To increment the sum of the number of points earned for the rest of the courses, enter the
following code:

totalGradePoints += course2Credit * course2Grade;

totalGradePoints += course3Credit * course3Grade;

totalGradePoints += course4Credit * course4Grade;

totalGradePoints += course5Credit * course5Grade;

8. Take a few moments to review your 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.

E. Format decimal output


In this exercise, you'll calculate the final GPA and change the console output to get the formatting you
want. The CGPA is the total sum of points divided by the total sum of credit hours.

1. Calculate the final GPA

1. In the .NET editor, find the Console.WriteLine() statements used to display course information.

2. Delete the following code entered in the previous fiscal year:

Console.WriteLine($"{totalGradePoints} {totalCreditHours}");

You've verified that your values are correct, so this line is no longer needed.

3. Create a blank line of code above the Console.WriteLine() statements.

4. On the blank line of code you created, to initialize a variable that stores the final MPC, enter the
following code:

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

decimal gradePointAverage = totalGradePoints/totalCreditHours;

5. Take a moment to think about the types of data you're splitting.

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:

decimal gradePointAverage = (decimal) totalGradePoints/totalCreditHours;

7. Go to the last Console.WriteLine() statement and create a blank line of code below it.

8. To view the final GPA, enter the following code:

Console.WriteLine($"Final GPA: {gradePointAverage}");

9. To see the results, select Run.

Compare your app's output to the next output

English 101 4 3

Algebra 101 3 3

Biology 101 3 4

Computer Science I 3 4

Psychology 101 4 3

Final GPA: 3.3529411764705882352941176471

F. Format decimal output


You may have noticed that the decimal result contains many more digits than a standard MPC. For the
purposes of this task, you'll manipulate the decimal MPC value so that only three digits appear.

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.

1. Move over the Console.WriteLine() statements.

2. Create a blank line of code above the Console.WriteLine() statements.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

3. On the blank code line you created, to initialize a variable that stores the starting digit of the
MPC, enter the following code:

int leadingDigit = (int) gradePointAverage;

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:

int firstDigit = (int) (gradePointAverage * 10) % 10;

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 = (int) (2.994573 * 10) % 10;

int firstDigit = 29 % 10;

int firstDigit = 9;

The value of firstDigit obtained is 9.

Then you apply the same operation to retrieve the second digit.

1. Enter the following code on the new blank code line:

int secondDigit = (int) (gradePointAverage * 100) % 10;

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:

Console.WriteLine($"Final GPA: {leadingDigit}.{firstDigit}{secondDigit}");

The goal was to create an app that takes a student's course information, calculates the general GPA, and
displays the results.

Réaliser par : Mr NJIDJOU TADE Joel


L’INSTITUT SUPERIEUR DADA
24-03268/NHA/MINESUP/DDES/ESUP/SDA/MF

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.

Réaliser par : Mr NJIDJOU TADE Joel

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy