39
Hazırlayan Advanced Computer Programming Yrd. Doç. Dr. Mehmet Fidan

Advanced Computer Programmingendustri.eskisehir.edu.tr/mfidan/BİL255/icerik/bil255_week2_2016.pdf · number, as defined by IEEE 754. For more information on IEEE 754, visit the IEEE

  • Upload
    others

  • View
    11

  • Download
    0

Embed Size (px)

Citation preview

Hazırlayan

Advanced Computer Programming

Yrd. Doç. Dr. Mehmet Fidan

Console Input and Output Functions

• Console Output Functions:

– Console.Write()

– Console.WriteLine()

Advanced Computer Programming

Console.Write()

C# program that uses Console.Write

using System;

class Program

{

static void Main()

{

Console.Write("One "); // <-- This writes the word.

Console.Write("Two "); // <-- This is on the same line.

Console.Write("Three"); // <-- Also on the same line.

Console.WriteLine(); // <-- This writes a newline.

Console.WriteLine("Four"); // <-- This is on the next line.

Console.Readline();

}

}

Advanced Computer Programming

Output

One Two ThreeFour

Console.Write()

•using System;•using System.Collections.Generic;•using System.Linq;•using System.Text;•

•namespace Example1•{• class Program• {•

• static void Main()• {• int num=2;• Console.Write("\nPrevious Value:\t{0}", num);• num++;• Console.Write("\nCurrent Value:\t{0}", num);•

• Console.WriteLine("\n\n\n----------------");• Console.Write("\nPrevious Value:\t{0}", num);• num--;• Console.Write("\nCurrent Value:\t{0}", num);• Console.ReadLine();• }• }•}

Advanced Computer Programming

Console.Writeline

• The Write () method outputs one or more values to the screen without a new line character.

• The WriteLine() always appends a new line character to the end of the string. this means any subsequent output will start on a new line.

Console.WriteLine()

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System;class Program{

static void Main(){

Console.Write("Box");Console.Write("Table");Console.Write("chair");Console.WriteLine();Console.WriteLine("desk");

Console.Readline();}

}

Console.WriteLine()

Single Output Printing

Console.Writeline()

• Multiple Output Printing

Console.WriteLine()

using System;

class Program

{

static void Main()

{

// Write an int with Console.WriteLine.

int valueInt = 4;

Console.WriteLine(valueInt);

// Write a string with the method.

string valueString = "Your string";

Console.WriteLine(valueString);

// Write a bool with the method.

bool valueBool = false;

Console.WriteLine(valueBool);

}

}

Output 4

Your string

False

Input Functions: Console.ReadLine

using System;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

string firstName = "John";

string lastName = "Doe";

Console.WriteLine("Name: " + firstName + " " + lastName);

Console.WriteLine("Please enter a new first name:");

firstName = Console.ReadLine();

Console.WriteLine("New name: " + firstName + " " + lastName);

Console.ReadLine();

}

}

}

Read, ReadLine, ReadKey

Read() Readline() ReadKey()

Accept the string value

and return integer

value.

Accept the string and

return String

Accept the character and

return Character

Console.Read

using System;

class Program

{

static void Main()

{

// This program accepts console input.

// ... When the enter key is pressed, the Read method returns the first time.

// ... Then, each call to Read accesses one further character from the input.

int result;

while ((result = Console.Read()) != 0)

{

Console.WriteLine("{0} = {1}", result, (char)result);

}

}

}

Convert Function for Integer Inputs

using System;

class Program

{

static void Main()

{

Console.WriteLine("How many students would you like to enter?");

int amount = Convert.ToInt32(Console.Read());

Console.WriteLine("{0} {1}", "amount equals", amount);

for (int i=0; i < amount; i++)

{

Console.WriteLine("Input the name of a student");

String StudentName = Console.ReadLine();

Console.WriteLine("the Students name is " + StudentName);

}

}

}

VALUES & VARIABLES

Advanced Computer Programming

Properties of variables:

Should have a type

Stores data

Case sensitive

Their names can not start with a number

Reserved keywords can not be used as variable names

VALUES & VARIABLES

Advanced Computer Programming

Keywords:

VALUES & VARIABLES

Advanced Computer Programming

How to define a variable:

int x = 3;

Type

Variable

Value

Semicolon: End of

statement

VALUES & VARIABLES

Advanced Computer Programming

How to define a variable:

int nInteger;

string sString;

int nInteger = 42;

string sString = "This is a string!";

int nInteger;

string sString;

...

nInteger = 42;

sString = "This is a string!";

Double quotes

represents a string

VARIABLE TYPES

Advanced Computer Programming

The Boolean Types:

Boolean types are declared using the keyword, bool. They have two values: true or false. In other

