Docsity

CS 112 Lecture 4: Computer Hardware, Software, Variables, and Data Types in C#, Slides of C programming

Toggle sidebar
bg1
1
CS 112 Introduction to
Programming
Lecture #4:
Computer Hardware/Software;
Variables, C# Data Types, and IO
http://flint.cs.yale.edu/cs112/
2
Outline
ØReview
qComputer hardware/software
qVariables and C# data types
qInput and output
3
Review
rDifferent programming language levels
mMachine code, assembly code, intermediate language, high
level language
mA compiler translates a program from a higher level language
to a lower level language
rC# compiler compiles a C# program to MSIL
rStructure of a C# program
mA program consists of one or more classes
mA class consists of one or more methods
mA method consists of one or more statements
mWhite space and comments, identifiers, keywords, namespace
rOur first C# programs
4
C# Program Structure (Console)
rProgram specifications (optional)
//==========================================================
//
// File: HelloWorld.cs CS112 Demo
//
// Author: Zhong Shao Email: [email protected]
//
// Classes: HelloWorld
// --------------------
// This program prints the string "Hello World!”
//
//==========================================================
rLibrary imports (optional)
using System;
rClass and namespace definitions
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine(“Hello World!”);
}
}
5
C# Program Structure (Window)
rProgram specifications (optional)
//==========================================================
//
// File: HelloWorld.cs CS112 Demo
//
// Author: Zhong Shao Email: [email protected]
//
// Classes: HelloWorld
// --------------------
// This program shows a message box.
//
//==========================================================
rLibrary imports (optional)
using System;
using System.Windows.Forms;
rClass and namespace definitions
class HelloWorld
{
static void Main(string[] args)
{
MessageBox.Show(“Hello World!”);
}
}
6
Outline
qReview
ØComputer hardware/software
qVariables and C# data types
qInput and output
pf3
pf4
pf5

Partial preview of the text

Download CS 112 Lecture 4: Computer Hardware, Software, Variables, and Data Types in C# and more Slides C programming in PDF only on Docsity!

CS 112 Introduction to

Programming

Lecture #4:

Computer Hardware/Software;

Variables, C# Data Types, and IO

http://flint.cs.yale.edu/cs112/

2

Outline

ÿ Review

q Computer hardware/software

q Variables and C# data types

q Input and output

3

Review

r Different programming language levels

m Machine code, assembly code, intermediate language, high

level language

m A compiler translates a program from a higher level language

to a lower level language

r C# compiler compiles a C# program to MSIL

r Structure of a C# program

m A program consists of one or more classes

m A class consists of one or more methods

m A method consists of one or more statements

m White space and comments, identifiers, keywords, namespace

r Our first C# programs

4

C# Program Structure (Console)

r Program specifications (optional) //========================================================== // // File: HelloWorld.cs CS112 Demo // // Author: Zhong Shao Email: [email protected] // // Classes: HelloWorld // -------------------- // This program prints the string "Hello World!” // //========================================================== r Library imports (optional) using System; r Class and namespace definitions

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

5

C# Program Structure (Window)

r Program specifications (optional) //========================================================== // // File: HelloWorld.cs CS112 Demo // // Author: Zhong Shao Email: [email protected] // // Classes: HelloWorld // -------------------- // This program shows a message box. // //========================================================== r Library imports (optional) using System; using System.Windows.Forms; r Class and namespace definitions class HelloWorld { static void Main(string[] args) { MessageBox.Show(“Hello World!”); } }

6

Outline

q Review

ÿ Computer hardware/software

q Variables and C# data types

q Input and output

7

Outline

q Admin. and review

ÿ Computer hardware/software

q Variables and C# data types

8

Computer Environment: Hardware

r Hardware

m the physical, tangible parts of a computer

m E.g., CPU, storage, keyboard, monitor

Monitor

Keyboard

Main

Memory

Central

Processing

Unit

CD ROM

Hard Disk

chip that executeschip that executes

program commandsprogram commands

e.g.,e.g.,

Intel Pentium IVIntel Pentium IV

Sun SparcSunSparc

TransmetaTransmeta

primary storage areaprimary storage area

for programs and datafor programs and data

also called RAMalso called RAM

9

Storing Information

r Computers store all information digitally:

m E.g. numbers, program instructions, text, audio, and

video

r Information is stored in binary numbers

m A single binary digit (0 or 1) is called a bit

m A single bit can represent two possible states, like a

light bulb that is either on (1) or off (0)

m Combinations of bits are used to store values

H i , H i , H e a t h e r .H e a t h e r.

10

