SlideShare una empresa de Scribd logo
1 de 27
Operators, Loops,
Conditional
statements in C#
Table of contents
• Operators
 Arithmetic
 Conditional
 Logic
 Binary
 Operators Priority
• Conditional statements
 if
 if else
 goto
 switch
 break
 continue
Table of contents (1)
• Loops
 for
 while
 do while
 Foreach
• If we have time
 Arrays
 Strings
 Objects & structures
Operators in C#
Category Operators
Arithmetic + - * / % ++ --
Logical && || ^ !
Binary & | ^ ~ << >>
Comparison == != < > <= >=
Assignment = += -= *= /= %= &= |= ^= <<=
>>=
String concatenation +
Type conversion is as typeof
Other . [] () ?: new
Operators Precedence
Precedence Operators
Highest ()
++ -- (postfix) new typeof
++ -- (prefix) + - (unary) ! ~
* / %
+ -
<< >>
< > <= >= is as
== !=
&
Lower ^
Operators Precedence (2)
Precedence Operators
Higher |
&&
||
?:
Lowest = *= /= %= += -= <<= >>= &= ^= |=
 Parenthesis operator always has highest
precedence
 Note: prefer using parentheses, even when it
seems stupid to do so
Arithmetic Operators – Example
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(11 / 3); // 3
Arithmetic Operators – Example (2)
Console.WriteLine(11.0 / 3); // 3.666666667
Console.WriteLine(11 / 3.0); // 3.666666667
Console.WriteLine(11 % 3); // 2
Console.WriteLine(11 % -3); // 2
Console.WriteLine(-11 % 3); // -2
Console.WriteLine(1.5 / 0.0); // Infinity
Console.WriteLine(-1.5 / 0.0); // -Infinity
Console.WriteLine(0.0 / 0.0); // NaN
int x = 0;
Console.WriteLine(5 / x); // DivideByZeroException
Arithmetic Operators – Overflow Examples
int bigNum = 2000000000;
int bigSum = 2 * bigNum; // Integer overflow!
Console.WriteLine(bigSum); // -294967296
bigNum = Int32.MaxValue;
bigNum = bigNum + 1;
Console.WriteLine(bigNum); // -2147483648
checked
{
// This will cause OverflowException
bigSum = bigNum * 2;
}
The if Statement
• The most simple conditional statement
• Enables you to test for a condition
• Branch to different parts of the code depending on the result
• The simplest form of an if statement:
if (condition)
{
statements;
}
The if-else Statement
• More complex and useful conditional statement
• Executes one branch if the condition is true,
and another if it is false
• The simplest form of an if-else statement:
if (expression)
{
statement1;
}
else
{
statement2;
}
Nested if Statements
• if and if-else statements can be nested, i.e. used inside another if or else
statement
• Every else corresponds to its closest preceding if
if (expression)
{
if (expression)
{
statement;
}
else
{
statement;
}
}
else
statement;
Multiple if-else-if-else-…
• Sometimes we need to use another if-construction in the else block
 Thus else if can be used:
int ch = 'X';
if (ch == 'A' || ch == 'a')
{
Console.WriteLine("Vowel [ei]");
}
else if (ch == 'E' || ch == 'e')
{
Console.WriteLine("Vowel [i:]");
}
else if …
else …
The switch-case Statement
• Selects for execution a statement from a list
depending on the value of the switch
expression
switch (day)
{
case 1: Console.WriteLine("Monday"); break;
case 2: Console.WriteLine("Tuesday"); break;
case 3: Console.WriteLine("Wednesday"); break;
case 4: Console.WriteLine("Thursday"); break;
case 5: Console.WriteLine("Friday"); break;
case 6: Console.WriteLine("Saturday"); break;
case 7: Console.WriteLine("Sunday"); break;
default: Console.WriteLine("Error!"); break;
}
Using switch: Rules
• Variables types like string, enum and integral
types can be used for switch expression
• The value null is permitted as a case label
constant
• The keyword break exits the switch statement
• "No fall through" rule – you are obligated to use
break after each case
• Multiple labels that correspond to the same
statement are permitted
What Is Loop?
• A loop is a control statement that allows repeating execution of a block of
statements
 May execute a code block fixed number of times
 May execute a code block while given condition holds
 May execute a code block for each member of a collection
