SlideShare a Scribd company logo
FUNDAMENTALS OF PROGRAMMING
WITH C#
"To Program“. What Does It Mean ?
To "program" means to organize the work of the computer
through sequences of instructions.
THE ESSENCE OF PROGRAMMING
The essence of programming is to control the work of the
computer on all levels. This is done with the help of
“instructions" from a programmer.
What is an algorithm?
A sequence of steps to achieve, complete some work or obtain some result.
Example:
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2 Step 5: Display sum Step
6: Stop
Programming involves describing what you want the
computer to do by a sequence of steps, by algorithms.
Programmers are the people who create these
instructions which control computers. These instructions
are called programs.
STAGES IN SOFTWARE DEVELOPMENT
• Gathering the Requirements
In the beginning, only an idea for a certain product exists. It includes a list of
requirements, which define actions by the users and the computer. The requirements
for the product are usually defined in the form of documentation made by experts,
who are familiar with the problems in a certain field. There is no programming done at
this stage.
• Planning and Preparing the Architecture and Design
After all the requirements have been gathered comes the planning stage. At this
stage, a technical plan for the implementation of the project is created, describing the
platforms, technologies and the initial architecture (design) of the product.
• Implementation
At this phase, the program (application) is implemented (written) according to the
given task, design and architecture. Programmers participate by writing the program
(source) code. The other stages can either be short or completely skipped when
creating a small project, but the implementation always presents; otherwise the
process is not software development.
• Product Testing
The purpose of this phase is to make sure that all the requirements are strictly
followed and covered. This stage is done using either an automated or a manual test
or both.
• Deployment and Operation
This is the process which puts a given software product into exploitation. If the
product is complex and serves many people, this process can be the slowest and
most expensive one. For smaller programs this is a relatively quick and painless
process.
• Technical Support
Problems may occur during the exploitation process. They may be caused by many
factors – errors in the software, incorrect usage or faulty configuration, but most
problems occur when the users change their requirements. As a result of these
problems, the software loses its abilities to solve the business task it was created for.
This requires additional involvement by the developers and the support experts. The
support process usually continues throughout the whole life-cycle of the software
product, regardless of how good it is.
• Documentation
Not a separate stage but accompanies all the other stages. Documentation is an
important part of software development, it aims to pass knowledge between the
different participants in the development and support of a software product.
Information is passed along between different stages as well as within a single stage.
INTRODUCTION TO C#
What is C#?
C# is an elegant and type-safe object-oriented language that enables developers to
build a variety of secure and robust applications that run on the .NET Framework. It is
a language developed by, its syntax is similar to that of C and C++. C# and .NET are
Microsoft’s natural response to the Java technology.
• C# is case sensitive, be careful when writing a code, the same keywords, written in
uppercase, lower-case or a mix of both, means different things in C#. The Program
Code must be correctly formatted. Formatting is adding characters such as spaces,
tabs and new lines, which are insignificant to the compiler but they give the code a
logical structure and make it easier to read. Improper formatting makes the code
difficult to read and understand, and therefore difficult to modify and maintain.
STRUCTURE OF A C# CODE
class HelloWorld //defining a class
{
static void Main(string[] args) //defining a method
//contents of the method
{
System.Console.WriteLine("Hello Earth!");
System.Console.WriteLine("I am Human!");
}
}
DEFINING A CLASS
The simplest definition of a class consists of the keyword class, followed by the name
of the class. The content of the class is located in a block of program lines,
surrounded by curly brackets: { }.
DEFINING THE MAIN() METHOD
static void Main(string[] args)
The method must be declared as shown above, it must be static and void, it
must have a name Main and as a list of parameters it must have only one
parameter of type array of string. In our example the parameter is called args
but that is not mandatory. This parameter is not used in most cases so it can
be omitted (it is optional). In which case the entry point of the program can be
simplified and will look like this:
static void Main()
CONTENTS OF THE MAIN()
METHOD
The content of every method is found after its signature, surrounded by
opening and closing curly brackets.
FILE NAMES CORRESPOND TO CLASS
NAMES
Every C# program consists of one or several class definitions. It is accepted that each
class is defined in a separate file with a name corresponding to the class name and a
.cs extension.
DATA TYPES
Data types are sets (ranges) of values that have similar characteristics.
Basic data types in C# are distributed into the following types:
• Integer types – Integer types represent integer numbers and are sbyte, byte, short,
ushort, int, uint, long and ulongReal floating-point types – float, double;
• Real type– Real types in C# are the real numbers we know from mathematics. They
are represented by a floating-point and are float and double.
• Boolean type – boolean type is declared with the keyword bool. It has two possible
values: true and false. Its default value is false and it is used most often to store the
calculation result of logical expressions.
• Character type – character type is a single character char, it is declared in C# with
the keyword char. Strings are sequences of characters, declared by the keyword
string, strings are enclosed in quotation marks.
• Object type – object type is a special type, which is the parent of all other types in
the .NET Framework. Declared with the keyword object, it can take values from any
other type. It is a reference type, i.e. an index (address) of a memory area which
stores the actual value.
VARIABLES
A variable is a named area of memory which stores a value from a particular
data type, and that area of memory is accessible in the program by its name.
Variables can be stored directly in the operational memory of the program (in
the stack) or in the dynamic memory in which larger objects are stored (such
as character strings and arrays).
RULES FOR NAMING VARIABLES
The name of the a variable can be any of our choice but must follow certain rules
defined in the C# language specification:
• Variable names can contain the letters a-z, A-Z, the digits 0-9 as well as the
character '_'.
• Variable names cannot start with a digit.
• Keywords of the C# language such as base, char, default, int, object, this, null and
many others cannot be used as variable names.
DECLARING VARIABLES
The syntax for declaring variables in C# is as follows:
<data type> <identifier> [= <initialization>];
When you declare a variable, you perform the following steps:
• specify its type (such as int);
• specify its name (identifier, such as age);
• specify an initial value (optional).
Initialization of Variables
• Assigning a value to a variable is the act of providing a value that must be stored in
the variable. This operation is performed by the assignment operator "=". The word
initialization in programming means specifying an initial value.
Example:
// Declare and initialize some variables
byte centuries = 20;
ushort years = 2000;
decimal decimalPI = 3.141592653589793238m;
bool isEmpty = true;
char ch = 'a';
string firstName = "John";
ch = (char)5;
char secondChar;
// Here we use an already initialized variable and reassign it
secondChar = ch;
OPERATORS
Operators allows processing of data. They take as an input one or more operands and return
some value as a result. Operators in C# are special characters (such as "+", ".", "^", etc.) and
they perform transformations on one, two or three operands.
Operators in C# can be separated in several different categories:
• Arithmetic operators – they are used to perform simple mathematical operations, this
category involves the following operators: -, +, *, /, %, ++, --
• Assignment operators – allow assigning values to variables, , this category involves the
following operators: =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
• Comparison operators – allow comparison of two literals and/or variables, this
category involves the following operators: ==, !=, >, =, <=
• Logical operators – operators that work with Boolean data types and Boolean
expressions, this category involves the following operators: &&, ||, !,
• Type conversion operators – allow conversion of data from one type to another, this
category involves the following operators: (type), as, is, typeof, sizeof
Example: Arithmetic operators
int squarePerimeter = 17;
double squareSide = squarePerimeter / 4.0;
double squareArea = squareSide * squareSide;
Console.WriteLine(squareSide); // 4.25
Console.WriteLine(squareArea); // 18.0625
int a = 5;
int b = 4;
Console.WriteLine(a + b); // 9
Console.WriteLine(a + (b++)); // 9
Console.WriteLine(a + b); // 10
Console.WriteLine(a + (++b)); // 11
Console.WriteLine(a + b); // 11
Console.WriteLine(14 / a); // 2
Console.WriteLine(14 % a); // 4
Example: Logical Operators
bool a = true;
bool b = false;
Console.WriteLine(a && b); // False
Console.WriteLine(a || b); // True
Console.WriteLine(!b); // True
Console.WriteLine(b || true); // True
Console.WriteLine((5 > 7) ^ (a == b)); // False
Example: Comparison Operators
int x = 10, y = 5;
Console.WriteLine("x > y : " + (x > y)); // True
Console.WriteLine("x < y : " + (x < y)); // False
Console.WriteLine("x >= y : " + (x >= y)); // True
Console.WriteLine("x <= y : " + (x <= y)); // False
Console.WriteLine("x == y : " + (x == y)); // False
Console.WriteLine("x != y : " + (x != y)); // True
Example: Assignment Operators
int x = 6;
int y = 4;
Console.WriteLine(y *= 2); // 8
int z = y = 3; // y=3 and z=3
Console.WriteLine(z); // 3
Console.WriteLine(x += 4); // 10
Console.WriteLine(x /= 2); // 5
Example: Type Conversion Operators
int myInt = 5;
Console.WriteLine(myInt); // 5
long myLong = myInt;
Console.WriteLine(myLong); // 5
Console.WriteLine(myLong + myInt); // 10
WHAT IS THE CONSOLE?
The Console is a window of the operating system through which users can interact
with system programs of the operating system or with other console applications. The
interaction consists of text input from the standard input (usually keyboard) or text
display on the standard output. These actions are also known as input-output
operations. The text written on the console brings some information and is a
sequence of characters sent by one or more programs.
WHEN TO USE THE CONSOLE?
In some cases the console remains an irreplaceable tool for communication with the
user. One of these cases is when writing small and simple programs where it is
necessary to focus the attention on the specific problem to be solved, rather than the
elegant representation of the result to the user. Then a simple solution is used for
entering or printing a result, such as input/output console. Another use case is when
we want to test a small piece of code for a larger application. Due to simplicity of the
operation of the console application we can isolate this part of the code easily and
comfortably without having to go through a complex user interface and a number of
screens to get to the desired code for testing.
CONSOLE.OUT STREAM
System.Console class has different properties and methods which are used to read
and display text on the console as well as its formatting. Among them there are three
properties that make impression and they are related toinput/output, namely the
Console.Out, Console.In and Console.Error. They provide access to the standard
streams for printing on the console, for reading from the console and to the error
messages reporting stream accordingly.
Example:
// Print String
Console.WriteLine("Hello World");
// Print int
Console.WriteLine(5);
// Print double
Console.WriteLine(3.14159265358979);
READING THROUGH
CONSOLE.READLINE()
The method Console.ReadLine() provides great convenience for reading from
console. How does it work? When this method is invoked, the program waits for an
input from the console. The user enters some string on the console and presses the
[Enter] key. At this moment the console understands that the user has finished
entering and reads the string. The method Console.ReadLine() returns as result the
string entered by the user.
Example:
Console.Write("Please enter your first name: ");
string firstName = Console.ReadLine();
Console.Write("Please enter your last name: ");
string lastName = Console.ReadLine();
Console.WriteLine("Hello, {0} {1}!", firstName, lastName);
// Output: Please enter your first name: My
// Please enter your last name: Name
//Hello, My Name!
READING NUMBERS
Reading numbers from the console in C# is not done directly. In order to read a
number we should have previously read the input as a string (using ReadLine()) and
then convert this string to a number. This process is called parsing.
Example:
class RedingNumbers
{
static void Main(string[] args)
{
Console.Write("a = ");
int a = int.Parse(Console.ReadLine());
Console.Write("b = ");
int b = int.Parse(Console.ReadLine());
Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
Console.Write("f = ");
double f = double.Parse(Console.ReadLine());
Console.WriteLine("{0} * {1} / {2} = {3}",
a, b, f, a * b / f);
}
}
READING BY CONSOLE.READKEY()
The method Console.ReadKey() waits for key pressing on the console and reads its
character equivalent without the need of pressing [Enter]. The result of invoking
ReadKey() is information about the pressed key (or more accurately a key
combination) as an object of type ConsoleKeyInfo.
Example:
ConsoleKeyInfo key = Console.ReadKey();
Console.WriteLine("Character entered: " + key.KeyChar);
CONSOLE INPUT AND OUTPUT EXAMPLE
Console.WriteLine("This program calculates " +
"the area of a rectangle or a triangle");
Console.WriteLine("Enter a and b (for rectangle) " +
"or a and h (for triangle): ");
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
Console.WriteLine("Enter 1 for a rectangle or " +
"2 for a triangle: ");
int choice = int.Parse(Console.ReadLine());
double area = (double)(a * b) / choice;
Console.WriteLine("The area of your figure is " + area);
Console.ReadLine();
CONDITIONAL STATEMENT "IF" AND "IF-
ELSE"
Because of conditional statements a program can behave differently based on a
defined condition checked during the execution of the statement.
Conditional Statement "if“
Includes: if-clause, Boolean expression and body of the conditional statement. The
Boolean expression can be a Boolean variable or Boolean logical expression.
Boolean expressions cannot be integer.
The expression in the brackets which follows the keyword if must return the Boolean
value true or false. If the expression is calculated to the value true, then the body of a
conditional statement is executed. If the result is false, then the operators in the body
will be skipped.
Example:
Console.WriteLine("Enter two numbers.");
Console.Write("Enter first number: ");
int firstNumber = int.Parse(Console.ReadLine());
Console.Write("Enter second number: ");
int secondNumber = int.Parse(Console.ReadLine());
int biggerNumber = firstNumber;
if (secondNumber > firstNumber)
{
biggerNumber = secondNumber;
}
Console.WriteLine("The bigger number is: {0}", biggerNumber);
Conditional Statement "if-else“
The format of the if-else structure consists of the reserved word if, Boolean expression,
body of a conditional statement, reserved word else and else-body statement. The body
of else-structure may consist of one or more operators, enclosed in curly brackets, same
as the body of a conditional statement.
This statement works as follows: the expression in the brackets (a Boolean expression) is
calculated. The calculation result must be Boolean – true or false. Depending on the
result there are two possible outcomes. If the Boolean expression is calculated to true,
the body of the conditional statement is executed and the else-statement is omitted and
its operators do not execute. Otherwise, if the Boolean expression is calculated to false,
the else-body is executed, the main body of the conditional statement is omitted and the
operators in it are not executed.
Example:
int first = 5;
int second = 3;
if (first == second)
{
Console.WriteLine("These two numbers are equal.");
}
else
{
if (first > second)
{
Console.WriteLine("The first number is greater.");
}
else
{
Console.WriteLine("The second number is greater.");
}
}
Conditional Statement "switch-case“
The structure switch-case chooses which part of the programming code to execute
based on the calculated value of a certain expression (most often of integer type).
The selector is an expression returning a resulting value that can be compared, like a
number or string. The switch operator compares the result of the selector to every
value listed in the case labels in the body of the switch structure. If a match is found in
a case label, the corresponding structure is executed. If no match is found, the default
statement is executed (when such exists). The value of the selector must be
calculated before comparing it to the values inside the switch structure. The labels
should not have repeating values, they must be unique.
Example:
int number = 6;
switch (number)
{
case 1:
case 4:
case 6:
case 8:
case 10:
Console.WriteLine("The number is not prime!"); break;
case 2:
case 3:
case 5:
case 7:
Console.WriteLine("The number is prime!"); break;
default:
Console.WriteLine("Unknown number!"); break;
}