Binary Bit Combinations

1 bit1 bit

2 bits2 bits

3 bits3 bits

4 bits4 bits

Each additional bit doubles the number of possible combinationsEach additional bit doubles the number of possible combinations

11

Information is Stored in Memory

Large values are Large values are

stored in consecutivestored in consecutive

memory locationsmemory locations

Each memory cell stores aEach memory cell stores a

set number of bits (usuallyset number of bits (usually

8 bits, or one8 bits, or one^ bytebyte ))

Each memory cell has aEach memory cell has a

numericnumeric addressaddress , which, which

uniquely identifies ituniquely identifies it

12

Computer Environment: Software

r Operating System

m E.g., Linux, Mac OS X, Windows 2000, Windows XP

m manages resources such as CPU, memory, and disk

m controls all machine activities

r Application programs

m generic term for any other kind of software

m compiler, word processors, missile control systems,

games

19

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);

20

Constants

r A constant is similar to a variable except that it holds

one value for its entire existence

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

constant

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

constant

constant int numberOfStudents = 42;

r Why constants?

m give names to otherwise unclear literal values

m facilitate changes to the code

m prevent inadvertent errors

21

C# Data Types

r There are 15 data types in C#

r Eight of them represent integers:

m byte, sbyte, short, ushort, int, uint, long,ulong

r Two of them represent floating point numbers

m float, double

r One of them represents decimals:

m decimal

r One of them represents boolean values:

m bool

r One of them represents characters:

m char

r One of them represents strings:

m string

r One of them represents objects:

m object

22

Numeric Data Types

r The difference between the various numeric types is their size,

and therefore the values they can store:

Range

0 - 255 -128 - 127 -32,768 - 32767 0 - 65537 -2,147,483,648 – 2,147,483, 0 – 4,294,967, -9× 1018 to 9× 1018 0 – 1.8× 1019

±1.0× 10 -28; ±7.9× 1028 with 28-29 significant digits

±1.5× 10 -45; ±3.4× 1038 with 7 significant digits ±5.0× 10 -324; ±1.7× 10308 with 15-16 significant digits Question: you need a variable to represent world population. Which type do you use?

Type

byte sbyte short ushort int uint long ulong

decimal

float double

Storage

8 bits 8 bits 16 bits 16 bits 32 bits 32 bits 64 bits 64 bits

128 bits

32 bits 64 bits

23

Examples of Numeric Variables

int x = 1;

short y = 10;

float pi = 3.14 f ; // f denotes float

float f3 = 7E-02 f ; // 0.

double d1 = 7E-100;

// use m to denote a decimal

decimal microsoftStockPrice = 28.38 m ;

Example: TestNumeric.cs

24

Boolean

r A bool value represents a true or false

condition

r A boolean can also be used to represent any

two states, such as a light bulb being on or off

r The reserved words true and false are

the only valid values for a boolean type

bool doAgain = true;

25

Characters

r A char is a single character from the a character set

r A character set is an ordered list of characters; each character is

given a unique number

r C# uses the Unicode character set, a superset of ASCII

m Uses sixteen bits per character, allowing for 65,536 unique characters m It is an international character set, containing symbols and characters from many languages m Code chart can be found at: http://www.unicode.org/charts/

r Character literals are represented in a program by delimiting with

single quotes, e.g.,

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

char response = ‘Y’;

26

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.

27

string

r A string represents a sequence of

characters, e.g.,

string message = “Hello World”;

r Strings can be created with verbatim

string literals by starting with @, e.g.,

string a2 = @“\server\fileshare\Hello.cs”;

r Question: how to represent this string:

The double quotation mark is “

r Question: how to represent this string:

\plucky.cs.yale.edu\zs9$\MyDocs

28

Outline

q Review

q Computer hardware/software

q Variables and C# data types

ÿ Input and output

29

Data Input

r Console.ReadLine()

m Used to get a value from the user input m Example

string myString = Console.ReadLine();

r Convert from string to the correct data type

m 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 );

m Double.Parse() m Single.Parse()

30

Output

r Console.WriteLine(variableName) will print the variable

r You can use the values of some variables at some positions of

a string:

System.Console.WriteLine(“{0} {1}.”, iAmVar0, iAmVar1);

r You can control the output format by using the format specifiers:

float price = 2.5f; System.Console.WriteLine(“Price = {0:C}.”, price);

Price = $2.50.

q For a complete list of format specifiers, see

http://msdn.microsoft.com/library/en-us/csref/html/vclrfFormattingNumericResultsTable.asp

Example: TaxAndTotal.cs