• Loops that never end are called an infinite loops
While Loop
• The simplest and most frequently used loop
• The repeat condition
 Returns a boolean result of true or false
 Also called loop condition
while (condition)
{
statements;
}
Prime Number – Example
• Checking whether a number is prime or not
Console.Write("Enter a positive integer number: ");
string consoleArgument=Console.ReadLine();
uint number = uint.Parse(consoleArgument);
uint divider = 2;
uint maxDivider = (uint) Math.Sqrt(number);
bool prime = true;
while (prime && (divider <= maxDivider))
{
if (number % divider == 0)
{
prime = false;
}
divider++;
}
Console.WriteLine("Prime? {0}", prime);
Do-While Loop
• Another loop structure is:
• The block of statements is repeated
 While the boolean loop condition holds
• The loop is executed at least once
do
{
statements;
}
while (condition);
For Loops
• The typical for loop syntax is:
• Consists of
 Initialization statement
 Boolean test expression
 Update statement
 Loop body block
for (initialization; test; update)
{
statements;
}
For Loops
• The typical foreach loop syntax is:
• Iterates over all elements of a collection
 The element is the loop variable that takes sequentially all collection values
 The collection can be list, array or other group of elements of the same type
foreach (Type element in collection)
{
statements;
}
Nested Loops
Using Loops Inside a Loop
C# Jump Statements
• Jump statements are:
 break, continue, goto
• How continue works?
 In while and do-while loops jumps to the test expression
 In for loops jumps to the update expression
• To exit an inner loop use break
• To exit outer loops use goto with a label
 Avoid using goto! (it is considered harmful)
Execersises
1. Read 2 numbers from the console and output the bigger.
2. Read a number from the console and output if it is even or odd.
3. Read 3 numbers from the console and order them in an ascending order.
4. Output all odd numbers from 1 to 20.
5. Read a number from the console and output its factorial.
6. Check if a number is prime.
7. Calculate the product of all numbers in the interval [N..M].(Tip:Check
the input of the program.).
Пресметнете резултата от умножението на всички числа в интервала
[N:M]
8. Calculate N raised to power M using for-loop.
9. Print a triangle like the one below:
1
1 2
1 2 3
…..
1 2 … 50
10. Въведете едно число и изкарайте с цифрите в обратен ред.
Questions?
Thank you
Vladislav Hadzhiyski
Email: Vladislav.Hadzhiyski@gmail.com

Más contenido relacionado

La actualidad más candente (17)

C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)
 
Loop c++
Loop c++Loop c++
Loop c++
 
java in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariyajava in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariya
 
C++ loop
C++ loop C++ loop
C++ loop
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorial
 
Program control statements in c#
Program control statements in c#Program control statements in c#
Program control statements in c#
 
Working of while loop
Working of while loopWorking of while loop
Working of while loop
 
Loop control in c++
Loop control in c++Loop control in c++
Loop control in c++
 
C++ control loops
C++ control loopsC++ control loops
C++ control loops
 
LISP:Loops In Lisp
LISP:Loops In LispLISP:Loops In Lisp
LISP:Loops In Lisp
 
Java control flow statements
Java control flow statementsJava control flow statements
Java control flow statements
 
Loops in c++ programming language
Loops in c++ programming language Loops in c++ programming language
Loops in c++ programming language
 
Java loops
Java loopsJava loops
Java loops
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Iteration
IterationIteration
Iteration
 
Loops c++
Loops c++Loops c++
Loops c++
 
Looping
LoopingLooping
Looping
 

Similar a Operators loops conditional and statements

Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constantsTAlha MAlik
 
07 control+structures
07 control+structures07 control+structures
07 control+structuresbaran19901990
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Rasan Samarasinghe
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loopsManzoor ALam
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingChaAstillas
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
 
C_BASICS FOR C PROGRAMMER WITH SRIVATHS P
C_BASICS FOR C PROGRAMMER WITH  SRIVATHS PC_BASICS FOR C PROGRAMMER WITH  SRIVATHS P
C_BASICS FOR C PROGRAMMER WITH SRIVATHS Pamankr1234am
 