More Related Content

PPTX
object oriented programming part inheritance.pptx
PDF
CP c++ programing project Unit 1 intro.pdf
PPT
Introduction To Programming subject1.ppt
PPT
Lecture 01 2017
PDF
Pc module1
PPTX
C Programming Unit-1
PDF
Deepakkumarassignmentnumberdiles1 01.pdf
PDF
Learn C# programming - Program Structure & Basic Syntax
object oriented programming part inheritance.pptx
CP c++ programing project Unit 1 intro.pdf
Introduction To Programming subject1.ppt
Lecture 01 2017
Pc module1
C Programming Unit-1
Deepakkumarassignmentnumberdiles1 01.pdf
Learn C# programming - Program Structure & Basic Syntax

Similar to c#.pptx (20)

PPTX
Unit-1 (introduction to c language).pptx
PPT
490450755-Chapter-2.ppt
PPT
490450755-Chapter-2.ppt
PDF
Learning the C Language
PPTX
STRUCTURED PROGRAMMING (USING C PROGRAMMING).pptx
PPTX
unit2.pptx
PPT
Chapter-2 edited on Programming in Can refer this ppt
PPTX
C language ppt
PPTX
Unit-2.pptx
PPTX
object oriented programming language in c++
PDF
Introduction to Programming Fundamentals 3.pdf
PPTX
C++ Introduction to basic C++ IN THIS YOU WOULD KHOW ABOUT BASIC C++
PPT
history of c.ppt
PPTX
Intro in understanding to C programming .pptx
PPTX
Intro in understanding to C programming .pptx
PPTX
1.0 Introduction to C programming for all first year courses.pptx
PPT
8844632.ppt
DOC
Exhibit design and programming skills to build and automate business solution...
PPTX
c programming session 1.pptx
PPTX
Presentation c++
Unit-1 (introduction to c language).pptx
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
Learning the C Language
STRUCTURED PROGRAMMING (USING C PROGRAMMING).pptx
unit2.pptx
Chapter-2 edited on Programming in Can refer this ppt
C language ppt
Unit-2.pptx
object oriented programming language in c++
Introduction to Programming Fundamentals 3.pdf
C++ Introduction to basic C++ IN THIS YOU WOULD KHOW ABOUT BASIC C++
history of c.ppt
Intro in understanding to C programming .pptx
Intro in understanding to C programming .pptx
1.0 Introduction to C programming for all first year courses.pptx
8844632.ppt
Exhibit design and programming skills to build and automate business solution...
c programming session 1.pptx
Presentation c++
Ad

