• No results found

Lecture 2: C# Programming Basic syntax

N/A
N/A
Protected

Academic year: 2020

Share "Lecture 2: C# Programming Basic syntax"

Copied!
43
0
0

Loading.... (view fulltext now)

Full text

(1)

Lecture 2: C#

Programming Basic syntax

(2)

Creating, Compiling, and Running

Your First C# Program

using System; class Example {

static void Main() {

Console.WriteLine("C# gives you programming power."); }

(3)

Comments

C# supports three types of comments,

⚫ // single line comment

⚫ /* multiple line comments */

⚫ The third type of comment supported by C# is a

(4)

Using System

Program is using the System namespace.

A namespace defines a declarative region.

⚫ A namespace provides a way to keep one set of names

separate from another.

⚫ Names declared in one namespace will not conflict with

(5)

Static void Main

All C# applications begin execution by calling Main( ).

A method that is modified by static can be called before

an object of its class has been created.

This is necessary because Main( ) is called at program

startup.

The keyword void indicates that Main( ) does not return a

(6)

WriteLine( )

WriteLine( ) displays the string that is passed to it.

Information that is passed to a method is called an argument.

In addition to strings, WriteLine( ) can be used to display other types of information, such as numeric data.

The Write( ) method is just like WriteLine( ), except that it does not output a new line after each call.

The line begins with Console, which is the name of a predefined class that supports console I/O.

(7)

Algorithm For Calculating Area of a

Rectangle

:

⚫ Create a class “UseVars” or any name.(ﻢﺳا يأ)

⚫ Declare (ﻦﻠﻋأ) the variable – length , width.

⚫ Initialize (ﺔﺌﯿﮭﺗ) the variable – length,width.

⚫ Print the variable – length ,width.

⚫ Calculate (بﺎﺴﺣ) area of rectangle (ﻞﯿﻄﺘﺴﻤﻟا) .

⚫ Print the variable area.

LENGTH

(8)

Variables

⚫ Variable is a named memory location that can be assigned a value. class UseVars {

static void Main() {

int length; // this declares a variable

int width; // this declares another variable int area; // this is a third variable

length = 9;

Console.WriteLine("length contains " + length);

width = 7;

Console.WriteLine("width contains " + width);

area = length * width;

Console.Write("area contains length * width: "); Console.WriteLine(area);

} }

(9)

Output :

⚫ Length contains 9

⚫ Width contains 7

(10)

The double Data Type

⚫ To allow numbers with fractional components, C#

defines two floating-point types: float and double, which represent single- and double-precision

values, respectively.

To declare a variable of type double, use a statement

similar to that shown here:

double result;

(11)

Dynamic Initialization

⚫ C# allows variables to be initialized dynamically, using any expression valid at the point at which the variable is declared.

⚫ using System;

⚫ class DynInit {

⚫ static void Main() {

⚫ double radius = 4, height = 5;

⚫ // Dynamically initialize volume.

⚫ double volume = 3.1416 * radius * radius * height;

⚫ Console.WriteLine("Volume is " + volume);

⚫ }

(12)

Operators

⚫ Arithmetic operators.

⚫ Relational Operators.

⚫ Bitwise Operators.

(13)

Arithmetic Operators

Operator Operation

+ Addition

Subtraction (also unary minus)

* Multiplication

/ Division

% Modulus

++ Increment

(14)

% Operator

⚫ using System;

⚫ class ModDemo {

⚫ static void Main() {

⚫ int iresult, irem;

⚫ double dresult, drem;

⚫ iresult = 10 / 3;

⚫ irem = 10 % 3;

⚫ dresult = 10.0 / 3.0;

⚫ drem = 10.0 % 3.0;

⚫ Console.WriteLine("Result and remainder of 10 / 3: " +

⚫ iresult + " " + irem);

⚫ Console.WriteLine("Result and remainder of 10.0 / 3.0: " +

⚫ dresult + " " + drem);

⚫ }

(15)

⚫ 3 (quotient)

⚫ 3 | 10

⚫ 9

⚫ 1 (remainder)

⚫ The output from the program is shown here:

⚫ Result and remainder of 10 / 3: 3 1

⚫ Result and remainder of 10.0 / 3.0: 3.33333333333333 1

⚫ As you can see, the % yields a remainder of 1 for both

(16)

Increment and Decrement

⚫ X = x + 1 is same as x++ ⚫ X= x – 1 is same as --X ⚫ x = 10; ⚫ y = ++x; ans : y =? ⚫ X = 10;

⚫ y = x++; ans : y=? and x = ?

⚫ x = 10; y = 2;

⚫ z = x++ - (x * y);

(17)

Relational Operators

⚫ < Less than

⚫ <= Less than or equal to

⚫ > Greater than

⚫ >= Greater than or equal to

⚫ = = Equal to

(18)

Bitwise Operator

⚫ & - AND

⚫ | - OR

⚫ ^ - XOR (exclusive OR)

⚫ || - Short-circuit OR

⚫ && - Short-circuit AND

(19)

Table for Bitwise Operators

P Q P&Q P|Q p ^ q ~P

false false false false false true false true false true true true true false false true true false true true true true false false

(20)

Assignment Operator

⚫ Variable op = expression

The operator pair += tells the compiler to assign to x the

value of x plus 10.

⚫ += –= *= /=

⚫ %= &= |= ^=

⚫ X += 10; is same as x=x+10;

(21)

The if Statement

it is syntactically similar to the if statements in C, C++,

and Java. Its simplest form is shown

⚫ here:

if(condition) statement;

For Example

⚫ if(10 < 11) Console.WriteLine("10 is less than 11");

⚫ In this case, since 10 is less than 11, the conditional

(22)

The for Loop

for(initialization; condition; iteration)

statement;

⚫ using System;

⚫ class ForDemo {

⚫ static void Main() {

⚫ int count;

⚫ Console.WriteLine("Counting from 0 to 4:");

⚫ for(count = 0; count < 5; count = count+1)

⚫ Console.WriteLine(" count is " + count);

⚫ Console.WriteLine("Done!"); ⚫ } ⚫ } Output Counting from 0 to 4: count is 0 count is 1 count is 2 count is 3 count is 4 Done!

(23)

While Loops

⚫ Condition is tested at the top of the Loop : If condition not satisfied then the loop will not be executed even once.

⚫ using System;

⚫ class WhileDemo {

⚫ static void Main() {

⚫ char ch;

⚫ // Print the alphabet using a while loop.

⚫ ch = 'a'; ⚫ while(ch <= 'z') { ⚫ Console.Write(ch); ⚫ ch++; ⚫ } ⚫ } ⚫ }

(24)

Do while Loops

⚫ Condition is tested at the bottom of the Loop –Do while will always execute atleast once.

⚫ using System;

⚫ class DWDemo {

⚫ static void Main() {

⚫ char ch;

⚫ do {

⚫ Console.Write("Press a key followed by ENTER: ");

⚫ ch = (char) Console.Read(); // read a keypress

⚫ } while(ch != 'q');

⚫ }

(25)

Usage of Break Statement

⚫ using System;

⚫ class Break2 {

⚫ static void Main() {

⚫ char ch; ⚫ for( ; ; ) { ⚫ ch = (char) Console.Read(); ⚫ if(ch == 'q') break; ⚫ } ⚫ Console.WriteLine("You pressed q!"); ⚫ } ⚫ }

(26)

Break – Comes out of Inner Loop

⚫ using System;

⚫ class Break3 {

⚫ static void Main() {

⚫ for(int i=0; i<3; i++) {

⚫ Console.WriteLine("Outer loop count: " + i);

⚫ Console.Write(" Inner loop count: ");

⚫ int t = 0; ⚫ while(t < 100) { ⚫ if(t == 10) break; ⚫ Console.Write(t + " "); ⚫ t++; ⚫ } ⚫ Console.WriteLine(); ⚫ } ⚫ Console.WriteLine("Loops complete."); ⚫ } ⚫ }

(27)

⚫ Outer loop count: 0

⚫ Inner loop count: 0 1 2 3 4 5 6 7 8 9

⚫ Outer loop count: 1

⚫ Inner loop count: 0 1 2 3 4 5 6 7 8 9

⚫ Outer loop count: 2

⚫ Inner loop count: 0 1 2 3 4 5 6 7 8 9

(28)

Use continue

⚫ using System;

⚫ class ContDemo {

⚫ static void Main() {

⚫ int i;

⚫ // Print even numbers between 0 and 100.

⚫ for(i = 0; i<=100; i++) {

⚫ // Iterate if i is odd. ⚫ if((i%2) != 0) continue; ⚫ Console.WriteLine(i); ⚫ } ⚫ } ⚫ }

(29)

The C# Keywords

⚫ The reserved keywords cannot be used as names for variables, classes, or methods.

(30)

Data Types

⚫ Integers

⚫ C# defines nine integer types:

(31)
(32)
(33)

The Scope and Lifetime of

Variables

Difference between Scope and Lifetime?

Scope: It defines the visibility/accessibility of the variable

in a program.

⚫ Local variable - the scope is local to that function.

⚫ Static global variable - scope is limited to that file only.

(34)

Lifetime of a Variable :

⚫ It is the duration of time for which the variable holds the

value during the execution of a program.

⚫ Local variable - the lifetime is within the functional block

in which it is declared. The memory allocated when function starts and deallocated when it terminates.

⚫ static variable - the life time will be the entire execution of

the program. value persists even between function calls.

⚫ Global variable - the life time will be the entire execution

(35)
(36)

Operators

An operator is a symbol that tells the compiler

to perform a specific mathematical or logical manipulation. C# has four general classes of

(37)

Logical Operators

Relational Operators

(38)
(39)

Operator Precedence

R -> L

R -> L R-> L

(40)

Inputting Characters from the

Keyboard

To read a character from the keyboard, call Console.Read( ). using System;

class KbIn {

static void Main() { char ch;

Console.Write("Press a key followed by ENTER: "); // Read a key from the keyboard.

ch = (char) Console.Read();

Console.WriteLine("Your key is: " + ch); }

}

output

Here is a sample run:

Press a key followed by ENTER: t Your key is: t

(41)

To check if the character is same as

assigned character.

⚫ Create a class .

⚫ Declare the variable answer of type char .

⚫ Initialise the variable answer= ‘K’.

⚫ Print message “ Guess a letter between A and Z”

⚫ Read a character from user . Store it in ch.

⚫ If (answer = ch) then print “Right”

(42)

The switch Statement

The general form of the switch statement is switch(expression) { case constant1: statement sequence break; case constant2: statement sequence break; case constant3: statement sequence break; . . . default: statement sequence break; }

(43)

Example

using System;

class VowelsAndConsonants { static void Main() {

char ch; Console.Write("Enter a letter: "); ch = (char) Console.Read(); switch(ch) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'y': Console.WriteLine("Letter is a vowel."); break; default: Console.WriteLine("Letter is a consonant."); break; } } }

Figure

Table for Bitwise Operators

References

Related documents

Scarabaeus megaparvulus has a well-developed transverse frontal carina; a more densely punctate pronotum without sagittal line and with a basal medial lobe; exposed scutellum;

Head prognathous, broad, as wide as anterior border of pronotum; slightly tu- mid, posterior border gently and broadly concave; compound eyes relatively small, separated from

First desig- nated in 2014, SPWS connects a patchwork of contiguous protected areas including Xe Pian National Protected Area, Nam Ghong Provincial Protected Area, Dong

Injection Quantity Control Cylinder Injection Quantity Correction Pre-Injection Main Injection Crankshaft Angle Inject on Rate Inject on Pressure 1 3 4

The accumulation of the spatial discretization error in every time step, identified above as the reason for suboptimality of theoretical results, is usually avoided in standard FEMs

Switch case value of if there is optional in addition to choose a constant or skim through all in select which statement inside other syntax of switch case statement can

Like the IF statement the CASE statement selects one sequence of statements to execute However to select the sequence the CASE statement uses a selector rather than multiple

Furthermore, researchers suggest that the expression of PTSD symptoms in women who have experienced childhood victimization may differ from those who have experienced other types