System verilog control flow
System verilog control flowSystem verilog control flow
System verilog control flowPushpa Yakkala
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slidesluqman bawany
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxLikhil181
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operatorsraksharao
 
c++ Data Types and Selection
c++ Data Types and Selectionc++ Data Types and Selection
c++ Data Types and SelectionAhmed Nobi
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#Rohit Rao
 

Similar a Operators loops conditional and statements (20)

Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constants
 
8 statement level
8 statement level8 statement level
8 statement level
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
C language
C languageC language
C language
 
07 control+structures
07 control+structures07 control+structures
07 control+structures
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
C_BASICS FOR C PROGRAMMER WITH SRIVATHS P
C_BASICS FOR C PROGRAMMER WITH  SRIVATHS PC_BASICS FOR C PROGRAMMER WITH  SRIVATHS P
C_BASICS FOR C PROGRAMMER WITH SRIVATHS P
 
System verilog control flow
System verilog control flowSystem verilog control flow
System verilog control flow
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptx
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
Lesson 5
Lesson 5Lesson 5
Lesson 5
 
c++ Data Types and Selection
c++ Data Types and Selectionc++ Data Types and Selection
c++ Data Types and Selection
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 

Más de Vladislav Hadzhiyski

Más de Vladislav Hadzhiyski (7)

03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop
 
00 introduction presentation
00 introduction presentation00 introduction presentation
00 introduction presentation
 
01 c sharp_introduction
01 c sharp_introduction01 c sharp_introduction
01 c sharp_introduction
 
Mvc razor and working with data
Mvc razor and working with dataMvc razor and working with data
Mvc razor and working with data
 
ASP.NET MVC overview
ASP.NET MVC overviewASP.NET MVC overview
ASP.NET MVC overview
 
Web forms Overview Presentation
Web forms Overview PresentationWeb forms Overview Presentation
Web forms Overview Presentation
 
Introduction presentation
Introduction presentationIntroduction presentation
Introduction presentation
 

Último

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 