languages, such as C and C++, boolean conditions can be satisfied where 0 means false and

anything else means true. However, in C# the only values that satisfy a boolean condition is true

and false, which are official keywords.

using System;

class Booleans{

public static void Main(){

bool content = true;bool noContent = false;

Console.WriteLine("It is {0} that C# Station provides C# programming language content.", content);Console.WriteLine("The statement above is not {0}.", noContent);

}}

VARIABLE TYPES

Advanced Computer Programming

Integral Types:

In C#, an integral is a category of types. For anyone confused because the word Integral sounds like amathematical term, from the perspective of C# programming, these are actually defined as Integral typesin the C# programming language specification. They are whole numbers, either signed or unsigned, and thechar type. The char type is a Unicode character, as defined by the Unicode Standard. For more information,visit The Unicode Home Page.

Type Size (in bits) Rangesbyte 8 -128 to 127byte 8 0 to 255short 16 -32768 to 32767ushort 16 0 to 65535int 32 -2147483648 to 2147483647uint 32 0 to 4294967295long 64 -9223372036854775808 to 922337203685477580ulong 64 0 to 18446744073709551615char 16 0 to 65535

VARIABLE TYPES

Advanced Computer Programming

Integral Types:

In C#, an integral is a category of types. For anyone confused because the word Integral sounds like amathematical term, from the perspective of C# programming, these are actually defined as Integral typesin the C# programming language specification. They are whole numbers, either signed or unsigned, and thechar type. The char type is a Unicode character, as defined by the Unicode Standard. For more information,visit The Unicode Home Page.

short 2 byte

short sval = -12;

ushort 2 bytes

ushort sval= 12;

int 4 bytes

int nval = -12500;

uint 4 bytes

uint nval = 12500;

long 8 bytes

long lVal = -548444101;

ulong 8 bytes

ulong lVal = 548444101;

VARIABLE TYPES

Advanced Computer Programming

Floating Point and Decimal Types:

A C# floating point type is either a float or double. They are used any time you need to represent a realnumber, as defined by IEEE 754. For more information on IEEE 754, visit the IEEE Web Site. Decimal typesshould be used when representing financial or money values.

Type Size (in bits) precision Rangefloat 32 7 digits 1.5 x 10-45 to 3.4 x 1038

double 64 15-16 digits 5.0 x 10-324 to 1.7 x 10308

decimal 128 28-29 decimal places 1.0 x 10-28 to 7.9 x 1028

float 4 bytes

– float fVal = -1,2;

double 8 bytes

– double dVal = -3.565;

decimal 16 bytes

– decimal dVal = -3456.343;

VARIABLE TYPES

Advanced Computer Programming

The String Type:

A string is a sequence of text characters. You typically create a string with a string literal, enclosed inquotes: "This is an example of a string.”

string myString = “Hello!”; Hello!Verbatim strings

string myString = @“2.5”” disk”; 2.5” diskstring e = "Joe said \"Hello\" to me"; Joe said "Hello" to mestring f = @"Joe said ""Hello"" to me"; Joe said "Hello" to mestring g = "\\\\server\\share\\file.txt"; \\server\share\file.txtstring h = @"\\server\share\file.txt"; \\server\share\file.txt

Some characters aren't printable, but you still need to use them in strings. Therefore, C# has a specialsyntax where characters can be escaped to represent non-printable characters. For example, it is commonto use newlines in text, which is represented by the '\n' char. The backslash, '\', represents the escape.When preceded by the escape character, the 'n' is no longer interpreted as an alphabetical character, butnow represents a newline.

You may be now wondering how you could represent a backslash character in your code. We have toescape that too by typing two backslashes, as in '\\'.

VARIABLE TYPES

Advanced Computer Programming

Escape Sequence Meaning\' Single Quote\" Double Quote\\ Backslash\0 Null, not the same as the C# null value\a Bell\b Backspace\f Form Feed\n Newline\r Carriage Return\t Horizontal Tab\v Vertical Tab

VARIABLE TYPES

Advanced Computer Programming

Expressions:

Expressions are used for performing operations over variables.

Return a value of known type. Two types of expressions

Operators Functions

VARIABLE TYPES

Advanced Computer Programming

Arithmetic operations:

They need more than one variable. Performs mathematical operations

+ (addition operation) - (subtraction operation) * (multiplication operation) / (division operation) % (modulus operation) ….

Category (by precedence) Operator(s) Associativity

Primary x.y f(x) a[x] x++ x-- leftUnary + - ! ~ ++x --x (T)x rightMultiplicative * / % leftAdditive + - leftShift << >> leftRelational < > <= >= leftEquality == != rightLogical AND & leftLogical XOR ^ leftLogical OR | leftConditional AND && leftConditional OR || leftNull Coalescing ?? LeftTernary ?: rightAssignment = *= /= %= += -= <<= >>= &= ^= |= => right

