Introduction to the Values of a Program
Introduction to the Values of a Program
Fundamentals of Variables
Introduction to Values
A value is a piece of information (called data) you need to use in your program. One way to use a value is to display it to the user. To do this, you can include the value in the parentheses of Write(). Here are two examples:
using static System.Console;
Write(248);
Practical Learning: Introducing Variables
using static System.Console;
Introduction to Variables
A variable is a value that is stored in the computer memory (the random access memory, also called RAM). Such a value can be retrieved from the computer memory and displayed to the user.
Declaring a Variable
Before using a variable in your application, you must let the compiler know. Letting the compiler know is referred to as declaring a variable.
To declare a variable, you must provide at least two pieces of information. Actually, you have various options. We will start with one of them. One option to declare a variable is to provide the type of value, also called a data type, followed by a name for the variable. The formula to follow is:
data-type variable-name;
Initializing a Variable
When declaring a variable, you can give it a primary value. This is referred to as initializing the variable. You can use the following formula:
data-type variable-name = value;
This would be done as follows:
using static System.Console;
data-type variable-name = desired-value;
A variable must have a name. There are rules you must follow to specify the name of a variable. To start, you must avoid reserved words, also called keywords. These keywords are:
There are other names that are not considered C# keywords but should be avoided because they may cause a conflict in your code. They are referred to as contextual keywords. They are:
add | ascending | descending | ||
from | group | into | join | let |
orderby | partial (method) | partial (type) | remove | |
select | where (generic) | where (query) | ||
There are some rules we will follow to name variables:
Besides these rules, you can also create your own rules but that follow the above restrictions. For example:
C# is case-sensitive. This means that the names Case, case, and CASE are completely different.
Practical Learning: Introducing Variable Names
using static System.Console;
// data-type variable - name = value;
A Primary Introduction to Strings
Introduction
A string one or a group of symbols, readable or not. The symbols can be letters (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z), digits (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) are non-readable characters (` ~ ! @ # $ % ^ & * ( ) - _ = + [ { ] } \ | ; : ' < ? . / , > "). To create a string, include its symbol, symbols, or combination inside double-quotes.
One way to use a string in a program is to store that string in the computer memory. To do that, you can declare a variable that holds a string as value. To let you do this, the C# language provides a data type named string. Use it to declare a string-based variable. Here is an example:
using static System.Console;
string firstName;
To provide the value of the variable, specify its value in double-quotes and assign it to the variable. Here is an example:
using static System.Console;
string firstName = "James";
Displaying a String
Displaying a value consists of printing it to the computer screen. If you simply have a string to display, include that string in the parentheses of Write(). Here is an example:
using static System.Console;
Write("Welcome to the World of C# Programming!");
This would produce:
Welcome to the World of C# Programming!Press any key to close this window . . .
Primary Topics on Strings
If you use Write(), everything displays on the same line. This means that, after a string has displayed, the caret stays on the same line. As an alternative, you can display a string on one line and then move the caret on the next line. To do this, use WriteLine(). In this case, after the string is displayed, whatever item comes next would display in the next line. Just as you can include a value in the parentheses of Write(), you can put a value in the parentheses of WriteLine(). Consider the following example:
using static System.Console;
WriteLine("Welcome to the World of C# Programming!");
This would produce:
Welcome to the World of C# Programming! Press any key to close this window . . .
In the same way, you can use any combination of Write() or of WriteLine() in your code. Here are examples:
using static System.Console; Write("Country Name:"); Write(" "); WriteLine("Australia");
This would produce:
Country Name: Australia Press any key to close this window . . .
You can leave the parentheses of WriteLine() empty or include something in it but you can never leave the parentheses of Write() empty.
Practical Learning: Creating a New Line
using static System.Console;
// data-type variable - name = value;
WriteLine("-/-Georgetown Cleaning Services -/-");
WriteLine("===================================");
-/-Georgetown Cleaning Services -/- =================================== Press any key to close this window . . .
using static System.Console; string customerName = "James Burreck"; string homePhone = "(202) 301-7030"; WriteLine("-/-Georgetown Cleaning Services -/-"); WriteLine("==================================="); Write("Customer: "); WriteLine(customerName); Write("Home Phone: "); WriteLine(homePhone); WriteLine("===================================");
-/-Georgetown Cleaning Services -/- =================================== Customer: James Burreck Home Phone: (202) 301-7030 =================================== Press any key to close this window . . .
Ordering Value Display
Imagine you have a certain value stored in a variable and you want to display the value of that variable on the screen. We already know that you can type Write() or WriteLine() and you can include a string in those parentheses. You can create an expression that includes the string in those parentheses and the value(s) of your choice. To proceed, the string in Write() or WriteLine() must be divided in two parts separated by a comma. The left side of the comma is the rough string you want to display. The right side of the comma is the name of a variable or a list of variables. If you use a list of variables (on the right side of the commas), the variables must be separated by commas. In the left string, type some curly bracjets, {}, for each variable that is on the right side of the comma. The {} combination is called a placeholder. If you are displaying only one variable, include 0 in the {} placeholder. If you are displaying more than one variable, the numbers in the {} placeholders muts be cumulative, as {0}, {1}, {2}, etc. The formulas to follow are:
Write("Something {0}", value); Write("Something {0} {1}", value1, value2); Write("Something {0} {1} {2}", value1, value2, value3); Write("Something {0} {1} {2} {3}", value1, value2, value3, value4); WriteLine("Something {0}", value); WriteLine("Something {0} {1}", value1, value2); WriteLine("Something {0} {1} {2}", value1, value2, value3); WriteLine("Something {0} {1} {2} {3}", value1, value2, value3, value4);
String Interpolation
String interpolation consists of inserting one string in another existing string to get a new string. To perform this operation, start the existing string with the $ sign. In the existing string, include the curly bracjets placeholder {}. In the {} placeholder, include the desired string. Normally, you usually perform this operation for a string variable. Here is an example:
using static System.Console; string firstName = "Robert"; WriteLine($"First Name: {firstName}"); WriteLine("===================================");
This would produce:
First Name: Robert =================================== Press any key to close this window . . .
If you want to interpolate more strings, create as many {} sections as you want. In each {} placeholder, include the variable of your choice. Here is an example:
using static System.Console; string firstName = "Robert"; string lastName = "Ellis"; WriteLine($"Customer: {firstName} {lastName}"); WriteLine("===================================");
This would produce:
Customer: Robert Ellis =================================== Press any key to close this window . . .
The Width to Display a Value
The {} placeholder is primarily used to hold a value. One way to control the display of the value is to specify how wide an area must be reserved for the value. To specify this information, on the right side of the value in the placeholder, type a comma and a number for the desired width. Such a value is aligned to the right side of the reserved area. If you want the value to be aligned to the left, provide the value as a negative. Here are examples:
using static System.Console; string firstName = "Robert"; string mi = "T"; string lastName = "Ellis"; WriteLine("First Name: '{0,10}'", firstName); WriteLine("Middle: '{0,10}'", mi); WriteLine("Last Name: '{0,10}'", lastName); WriteLine("-----------------------------------"); WriteLine("First Name: '{0,-10}'", firstName); WriteLine("Middle: '{0,-10}'", mi); WriteLine("Last Name: '{0,-10}'", lastName); WriteLine("==================================="); WriteLine($"First Name: {firstName}"); WriteLine($"First Name: '{firstName}'"); WriteLine($"First Name: '{firstName,20}'"); WriteLine($"First Name: '{firstName,-20}'");
This would produce:
First Name: ' Robert' Middle: ' T' Last Name: ' Ellis' ----------------------------------- First Name: 'Robert ' Middle: 'T ' Last Name: 'Ellis ' =================================== First Name: Robert First Name: 'Robert' First Name: ' Robert' First Name: 'Robert ' Press any key to close this window . . .
Requesting a String
Program interactivity allows a user to submit value to an application so that you would process those value. To do this, write ReadLine(). When the program executes, the carret would blink to the user to type something. To indicate what the user is supposed to type, you can precede ReadLine() with with a string in Write() or WriteLine().
When the user has typed something in response to ReadLine(), you can get that value and store it in a variable. To do that, assign ReadLine() to a string. You can then use that variable normally. In tje same way, you can use ReadLine() as many times as you want.
Introduction to Natural Numbers
Overview
A natural number is a value that contains only digits. To recognize such values, the C# language provides a data type named int. Use it to declare a variable that would hold a natural number. Here is an example:
using static System.Console;
int age;
The Value of an Integral Variable
To specify the variable of an int type, provide a value that contains only digits. Here is an example:
using static System.Console;
int age = 15;
Displaying an Integral Value
To display a number to the user, you can include that number in the parentheses of Write() or WriteLine(). Here is an example:
using static System.Console;
WriteLine(9285);
This would produce:
9285 Press any key to close this window . . .
If the value is stored in a variable, you can either display that value to the user, you can type the name of the variable in the parentheses of Write() or WriteLine(). Here are two examples:
using static System.Console; int monthlySalary = 3288; Write("Monthly Salary: "); WriteLine(monthlySalary);
This would produce:
Monthly Salary: 3288 Press any key to close this window . . .
You can also use string interpolatione to display the value of an integral variable. To do this, as seen with strings, start the interior of the parentheses of Write() or WriteLine() with $ followed by double-quotes. In the double-quote, write {}. In those square brackets, include the name of the integral variable.
Creating a Large Integer
The value of an integer can be between -2147483648 and 2147484647 (or -2,147,483,648 and 2,147,484,647). If you need to use a large value, to make it easier to humanly read, you can separate the thousands by underscores. Here are examples:
using static System.Console; int areaOfChina = 9_596_961; int areaOfCanada = 9_984_670; int areaOfBurkinaFaso = 275_200; int areaOfDjibouti = 23_200; WriteLine("Countries Areas"); WriteLine("---------------------"); Write("Djibouti: "); WriteLine(areaOfDjibouti); Write("Burkina Faso: "); WriteLine(areaOfBurkinaFaso); Write("China: "); WriteLine(areaOfChina); Write("Canada: "); WriteLine(areaOfCanada);
This would produce:
Countries Areas --------------------- Djibouti: 23200 Burkina Faso: 275200 China: 9596961 Canada: 9984670 Press any key to close this window . . .
Practical Learning: Introducing Integers
using static System.Console; string customerName = "James Burreck"; string homePhone = "(202) 301-7030"; int numberOfShirts = 1; int numberOfPants = 1; int numberOfDresses = 1; int orderMonth = 3; int orderDay = 15; int orderYear = 2020; WriteLine("-/-Georgetown Cleaning Services -/-"); WriteLine("==================================="); Write("Customer: "); WriteLine(customerName); Write("Home Phone: "); WriteLine(homePhone); Write("Order Date: "); Write(orderMonth); Write("/"); Write(orderDay); Write("/"); WriteLine(orderYear); WriteLine("-----------------------------------"); WriteLine("Item Type Qty"); WriteLine("-----------------------------------"); Write("Shirts "); WriteLine(numberOfShirts); Write("Pants "); WriteLine(numberOfPants); Write("Dresses "); WriteLine(numberOfDresses); WriteLine("===================================");
-/-Georgetown Cleaning Services -/- =================================== Customer: James Burreck Home Phone: (202) 301-7030 Order Date: 3/15/2020 ----------------------------------- Item Type Qty ----------------------------------- Shirts 1 Pants 1 Dresses 1 =================================== Press any key to close this window . . .
Converting a Value to an Integer
Your programs will deal with various types of values. Some of those values must be involved in arithmetic operations, but sometimes, when you have a value, you don't know what type that value is. Normally, beformed involving a value in a number-based operation, you may have to first convert that value to a number. To do this, type int.Parse(). In the parentheses of int.Parse(), type the value to be converted. Here is an example:
using static System.Console; string value = "3528"; int number = int.Parse(value); WriteLine(number);
Requesting an Integral Value
We already saw that, to request a value, you can use ReadLine(), but ReadLine() gets a string. As a result, you must convert the value of ReadLine() to an integer. To do that, ou can first get the value, then convert it. This can be done in two steps as follows:
using static System.Console; Write("Enter a number: "); string request = ReadLine(); int number = int.Parse(request); WriteLine(number); WriteLine("===================================");
To reduce the number of lines of your code, you can include ReadLine() in the parentheses of int.Parse().
Introduction to Floating-Point Numbers
A floating-point number is a number made of either only digits or two digit parts separated by a symbol referred to as a decimal separator. As one way to support floating-point numbers, the C# language provides a data type named double. Use it to declare a variable for a number. To provide a value for the variable, you can use the same types of numbers we saw for integers. Here are examples:
using static System.Console; double areaMaine = 35385; double areaAlaska = 1_723_337; WriteLine("States Areas"); Write("Maine: "); WriteLine(areaMaine); Write("Alaska: "); WriteLine(areaAlaska);
This would produce:
Monthly Salary: 3288 Press any key to close this window . . .
A Floating-Point Number with Precision
The primary difference between an integer and a floating-point number is that a decimal number can include a second part referred to as a precision. To specify the precision of a number, after the natural part, add the symbol used as the decimal separator. In US English, this is the period. Here is an example:
using static System.Console;
double hourlySalary = 25.85;
Write("Hourly Salary: ");
WriteLine(hourlySalary);
This would produce:
Hourly Salary: 25.85 Press any key to close this window . . .
If the integral part is large, you can use it "as is" or you can separate its thousansds with underscores. Here are examples:
using static System.Console; double areaGuam = 570.62; double areaAlaska = 665_384.04; double areaSouthDakota = 77115.68; double areaTennessee = 42_144.25; WriteLine("States Areas"); WriteLine("======================="); Write("Guam: "); WriteLine(areaGuam); Write("Alaska: "); WriteLine(areaAlaska); Write("Tennessee: "); WriteLine(areaTennessee); Write("South Dakota: "); WriteLine(areaSouthDakota);
This would produce:
States Areas ======================= Guam: 570.62 Alaska: 665384.04 Tennessee: 42144.25 South Dakota: 77115.68 Press any key to close this window . . .
In the above examples, we used the underscore separator only on the integral part of the number. In reality, you can also use that separator in the precision side. Here are examples:
using static System.Console; double number = 085.24_497; double value = 947_596.75_038; Write("Number: "); WriteLine(number); Write("Value: "); WriteLine(value); WriteLine("===================================");
This would produce:
Number: 85.24497 Value: 947596.75038 =================================== Press any key to close this window . . .
Converting a Value to Double-Precision
To convert a value to a floating-point number with double-precision, type double.Parse(). As seen with integers, in the parentheses of double.Parse(), type the value to be converted. Here is an example:
using static System.Console; string value = "495.86"; double number = double.Parse(value); WriteLine(number);
Requesting a Decimal Number
We saw that, to request a value, you can use ReadLine(). Once you have the value, you must convert it to a double value. We saw that you can use double.Parse() to do that. Here is an example:
using static System.Console; Write("Enter a number: "); string request = ReadLine(); double number = double.Parse(request); WriteLine(number); WriteLine("===================================");
You can also include ReadLine() in the parentheses of double.Parse().
Displaying a Decimal Number
Introduction
So far, to display the value of a decimal variable, we simply typed it in the parentheses of Write() or WriteLine() as we saw with strings (and integers). You can also use string interpolation to display the value. Here are examples:
using static System.Console; double number = 285.24_497; double value = 947_596.75_038; WriteLine($"Number: {number}"); WriteLine($"Value: {value}"); WriteLine("===================================");
This would produce:
Number: 285.24497 Value: 947596.75038 =================================== Press any key to close this window . . .
Displaying a Number with Fixed Precision
Because floating-point numbers use a precision part, sometimes you want to control how the number displays. The string interpolation mechanism provides many options. To start, in the {} placeholder, after the name of the variable, type a colon (:). After the colon, if you want to display the number with two decimal places, type f or F, n. Here are examples:
using static System.Console; double nbr = 4848075.5279; double val = 63828493.806; double number = 28835.24_497; double value = 947_596.75_038; WriteLine($"Number: {nbr:f}"); WriteLine($"Value: {val:f}"); WriteLine($"Number: {number:F}"); WriteLine($"Value: {value:F}"); WriteLine("===================================");
This would produce:
Number: 4848075.53 Value: 63828493.81 Number: 28835.24 Value: 947596.75 =================================== Press any key to close this window . . .
Formatting the Number with Thousands Separators
If the integral part of the number is large and you want to display it with decimal separators in the integral part but two decimal places, in the {} placeholder of the string interpolation, after the colon (:), type n or N. Here are examples:
using static System.Console; double nbr = 484.5279; double val = 63.806828493; double number = 288358075.24_497; double value = 947_596.75_038; WriteLine($"Number: {nbr:n}"); WriteLine($"Value: {val:n}"); WriteLine($"Number: {number:N}"); WriteLine($"Value: {value:N}"); WriteLine("===================================");
This would produce:
Number: 484.53 Value: 63.81 Number: 288,358,075.24 Value: 947,596.75 =================================== Press any key to close this window . . .
Practical Learning: Introducing Double-Precision Numbers
using static System.Console; string customerName = "James Burreck"; string homePhone = "(202) 301-7030"; int numberOfShirts = 1; int numberOfPants = 1; int numberOfDresses = 1; double priceOneShirt = 0.95; double priceAPairOfPants = 2.95; double priceOneDress = 4.55; int orderMonth = 3; int orderDay = 15; int orderYear = 2020; WriteLine("-/-Georgetown Cleaning Services -/-"); WriteLine("==================================="); Write("Customer: "); WriteLine(customerName); Write("Home Phone: "); WriteLine(homePhone); Write("Order Date: "); Write(orderMonth); Write("/"); Write(orderDay); Write("/"); WriteLine(orderYear); WriteLine("-----------------------------------"); WriteLine("Item Type Qty Sub-Total"); WriteLine("------------------------"); Write("Shirts "); Write(numberOfShirts); Write(" "); WriteLine(priceOneShirt); Write("Pants "); Write(numberOfPants); Write(" "); WriteLine(priceAPairOfPants); Write("Dresses "); Write(numberOfDresses); Write(" "); WriteLine(priceOneDress); WriteLine("===================================");
-/-Georgetown Cleaning Services -/- =================================== Customer: James Burreck Home Phone: (202) 301-7030 Order Date: 3/15/2020 ----------------------------------- Item Type Qty ----------------------------------- Shirts 1 Pants 1 Dresses 1 =================================== Press any key to close this window . . .
Managing Variables
Introduction
Microsoft Visual Studio provides many tools you can use to manage code and manage your variables. The Code Editor of Microsoft Visual Studio provides many tools to assist you in managing your code.
If you are using Microsoft Visual Studio and if you want to find different occurrences of a known character, symbol, word, or group of words, first select that item. Then:
In the same way, if you have a variable that is used more than once in your code and you want to see all places where that variable is used, simply click the name (and wait a second) and all of its occurrences would be highlighted:
To get a list of all sections where the variable is used, if you are using Microsoft Visual Studio:
This would produce a list of all sections where the variable is used and would display the list in the Find Symbol Results window:
To access a particular section where the variable is used, double-click its entry in the list.
Cutting, Copying, and Pasting Code
Normally, from your knowledge of using computers, you probably already know how to select, cut, and copy text. These two operations can be valuable to save code in Microsoft Visual Studio. This means that, if you have code you want to use in different sections, you can preserve it somewhere to access it whenever necessary.
To save code to use over and over again, first type the code in any text editor, whether in Notepad, Microsoft Word, or the Code Editor of Microsoft Visual Studio. You can use code from any document where text can be copied, including a web page. Select that code and copy it to the clipboard. To preserve it, in Microsoft Visual Studio, display the Toolbox (on the main menu, you can click View -> Toolbox). Right-click an empty area on the Toolbox and click Paste.
An alternative is to select the code, whether in the Code Editor or in a text editor. Then drag it and drop it on the Toolbox. In the same way, you can add different code items to the Toolbox. After pasting or adding the code to the Toolbox, it becomes available. To use that code, drag it from the Toolbox and drop it in the section of the Code Editor where you want to use it.
Renaming a Variable
As we will see throughout our lessons, there are many names you will use in your programs. After creating a name, in some cases you will have to change it. Microsoft Visual Studio makes it easy to find and change a name wherever it is used. Consider the following code:
using static System.Console; int nbr = 148; WriteLine(nbr);
To change the name of a variable, in the Code Editor, right-click the name of the variable and edit Rename:
This would display the Rename dialog box with the primary name:
If you want to change it, change the name of the variable. It would be automatically be updated wherever it is used in the project. If you want the studio to find and change the name inside the comments, click the Search in Comments check box. If the name is used in strings and you want to replace it, click the Search in Strings check box. When you click OK, the Preview Changes - Rename dialog box would come up. It shows the various parts where the name is used and will be replaced. If you still want to replace, click Apply.
Accessing a Variable's Declaration
If you create a long document that has many lines of code, in a certain section you may encounter a variable but you want to find out where it was declared. If you are using Microsoft Visual Studio, to access the place where a variable was declared:
In both cases, the caret would jump to where the variable was declared.
Accessing a Line of Code by its Index
If you are using the Code Editor of Microsoft Visual Studio, if you create a long document that has many lines of code, if you want to jump to a certain line of code:
This would display a dialog box. Enter the line number and click OK or press Enter.
Practical Learning: Ending the Lesson
|
|||
Previous | Copyright © 2001-2025, FunctionX | Monday 14 October 2024, 10:12 | Next |
|