Último (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Operators loops conditional and statements

  • 2. Table of contents • Operators  Arithmetic  Conditional  Logic  Binary  Operators Priority • Conditional statements  if  if else  goto  switch  break  continue
  • 3. Table of contents (1) • Loops  for  while  do while  Foreach • If we have time  Arrays  Strings  Objects & structures
  • 4. Operators in C# Category Operators Arithmetic + - * / % ++ -- Logical && || ^ ! Binary & | ^ ~ << >> Comparison == != < > <= >= Assignment = += -= *= /= %= &= |= ^= <<= >>= String concatenation + Type conversion is as typeof Other . [] () ?: new
  • 5. Operators Precedence Precedence Operators Highest () ++ -- (postfix) new typeof ++ -- (prefix) + - (unary) ! ~ * / % + - << >> < > <= >= is as == != & Lower ^
  • 6. Operators Precedence (2) Precedence Operators Higher | && || ?: Lowest = *= /= %= += -= <<= >>= &= ^= |=  Parenthesis operator always has highest precedence  Note: prefer using parentheses, even when it seems stupid to do so
  • 7. Arithmetic Operators – Example 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(11 / 3); // 3
  • 8. Arithmetic Operators – Example (2) Console.WriteLine(11.0 / 3); // 3.666666667 Console.WriteLine(11 / 3.0); // 3.666666667 Console.WriteLine(11 % 3); // 2 Console.WriteLine(11 % -3); // 2 Console.WriteLine(-11 % 3); // -2 Console.WriteLine(1.5 / 0.0); // Infinity Console.WriteLine(-1.5 / 0.0); // -Infinity Console.WriteLine(0.0 / 0.0); // NaN int x = 0; Console.WriteLine(5 / x); // DivideByZeroException
  • 9. Arithmetic Operators – Overflow Examples int bigNum = 2000000000; int bigSum = 2 * bigNum; // Integer overflow! Console.WriteLine(bigSum); // -294967296 bigNum = Int32.MaxValue; bigNum = bigNum + 1; Console.WriteLine(bigNum); // -2147483648 checked { // This will cause OverflowException bigSum = bigNum * 2; }
  • 10. The if Statement • The most simple conditional statement • Enables you to test for a condition • Branch to different parts of the code depending on the result • The simplest form of an if statement: if (condition) { statements; }
  • 11. The if-else Statement • More complex and useful conditional statement • Executes one branch if the condition is true, and another if it is false • The simplest form of an if-else statement: if (expression) { statement1; } else { statement2; }
  • 12. Nested if Statements • if and if-else statements can be nested, i.e. used inside another if or else statement • Every else corresponds to its closest preceding if if (expression) { if (expression) { statement; } else { statement; } } else statement;
  • 13. Multiple if-else-if-else-… • Sometimes we need to use another if-construction in the else block  Thus else if can be used: int ch = 'X'; if (ch == 'A' || ch == 'a') { Console.WriteLine("Vowel [ei]"); } else if (ch == 'E' || ch == 'e') { Console.WriteLine("Vowel [i:]"); } else if … else …
  • 14. The switch-case Statement • Selects for execution a statement from a list depending on the value of the switch expression switch (day) { case 1: Console.WriteLine("Monday"); break; case 2: Console.WriteLine("Tuesday"); break; case 3: Console.WriteLine("Wednesday"); break; case 4: Console.WriteLine("Thursday"); break; case 5: Console.WriteLine("Friday"); break; case 6: Console.WriteLine("Saturday"); break; case 7: Console.WriteLine("Sunday"); break; default: Console.WriteLine("Error!"); break; }
  • 15. Using switch: Rules • Variables types like string, enum and integral types can be used for switch expression • The value null is permitted as a case label constant • The keyword break exits the switch statement • "No fall through" rule – you are obligated to use break after each case • Multiple labels that correspond to the same statement are permitted
  • 16. What Is Loop? • A loop is a control statement that allows repeating execution of a block of statements  May execute a code block fixed number of times  May execute a code block while given condition holds  May execute a code block for each member of a collection • Loops that never end are called an infinite loops
  • 17. While Loop • The simplest and most frequently used loop • The repeat condition  Returns a boolean result of true or false  Also called loop condition while (condition) { statements; }
  • 18. Prime Number – Example • Checking whether a number is prime or not Console.Write("Enter a positive integer number: "); string consoleArgument=Console.ReadLine(); uint number = uint.Parse(consoleArgument); uint divider = 2; uint maxDivider = (uint) Math.Sqrt(number); bool prime = true; while (prime && (divider <= maxDivider)) { if (number % divider == 0) { prime = false; } divider++; } Console.WriteLine("Prime? {0}", prime);
  • 19. Do-While Loop • Another loop structure is: • The block of statements is repeated  While the boolean loop condition holds • The loop is executed at least once do { statements; } while (condition);
  • 20. For Loops • The typical for loop syntax is: • Consists of  Initialization statement  Boolean test expression  Update statement  Loop body block for (initialization; test; update) { statements; }
  • 21. For Loops • The typical foreach loop syntax is: • Iterates over all elements of a collection  The element is the loop variable that takes sequentially all collection values  The collection can be list, array or other group of elements of the same type foreach (Type element in collection) { statements; }
  • 22. Nested Loops Using Loops Inside a Loop
  • 23. C# Jump Statements • Jump statements are:  break, continue, goto • How continue works?  In while and do-while loops jumps to the test expression  In for loops jumps to the update expression • To exit an inner loop use break • To exit outer loops use goto with a label  Avoid using goto! (it is considered harmful)
  • 24. Execersises 1. Read 2 numbers from the console and output the bigger. 2. Read a number from the console and output if it is even or odd. 3. Read 3 numbers from the console and order them in an ascending order. 4. Output all odd numbers from 1 to 20. 5. Read a number from the console and output its factorial. 6. Check if a number is prime. 7. Calculate the product of all numbers in the interval [N..M].(Tip:Check the input of the program.). Пресметнете резултата от умножението на всички числа в интервала [N:M]
  • 25. 8. Calculate N raised to power M using for-loop. 9. Print a triangle like the one below: 1 1 2 1 2 3 ….. 1 2 … 50 10. Въведете едно число и изкарайте с цифрите в обратен ред.
  • 27. Thank you Vladislav Hadzhiyski Email: Vladislav.Hadzhiyski@gmail.com

Notas del editor

  1. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*