Left associativity means that operations are evaluated from left to right. Right associativity mean all operations occur from right to left, such as assignment operators where everything to the right is evaluated before the result is placed into the variable on the left.

VARIABLE TYPES

Advanced Computer Programming

Arithmetic operations:Abbreviations

int m = 5;int n = 4;

m = m + n; equals m += n; In other words in the end of both expressions m will have value of 9 and the value of n will not be changed.

They operate on one variable

++ is increment operator

i++; i = i + 1;

-- is decrement operator

i --; i = i – 1;

Prefix and postfix operators will yield to different results. i.e. “i++” and “++i” are not

same.

VARIABLE TYPES

Advanced Computer Programming

Arithmetic operations:Abbreviations

++k The result of the operation is the value of the operand after it has been incremented.

k++ The result of the operation is the value of the operand before it has been incremented.

--k The result of the operation is the value of the operand after it has been decremented.

k-- The result of the operation is the value of the operand before it has been decremented.

VARIABLE TYPES

Advanced Computer Programming

Arithmetic operations:Abbreviations

int k=0, m;

m = ++k;

Values of m and k will be 1

int k=0, m;

m = k++;

m will be 0 and

k will be 1

int k=5, m, n=2;

m = --k + n;

m will be 6 and

k will be 4

int k=0, m, n=7;

m = k++ + --n;

m will be 6 and

k will be 1 and

n will be 6

VARIABLE TYPES

Advanced Computer Programming

Arithmetic operations:Exercise

What will be the values of the variables after code piece below is executed?

int i, j, k;

i = 2;

j = 3 + i++;

k = 3 + ++i;

i *= ++k + j--;

i /= k-- + ++j;

VARIABLE TYPES

Advanced Computer Programming

Arithmetic operations:Exercise

Assuming that line of codes are independent, what will be the value of variable m after each line is executed?

int i = 0, j = 6, k = 4 , m = 5;

•m = k-- + ++i;

•m *= j % 4;

•m += k++ + (j-- * ++i);

http://msdn.microsoft.com/en-us/library/6a71f45d.aspx

VARIABLE TYPES

Advanced Computer Programming

Order of Operations: Rules that defines which procedures should be performed first.

In C# language some operators have execution privilege over others.

To predict the result of an expression first we should know the order of operations.

PEMDAS phrase may help to remember the order. P Parenthesis

E Exponent

M Multiplication

D Division

A Addition

S Subtraction

1 + 2 * 3 - 4 / 5 = ?

1 + (2 * 3) – (4 / 5)

6.2

VARIABLE TYPES

Advanced Computer Programming

Order of Operations:If we use all numbers in integer type then the result will be integer (In other words fraction

will be removed)

4/5 = 0

(integer division)

1 + (2 * 3) – (4 / 5)

7

VARIABLE TYPES

Advanced Computer Programming

Order of Operations:If we use all numbers in integer type then the result will be integer (In other words fraction

will be removed)

Different data types may yield different results in same operations.

Write and execute the codes in the next slides.

Explain the difference between results.

VARIABLE TYPES

Advanced Computer Programming

Characters:char 1 byte 0-256

'a' 'z' 'A' 'Z' '?' '@' '0' '9'

Special characters are represented by using “\” prefix.

'\n' : new line'\t' : tab'\'' : single quote'\\' : backslash

VARIABLE TYPES

Advanced Computer Programming

String:Sequence of characters.

Example: “Hello!”“first line\n second line \n third line”“” Empty string

“string” ClassUnicode – 16 bitExample:

string myString = “Hello!”;

Verbatim stringsstring myString = @“2.5”” disk”;

Result: “Hello world!”

VARIABLE TYPES

Retrieve a substring from a string

string Substring()

Advanced Computer Programming

String:

Result : “llo”

EXERCISE

Put your name and surname into two string variables.

Concatenate two strings.

Write the result to the console.

VARIABLE TYPES

C# language has built-in “DateTime” structure to represent date and time values.

We can store “year, month, day, hour, minute, second” values in a DateTime structure.

Advanced Computer Programming

Date Time:

DateTime dt = new DateTime(year, month, day);

Type

Variable name

Creating a new object

Initial values

VARIABLE TYPES

C# language has built-in “DateTime” structure to represent date and time values.

We can store “year, month, day, hour, minute, second” values in a DateTime structure.

Advanced Computer Programming

Date Time:

Type

A new DateTimeobject is created

VARIABLE TYPES

Their values can not be changed.

They have types.

We can use them in expressions bur can not alter them.

Defined by using “const” keyword before variable type.

Their values can be set only during definition line.

const int nVar = 34;

Advanced Computer Programming

Constants: