visula c# programming lecture 2

23
Introduction to Visual Programming Lecture #2: C# Program Structure identifiers, variables, inc & dec

Upload: abu-bakr-ashraf

Post on 22-May-2015

312 views

Category:

Education


0 download

DESCRIPTION

lecture 2

TRANSCRIPT

Page 1: Visula C# Programming Lecture 2

Introduction to Visual Programming

Lecture #2:

C# Program Structure identifiers, variables, inc & dec

Page 2: Visula C# Programming Lecture 2

2

C# Program Structure

Program specifications (optional)

//==========================================================// // File: HelloWorld.cs CS112 Assignment 00 // // Author: Muhammad Adeel Abid Email: [email protected] // // Classes: HelloWorld // -------------------- // This program prints a string called "Hello, World!”////==========================================================

Library imports

using System;

Class and namespace definitions

class HelloWorld{ static void Main(string[] args) { Console.WriteLine(“Hello, World!”); }}

Page 3: Visula C# Programming Lecture 2

3

Comments Comments

Comments are ignored by the compiler: used only for human readers (i.e., inline documentation)

Two types of comments• Single-line comments use //… // this comment runs to the end of the line

• Multi-lines comments use /* … */

/* this comment runs to the terminating symbol, even across line breaks */

Page 4: Visula C# Programming Lecture 2

4

Identifiers

Identifiers are the words that a programmer uses in a program

An identifier can be made up of letters, digits, and the underscore character

They cannot begin with a digit C# is case sensitive, therefore args and Args are

different identifiers Sometimes we choose identifiers

ourselves when writing a program (such as HelloWorld)

Sometimes we are using another programmer's code, so we use the identifiers that they chose (such as WriteLine)

using System;class HelloWorld{ static void Main(string[] args) { Console.WriteLine(“Hello World!”); }}

Page 5: Visula C# Programming Lecture 2

5

Identifiers: Keywords

Often we use special identifiers called keywords that already have a predefined meaning in the language Example: class

A keyword cannot be used in any other wayC# Keywords

abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach get goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed set short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using value virtual void volatile while

All C# keywords are lowercase!

Page 6: Visula C# Programming Lecture 2

6

C# Program Structure: Class

class HelloWorld

{

}

// comments about the class

class headerclass header

class bodyclass body

Comments can be added almost anywhereComments can be added almost anywhere

Page 7: Visula C# Programming Lecture 2

7

C# Classes

Each class name is an identifier• Can contain letters, digits, and underscores (_)• Cannot start with digits• Can start with the at symbol (@)

Convention: Class names are capitalized, with each additional English word capitalized as well (e.g., MyFirstProgram )

Class bodies start with a left brace ({) Class bodies end with a right brace (})

Page 8: Visula C# Programming Lecture 2

8

C# Program Structure: Method

class HelloWorld

{

}

// comments about the class

static void Main (string[] args)

{

}

// comments about the method

Console.Write(“Hello World!”);Console.WriteLine(“This is from CS112!”);

Page 9: Visula C# Programming Lecture 2

9

Console Application vs. Window Application

Console Application No visual component Only text input and output Run under Command Prompt or DOS Prompt

Window Application Forms with many different input and output types Contains Graphical User Interfaces (GUI) GUIs make the input and output more user friendly! Message boxes

• Within the System.Windows.Forms namespace• Used to prompt or display information to the user

Page 10: Visula C# Programming Lecture 2

10

Variables A variable is a typed name for a location in memory A variable must be declared, specifying the variable's

name and the type of information that will be held in it

int numberOfStudents;…

int average, max;

data type variable name

int total;…

Which ones are valid variable names?myBigVar VAR1 _test @test99bottles namespace It’s-all-over

9200920092049204

92089208921292129216921692209220922492249228922892329232

numberOfStudents:

average: max:

total:

Page 11: Visula C# Programming Lecture 2

11

Assignment

An assignment statement changes the value of a variable The assignment operator is the = sign

total = 55;

You can only assign a value to a variable that is consistent with the variable's declared type (more later)

You can declare and assign initial value to a variable at the same time, e.g., int total = 55;

The value on the right is stored in the variable on the left The value that was in total is overwritten

int total;…

Page 12: Visula C# Programming Lecture 2

12

Example

static void Main(string[] args) { int total;

total = 15; System.Console.Write(“total = “); System.Console.WriteLine(total);

total = 55 + 5; System.Console.Write(“total = “); System.Console.WriteLine(total); }

Page 13: Visula C# Programming Lecture 2

13

Constants

A constant is similar to a variable except that it holds one value for its entire existence

The compiler will issue an error if you try to change a constant

In C#, we use the constant modifier to declare a constant

constant int numberOfStudents = 42;

Why constants? give names to otherwise unclear literal values facilitate changes to the code prevent inadvertent errors

Page 14: Visula C# Programming Lecture 2

14

C# Data Types

There are 15 data types in C# Eight of them represent integers:

byte, sbyte, short, ushort, int, uint, long,ulong Two of them represent floating point numbers

float, double One of them represents decimals:

decimal One of them represents boolean values:

bool One of them represents characters:

char One of them represents strings:

string One of them represents objects:

object

Page 15: Visula C# Programming Lecture 2

15

Numeric Data Types The difference between the various numeric types is

their size, and therefore the values they can store:Range

0 - 255-128 - 127

-32,768 - 327670 - 65537

-2,147,483,648 – 2,147,483,6470 – 4,294,967,295

-91018 to 91018

0 – 1.81019

1.010-28; 7.91028 with 28-29 significant digits

1.510-45; 3.41038 with 7 significant digits5.010-324; 1.710308 with 15-16 significant digits

Question: you need a variable to represent world population. Which type do you use?

Type

bytesbyteshortushortintuintlongulong

decimal

floatdouble

Storage

8 bits8 bits16 bits16 bits32 bits32 bits64 bits64 bits

128 bits

32 bits64 bits

Page 16: Visula C# Programming Lecture 2

16

Examples of Numeric Variablesint x = 1;

short y = 10;

float pi = 3.14f; // f denotes float

float f3 = 7E-02f; // 0.07

double d1 = 7E-100;

// use m to denote a decimal

decimal microsoftStockPrice = 28.38m;

Example: TestNumeric.cs

Page 17: Visula C# Programming Lecture 2

17

Boolean

A bool value represents a true or false condition

A boolean can also be used to represent any two states, such as a light bulb being on or off

The reserved words true and false are the only valid values for a boolean type

bool doAgain = true;

Page 18: Visula C# Programming Lecture 2

18

Characters

A char is a single character from the a character set A character set is an ordered list of characters; each

character is given a unique number C# uses the Unicode character set, a superset of ASCII

Uses sixteen bits per character, allowing for 65,536 unique characters

It is an international character set, containing symbols and characters from many languages

Code chart can be found at:http://www.unicode.org/charts/

Character literals are represented in a program by delimiting with single quotes, e.g.,

'a‘ 'X‘ '7' '$‘ ',‘

char response = ‘Y’;

Page 19: Visula C# Programming Lecture 2

19

Common Escape Sequences

Escape sequence Description \n Newline. Position the screen cursor to the beginning of the

next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor to the beginning

of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the previous characters output on that line.

\’ Used to print a single quote \\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double quote (") character.

Page 20: Visula C# Programming Lecture 2

20

string

A string represents a sequence of characters, e.g.,string message = “Hello World”;

Page 21: Visula C# Programming Lecture 2

21

Data Input

Console.ReadLine() Used to get a value from the user input Example

string myString = Console.ReadLine();

Convert from string to the correct data type Int32.Parse()

• Used to convert a string argument to an integer• Allows math to be preformed once the string is converted• Example:

string myString = “1023”; int myInt = Int32.Parse( myString );

Double.Parse() //for double type variable Single.Parse() //for float type variable

Page 22: Visula C# Programming Lecture 2

22

Sample Input //for String String s; Console.Write("Enter a string ="); s = Console.ReadLine(); Console.WriteLine("You enter =" + s); //------------------------------------ //for int int a; Console.Write("Enter an integer ="); a = Int32.Parse(Console.ReadLine()); Console.WriteLine("You enter =" + a); //------------------------------------ //for float float flt; Console.Write("Enter float value ="); flt = Single.Parse(Console.ReadLine()); Console.WriteLine("You enter =" + flt); //------------------------------------ //for double double dbl; Console.Write("Enter Double type value ="); dbl = Double.Parse(Console.ReadLine()); Console.WriteLine("You enter =" + dbl);

Page 23: Visula C# Programming Lecture 2

23

Increment and Decrement

++ is used to denote IncrementPrefix increment(++a)Postfix increment(a++)

-- is used to denote DecrementPrefix decrement(--a)Postfix decrement(a--)