Docsity

C# Programming: Syntax, I/O, Conditions, Loops and Debugging, Lecture notes of Computer Science

Partial preview of the text

Download C# Programming: Syntax, I/O, Conditions, Loops and Debugging and more Lecture notes Computer Science in PDF only on Docsity!

Basic Syntax

Basic Syntax , I/O, Conditions, Loops and Debugging

  • Introduction and Basic Syntax
  • Input / Output
  • Comparison operators
  • The if-else / Switch-Case Statement
  • Logical Operators
  • Loops
  • Debugging and Troubleshooting Table of Contents 2
  • C# is modern, flexible, general-purpose

programming language

  • Object-oriented by nature, statically-typed, compiled
  • Runs on .NET Framework / .NET Core C# โ€“ Introduction 4 static void Main() { //Source code }

Program

starting

point

  • Visual Studio (VS) is powerful IDE for C#
  • Create a

console

application

Using Visual Studio 5

  • Defining and Initializing variables
  • Example: Declaring Variables 7 {data type / var} {variable name} = {value}; int number = 5; Data type Variable name Variable value

CONSOLE I/O

Reading from and Writing to the Console 8

  • Console.ReadLine() returns a string
  • Convert the string to number by parsing: Converting Input from the Console 10 string name = Console.ReadLine(); int age = int.Parse(Console.ReadLine()); double salary = double.Parse(Console.ReadLine()); bool isHungry = bool.Parse(Console.ReadLine());
  • We can print to the console, using the Console class
  • Use the System namespace to access System.Console

class

  • Writing output to the console:
    • Console.Write()
    • Console.WriteLine() Printing to the Console 11 Console.Write("Hi, "); Console.WriteLine("John!"); // Hi, John!
  • D โ€“ format number to certain digits with leading zeros
  • F โ€“ format floating point number with certain digits after the decimal point
  • Examples: Formatting Numbers in Placeholders double grade = 5.5334; int percentage = 55; Console.WriteLine("{0:F2}", grade); // 5. Console.WriteLine("{0:D3}", percentage); // 055

โ–ช Using string interpolation to print on the console โ–ช Examples: Using String Interpolation string name = "George"; int age = 5; Console.WriteLine($"Name: {name}, Age: {age}"); //Name: George, Age 5 Put $ in front of the string to use string interpolation

COMPARISON OPERATORS

Comparison Operators 17

Operator Notation in C#

Equals ==

Not Equals !=

Greater Than >

Greater Than or Equals >=

Less Than <

Less Than or Equals <=

THE IF-ELSE STATEMENT

Implementing Control-Flow Logic

  • The most simple conditional statement
    • Test for a condition
  • Example: Take as an input a grade and check if the student has passed the exam (grade >= 3.00) The If Statement 20 double grade = double.Parse(Console.ReadLine()); if (grade >= 3.00) { Console.WriteLine("Passed!"); } In C# the opening bracket stays on a new line