0% found this document useful (0 votes)
11 views31 pages

L02&L03

The document provides an overview of C# programming concepts, focusing on variables, data types, identifiers, and user input. It explains how to declare and display variables, the importance of using appropriate data types, and how to handle user input with type conversion. Key data types such as int, double, char, string, and bool are described along with their usage and characteristics.

Uploaded by

kcia1100011
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)
11 views31 pages

L02&L03

The document provides an overview of C# programming concepts, focusing on variables, data types, identifiers, and user input. It explains how to declare and display variables, the importance of using appropriate data types, and how to handle user input with type conversion. Key data types such as int, double, char, string, and bool are described along with their usage and characteristics.

Uploaded by

kcia1100011
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/ 31

C#

L02&L03
Objectives
• C# Variables
• C# Display Variables
• C# Identifiers
• C# Data Types
• C# User Input
C# Variables
Variables are containers for storing data values.

In C#, there are different types of variables (defined with different keywords),
for example:

•int - stores integers (whole numbers), without decimals, such as 123 or -123
•double - stores floating point numbers, with decimals, such as 19.99 or -19.99
•char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
•string - stores text, such as "Hello World". String values are surrounded by
double quotes
•bool - stores values with two states: true or false
Declaring (Creating) Variables

• To create a variable, you must specify the type and


assign it a value:
type variableName = value;

• Where type is a C# type (such as int or string), and variableName is


the name of the variable (such as x or name). The equal sign is used
to assign values to the variable.
Declaring (Creating) Variables
• To create a variable that should store text, look at the following
example:
• Example
• Create a variable called name of type string and assign it the value
"John":

• string name = "John";


• Console.WriteLine(name);
Declaring (Creating) Variables
• To create a variable that should store a number, look at
the following example:
• Example
• Create a variable called myNum of type int and assign it the value 15:
• int myNum = 15;
• Console.WriteLine(myNum);
Declaring (Creating) Variables
• You can also declare a variable without assigning the value, and assign
the value later:
• int myNum;
• myNum = 15;
• Console.WriteLine(myNum);
Declaring (Creating) Variables
• Note that if you assign a new value to an existing
variable, it will overwrite the previous value:
• Example
• Change the value of myNum to 20:
• int myNum = 15;
• myNum = 20; // myNum is now 20
• Console.WriteLine(myNum);
Declaring (Creating) Variables
• Other Types
• A demonstration of how to declare variables of other types:
• int myNum = 5;
• double myDoubleNum = 5.99D;
• char myLetter = 'D';
• bool myBool = true;
• string myText = "Hello";
C# Display Variables
• The WriteLine() method is often used to display variable
values to the console window.

• To combine both text and a variable, use the + character:

string name = "John";


Console.WriteLine("Hello " + name);
C# Display Variables
• You can also use the + character to add a variable to another
variable:

string firstName = "John ";


string lastName = "Doe";
string fullName = firstName + lastName;
Console.WriteLine(fullName);
C# Display Variables
• For numeric values, the + character works as a mathematical operator (notice
that we use int (integer) variables here):

int x = 5;
int y = 6;
Console.WriteLine(x + y); // Print the value of x + y

• From the example above, you can expect:


• x stores the value 5
• y stores the value 6
• Then we use the WriteLine() method to display the value of x + y, which is 11
C# Multiple Variables
• To declare more than one variable of the same type, use a comma-
separated list:

int x = 5, y = 6, z = 50;
Console.WriteLine(x + y + z);
C# Multiple Variables
• You can also assign the same value to multiple variables in one line:

int x, y, z; x = y = z = 50;
Console.WriteLine(x + y + z);
C# Identifiers
• All C# variables must be identified with unique names.
• These unique names are called identifiers.

• Identifiers can be short names (like x and y) or more descriptive names


(age, sum, totalVolume).
• Note: It is recommended to use descriptive names in order to create
understandable and maintainable code:
// Good
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;
C# Identifiers
The general rules for naming variables are:

• Names can contain letters, digits, and the underscore character (_)
• Names must begin with a letter or underscore
• Names should start with a lowercase letter and it cannot contain
whitespace
• Names are case sensitive ("myVar" and "myvar" are different variables)
• Reserved words (like C# keywords, such as int or double) cannot be
used as names
C# Data Types
• As explained in the variables chapter, a variable in C#
must be a specified data type:

int myNum = 5; // Integer (whole number)


double myDoubleNum = 5.99D; // Floating point number
char myLetter = 'D'; // Character
bool myBool = true; // Boolean
string myText = "Hello"; // String
C# Data Types
• A data type specifies the size and type of variable
values.
• It is important to use the correct data type for the
corresponding variable:
• to avoid errors,
• to save time and memory,
• but it will also make your code more maintainable and
readable.
C# Data Types
The most common data types are:

Data Type Size Description


int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

bool 1 bit Stores true or false values


char 2 bytes Stores a single character/letter, surrounded by single quotes

string 2 bytes per Stores a sequence of characters, surrounded by double quotes


character
C# Data Types
• Number types are divided into two groups:

• Integer types stores whole numbers, positive or negative (such as 123


or -456), without decimals. Valid types are int and long. Which type
you should use, depends on the numeric value.

• Floating point types represents numbers with a fractional part,


containing one or more decimals. Valid types are float and double.
C# Data Types
• Int
• The int data type can store whole numbers from -2147483648 to
2147483647.
• In general, the int data type is the preferred data type when we
create variables with a numeric value.
int myNum = 100000;
Console.WriteLine(myNum);
C# Data Types
• Long
• The long data type can store whole numbers from -
9223372036854775808 to 9223372036854775807.
• This is used when int is not large enough to store the value. Note that
you should end the value with an "L":

long myNum = 15000000000L;


Console.WriteLine(myNum);
C# Data Types
• Floating Point Types
• You should use a floating point type whenever you need a number
with a decimal, such as 9.99 or 3.14515.

• The float and double data types can store fractional numbers.
float myNum = 5.75;
Console.WriteLine(myNum);
double myNum = 17.15;
Console.WriteLine(myNum);
C# Data Types
• Booleans
• A boolean data type is declared with the bool keyword and can only
take the values true or false:

bool isCSharpFun = true;


bool isFishTasty = false;
Console.WriteLine(isCSharpFun); // Outputs True
Console.WriteLine(isFishTasty); // Outputs False
C# Data Types
• Characters
• The char data type is used to store a single character.
• The character must be surrounded by single quotes, like 'A' or 'c’:

char myGrade = 'B’;


Console.WriteLine(myGrade);
C# Data Types
• Strings
• The string data type is used to store a sequence of characters (text).
String values must be surrounded by double quotes:

string greeting = "Hello World";


Console.WriteLine(greeting);
Type Conversion Methods
• It is possible to convert data types by using built-in methods, such as
Convert.ToBoolean, Convert.ToDouble, Convert.ToString,
Convert.ToInt32 (int), and Convert.ToInt64 (long):

int myInt = 10;


double myDouble = 5.25;
bool myBool = true;
Console.WriteLine(Convert.ToString(myInt)); // convert int to string
Console.WriteLine(Convert.ToDouble(myInt)); // convert int to double
Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int
Console.WriteLine(Convert.ToString(myBool)); // convert bool to string
C# User Input
• Get User Input
• Console.WriteLine() is used to output (print) values.
• Console.ReadLine() to get user input.

• In the following example, the user can input his username, which is
stored in the variable userName. Then we print the value of
userName:
C# User Input

// Type your username and press enter


Console.WriteLine("Enter username:");
// Create a string variable and get user input from the keyboard and store it in the variable
string userName = Console.ReadLine();
// Print the value of the variable (userName), which will display the input value
Console.WriteLine("Username is: " + userName);
C# User Input
• User Input and Numbers
• The Console.ReadLine() method returns a string. Therefore, you cannot get
information from another data type, such as int. The following program will cause
an error:

Console.WriteLine("Enter your age:");


int age = Console.ReadLine();
Console.WriteLine("Your age is: " + age);

• The error message will be something like this:

Cannot implicitly convert type 'string' to 'int'


C# User Input
• You can convert any type explicitly, by using one of the Convert.To
methods:
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);

You might also like