Recently uploaded (20)

PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
Introduction to Artificial Intelligence
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Nekopoi APK 2025 free lastest update
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Transform Your Business with a Software ERP System
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
top salesforce developer skills in 2025.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Design an Analysis of Algorithms II-SECS-1021-03
Introduction to Artificial Intelligence
Wondershare Filmora 15 Crack With Activation Key [2025
Design an Analysis of Algorithms I-SECS-1021-03
Reimagine Home Health with the Power of Agentic AI​
How Creative Agencies Leverage Project Management Software.pdf
How to Migrate SBCGlobal Email to Yahoo Easily
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Nekopoi APK 2025 free lastest update
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Operating system designcfffgfgggggggvggggggggg
How to Choose the Right IT Partner for Your Business in Malaysia
Transform Your Business with a Software ERP System
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
top salesforce developer skills in 2025.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
2025 Textile ERP Trends: SAP, Odoo & Oracle
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Ad

c#.pptx

  • 2. "To Program“. What Does It Mean ?
  • 3. To "program" means to organize the work of the computer through sequences of instructions.
  • 4. THE ESSENCE OF PROGRAMMING The essence of programming is to control the work of the computer on all levels. This is done with the help of “instructions" from a programmer.
  • 5. What is an algorithm?
  • 6. A sequence of steps to achieve, complete some work or obtain some result. Example: Step 1: Start Step 2: Declare variables num1, num2 and sum. Step 3: Read values num1 and num2. Step 4: Add num1 and num2 and assign the result to sum. sum←num1+num2 Step 5: Display sum Step 6: Stop
  • 7. Programming involves describing what you want the computer to do by a sequence of steps, by algorithms. Programmers are the people who create these instructions which control computers. These instructions are called programs.
  • 8. STAGES IN SOFTWARE DEVELOPMENT • Gathering the Requirements In the beginning, only an idea for a certain product exists. It includes a list of requirements, which define actions by the users and the computer. The requirements for the product are usually defined in the form of documentation made by experts, who are familiar with the problems in a certain field. There is no programming done at this stage.
  • 9. • Planning and Preparing the Architecture and Design After all the requirements have been gathered comes the planning stage. At this stage, a technical plan for the implementation of the project is created, describing the platforms, technologies and the initial architecture (design) of the product.
  • 10. • Implementation At this phase, the program (application) is implemented (written) according to the given task, design and architecture. Programmers participate by writing the program (source) code. The other stages can either be short or completely skipped when creating a small project, but the implementation always presents; otherwise the process is not software development.
  • 11. • Product Testing The purpose of this phase is to make sure that all the requirements are strictly followed and covered. This stage is done using either an automated or a manual test or both.
  • 12. • Deployment and Operation This is the process which puts a given software product into exploitation. If the product is complex and serves many people, this process can be the slowest and most expensive one. For smaller programs this is a relatively quick and painless process.
  • 13. • Technical Support Problems may occur during the exploitation process. They may be caused by many factors – errors in the software, incorrect usage or faulty configuration, but most problems occur when the users change their requirements. As a result of these problems, the software loses its abilities to solve the business task it was created for. This requires additional involvement by the developers and the support experts. The support process usually continues throughout the whole life-cycle of the software product, regardless of how good it is.
  • 14. • Documentation Not a separate stage but accompanies all the other stages. Documentation is an important part of software development, it aims to pass knowledge between the different participants in the development and support of a software product. Information is passed along between different stages as well as within a single stage.
  • 15. INTRODUCTION TO C# What is C#? C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. It is a language developed by, its syntax is similar to that of C and C++. C# and .NET are Microsoft’s natural response to the Java technology.
  • 16. • C# is case sensitive, be careful when writing a code, the same keywords, written in uppercase, lower-case or a mix of both, means different things in C#. The Program Code must be correctly formatted. Formatting is adding characters such as spaces, tabs and new lines, which are insignificant to the compiler but they give the code a logical structure and make it easier to read. Improper formatting makes the code difficult to read and understand, and therefore difficult to modify and maintain.
  • 17. STRUCTURE OF A C# CODE class HelloWorld //defining a class { static void Main(string[] args) //defining a method //contents of the method { System.Console.WriteLine("Hello Earth!"); System.Console.WriteLine("I am Human!"); } }
  • 18. DEFINING A CLASS The simplest definition of a class consists of the keyword class, followed by the name of the class. The content of the class is located in a block of program lines, surrounded by curly brackets: { }.
  • 19. DEFINING THE MAIN() METHOD static void Main(string[] args) The method must be declared as shown above, it must be static and void, it must have a name Main and as a list of parameters it must have only one parameter of type array of string. In our example the parameter is called args but that is not mandatory. This parameter is not used in most cases so it can be omitted (it is optional). In which case the entry point of the program can be simplified and will look like this: static void Main()
  • 20. CONTENTS OF THE MAIN() METHOD The content of every method is found after its signature, surrounded by opening and closing curly brackets.
  • 21. FILE NAMES CORRESPOND TO CLASS NAMES Every C# program consists of one or several class definitions. It is accepted that each class is defined in a separate file with a name corresponding to the class name and a .cs extension.
  • 22. DATA TYPES Data types are sets (ranges) of values that have similar characteristics. Basic data types in C# are distributed into the following types: • Integer types – Integer types represent integer numbers and are sbyte, byte, short, ushort, int, uint, long and ulongReal floating-point types – float, double; • Real type– Real types in C# are the real numbers we know from mathematics. They are represented by a floating-point and are float and double.
  • 23. • Boolean type – boolean type is declared with the keyword bool. It has two possible values: true and false. Its default value is false and it is used most often to store the calculation result of logical expressions. • Character type – character type is a single character char, it is declared in C# with the keyword char. Strings are sequences of characters, declared by the keyword string, strings are enclosed in quotation marks. • Object type – object type is a special type, which is the parent of all other types in the .NET Framework. Declared with the keyword object, it can take values from any other type. It is a reference type, i.e. an index (address) of a memory area which stores the actual value.
  • 24. VARIABLES A variable is a named area of memory which stores a value from a particular data type, and that area of memory is accessible in the program by its name. Variables can be stored directly in the operational memory of the program (in the stack) or in the dynamic memory in which larger objects are stored (such as character strings and arrays).
  • 25. RULES FOR NAMING VARIABLES The name of the a variable can be any of our choice but must follow certain rules defined in the C# language specification: • Variable names can contain the letters a-z, A-Z, the digits 0-9 as well as the character '_'. • Variable names cannot start with a digit. • Keywords of the C# language such as base, char, default, int, object, this, null and many others cannot be used as variable names.
  • 26. DECLARING VARIABLES The syntax for declaring variables in C# is as follows: <data type> <identifier> [= <initialization>]; When you declare a variable, you perform the following steps: • specify its type (such as int); • specify its name (identifier, such as age); • specify an initial value (optional).
  • 27. Initialization of Variables • Assigning a value to a variable is the act of providing a value that must be stored in the variable. This operation is performed by the assignment operator "=". The word initialization in programming means specifying an initial value.
  • 28. Example: // Declare and initialize some variables byte centuries = 20; ushort years = 2000; decimal decimalPI = 3.141592653589793238m; bool isEmpty = true; char ch = 'a'; string firstName = "John"; ch = (char)5; char secondChar; // Here we use an already initialized variable and reassign it secondChar = ch;
  • 29. OPERATORS Operators allows processing of data. They take as an input one or more operands and return some value as a result. Operators in C# are special characters (such as "+", ".", "^", etc.) and they perform transformations on one, two or three operands. Operators in C# can be separated in several different categories: • Arithmetic operators – they are used to perform simple mathematical operations, this category involves the following operators: -, +, *, /, %, ++, -- • Assignment operators – allow assigning values to variables, , this category involves the following operators: =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
  • 30. • Comparison operators – allow comparison of two literals and/or variables, this category involves the following operators: ==, !=, >, =, <= • Logical operators – operators that work with Boolean data types and Boolean expressions, this category involves the following operators: &&, ||, !, • Type conversion operators – allow conversion of data from one type to another, this category involves the following operators: (type), as, is, typeof, sizeof
  • 31. Example: Arithmetic operators int squarePerimeter = 17; double squareSide = squarePerimeter / 4.0; double squareArea = squareSide * squareSide; Console.WriteLine(squareSide); // 4.25 Console.WriteLine(squareArea); // 18.0625 int a = 5; int b = 4; Console.WriteLine(a + b); // 9 Console.WriteLine(a + (b++)); // 9 Console.WriteLine(a + b); // 10 Console.WriteLine(a + (++b)); // 11 Console.WriteLine(a + b); // 11 Console.WriteLine(14 / a); // 2 Console.WriteLine(14 % a); // 4
  • 32. Example: Logical Operators bool a = true; bool b = false; Console.WriteLine(a && b); // False Console.WriteLine(a || b); // True Console.WriteLine(!b); // True Console.WriteLine(b || true); // True Console.WriteLine((5 > 7) ^ (a == b)); // False
  • 33. Example: Comparison Operators int x = 10, y = 5; Console.WriteLine("x > y : " + (x > y)); // True Console.WriteLine("x < y : " + (x < y)); // False Console.WriteLine("x >= y : " + (x >= y)); // True Console.WriteLine("x <= y : " + (x <= y)); // False Console.WriteLine("x == y : " + (x == y)); // False Console.WriteLine("x != y : " + (x != y)); // True
  • 34. Example: Assignment Operators int x = 6; int y = 4; Console.WriteLine(y *= 2); // 8 int z = y = 3; // y=3 and z=3 Console.WriteLine(z); // 3 Console.WriteLine(x += 4); // 10 Console.WriteLine(x /= 2); // 5
  • 35. Example: Type Conversion Operators int myInt = 5; Console.WriteLine(myInt); // 5 long myLong = myInt; Console.WriteLine(myLong); // 5 Console.WriteLine(myLong + myInt); // 10
  • 36. WHAT IS THE CONSOLE? The Console is a window of the operating system through which users can interact with system programs of the operating system or with other console applications. The interaction consists of text input from the standard input (usually keyboard) or text display on the standard output. These actions are also known as input-output operations. The text written on the console brings some information and is a sequence of characters sent by one or more programs.
  • 37. WHEN TO USE THE CONSOLE? In some cases the console remains an irreplaceable tool for communication with the user. One of these cases is when writing small and simple programs where it is necessary to focus the attention on the specific problem to be solved, rather than the elegant representation of the result to the user. Then a simple solution is used for entering or printing a result, such as input/output console. Another use case is when we want to test a small piece of code for a larger application. Due to simplicity of the operation of the console application we can isolate this part of the code easily and comfortably without having to go through a complex user interface and a number of screens to get to the desired code for testing.
  • 38. CONSOLE.OUT STREAM System.Console class has different properties and methods which are used to read and display text on the console as well as its formatting. Among them there are three properties that make impression and they are related toinput/output, namely the Console.Out, Console.In and Console.Error. They provide access to the standard streams for printing on the console, for reading from the console and to the error messages reporting stream accordingly.
  • 39. Example: // Print String Console.WriteLine("Hello World"); // Print int Console.WriteLine(5); // Print double Console.WriteLine(3.14159265358979);
  • 40. READING THROUGH CONSOLE.READLINE() The method Console.ReadLine() provides great convenience for reading from console. How does it work? When this method is invoked, the program waits for an input from the console. The user enters some string on the console and presses the [Enter] key. At this moment the console understands that the user has finished entering and reads the string. The method Console.ReadLine() returns as result the string entered by the user.
  • 41. Example: Console.Write("Please enter your first name: "); string firstName = Console.ReadLine(); Console.Write("Please enter your last name: "); string lastName = Console.ReadLine(); Console.WriteLine("Hello, {0} {1}!", firstName, lastName); // Output: Please enter your first name: My // Please enter your last name: Name //Hello, My Name!
  • 42. READING NUMBERS Reading numbers from the console in C# is not done directly. In order to read a number we should have previously read the input as a string (using ReadLine()) and then convert this string to a number. This process is called parsing.
  • 43. Example: class RedingNumbers { static void Main(string[] args) { Console.Write("a = "); int a = int.Parse(Console.ReadLine()); Console.Write("b = "); int b = int.Parse(Console.ReadLine()); Console.WriteLine("{0} + {1} = {2}", a, b, a + b); Console.WriteLine("{0} * {1} = {2}", a, b, a * b); Console.Write("f = "); double f = double.Parse(Console.ReadLine()); Console.WriteLine("{0} * {1} / {2} = {3}", a, b, f, a * b / f); } }
  • 44. READING BY CONSOLE.READKEY() The method Console.ReadKey() waits for key pressing on the console and reads its character equivalent without the need of pressing [Enter]. The result of invoking ReadKey() is information about the pressed key (or more accurately a key combination) as an object of type ConsoleKeyInfo. Example: ConsoleKeyInfo key = Console.ReadKey(); Console.WriteLine("Character entered: " + key.KeyChar);
  • 45. CONSOLE INPUT AND OUTPUT EXAMPLE Console.WriteLine("This program calculates " + "the area of a rectangle or a triangle"); Console.WriteLine("Enter a and b (for rectangle) " + "or a and h (for triangle): "); int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine()); Console.WriteLine("Enter 1 for a rectangle or " + "2 for a triangle: "); int choice = int.Parse(Console.ReadLine()); double area = (double)(a * b) / choice; Console.WriteLine("The area of your figure is " + area); Console.ReadLine();
  • 46. CONDITIONAL STATEMENT "IF" AND "IF- ELSE" Because of conditional statements a program can behave differently based on a defined condition checked during the execution of the statement.
  • 47. Conditional Statement "if“ Includes: if-clause, Boolean expression and body of the conditional statement. The Boolean expression can be a Boolean variable or Boolean logical expression. Boolean expressions cannot be integer. The expression in the brackets which follows the keyword if must return the Boolean value true or false. If the expression is calculated to the value true, then the body of a conditional statement is executed. If the result is false, then the operators in the body will be skipped.
  • 48. Example: Console.WriteLine("Enter two numbers."); Console.Write("Enter first number: "); int firstNumber = int.Parse(Console.ReadLine()); Console.Write("Enter second number: "); int secondNumber = int.Parse(Console.ReadLine()); int biggerNumber = firstNumber; if (secondNumber > firstNumber) { biggerNumber = secondNumber; } Console.WriteLine("The bigger number is: {0}", biggerNumber);
  • 49. Conditional Statement "if-else“ The format of the if-else structure consists of the reserved word if, Boolean expression, body of a conditional statement, reserved word else and else-body statement. The body of else-structure may consist of one or more operators, enclosed in curly brackets, same as the body of a conditional statement. This statement works as follows: the expression in the brackets (a Boolean expression) is calculated. The calculation result must be Boolean – true or false. Depending on the result there are two possible outcomes. If the Boolean expression is calculated to true, the body of the conditional statement is executed and the else-statement is omitted and its operators do not execute. Otherwise, if the Boolean expression is calculated to false, the else-body is executed, the main body of the conditional statement is omitted and the operators in it are not executed.
  • 50. Example: int first = 5; int second = 3; if (first == second) { Console.WriteLine("These two numbers are equal."); } else { if (first > second) { Console.WriteLine("The first number is greater."); } else { Console.WriteLine("The second number is greater."); } }
  • 51. Conditional Statement "switch-case“ The structure switch-case chooses which part of the programming code to execute based on the calculated value of a certain expression (most often of integer type). The selector is an expression returning a resulting value that can be compared, like a number or string. The switch operator compares the result of the selector to every value listed in the case labels in the body of the switch structure. If a match is found in a case label, the corresponding structure is executed. If no match is found, the default statement is executed (when such exists). The value of the selector must be calculated before comparing it to the values inside the switch structure. The labels should not have repeating values, they must be unique.
  • 52. Example: int number = 6; switch (number) { case 1: case 4: case 6: case 8: case 10: Console.WriteLine("The number is not prime!"); break; case 2: case 3: case 5: case 7: Console.WriteLine("The number is prime!"); break; default: Console.WriteLine("Unknown number!"); break; }