2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.

Slides:



Advertisements
Similar presentations
Air Force Institute of Technology Electrical and Computer Engineering
Advertisements

Programming Languages and Paradigms The C Programming Language.
Neal Stublen C# Data Types Built-in Types  Integer Types byte, sbyte, short, ushort, int, uint, long, ulong  Floating Point Types.
C#: Data Types Based on slides by Joe Hummel. 2 UCN Technology: Computer Science Content: “.NET is designed around the CTS, or Common Type System.
Introduction to the C# Programming Language for the VB Programmer.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
3. Data Types. 2 Microsoft Objectives “.NET is designed around the CTS, or Common Type System. The CTS is what allows assemblies, written in different.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Basic Elements of C++ Chapter 2.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
Fundamentals of C and C++ Programming Control Structures and Functions.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
Chapter 2: Using Data.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
1 Advanced Programming IF. 2 Control Structures Program of control –Program performs one statement then goes to next line Sequential execution –Different.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
 The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Controlling Program Flow. Data Types and Variable Declarations Controlling Program Flow.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
CSC 212 Object-Oriented Programming and Java Part 2.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
By Mr. Muhammad Pervez Akhtar
Programming Fundamentals. The setw Manipulator setw changes the field width of output. The setw manipulator causes the number (or string) that follows.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
1 Advanced Programming IF. 2 Control Structures Program of control –Program performs one statement then goes to next line Sequential execution –Different.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
C Language 1 Program Looping. C Language2 Topics Program looping Program looping Relational operators / expressions Relational operators / expressions.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 2 Variables.
Chapter Topics The Basics of a C++ Program Data Types
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Chapter 12 Variables and Operators
Basic Elements of C++.
Multiple variables can be created in one declaration
Computing with C# and the .NET Framework
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 3: Understanding C# Language Fundamentals
Basic Elements of C++ Chapter 2.
Chapter 12 Variables and Operators
Arrays, For loop While loop Do while loop
Starting JavaProgramming
Java - Data Types, Variables, and Arrays
Chapter 7 Additional Control Structures
Module 2: Understanding C# Language Fundamentals
Chapter 2 Variables.
PHP.
Chapter 6 Control Statements: Part 2
elementary programming
2.6 The if/else Selection Structure
Visual Programming COMP-315
Chapter 2 Variables.
Chapter 12 Variables and Operators
Presentation transcript:

2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Objectives Introduce the core C# language features class Main types 2: Basics Objectives Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Class Keyword class used to define new type specify name 2: Basics Class Keyword class used to define new type specify name enclose body in { } Most C# code placed inside a class no global variables allowed no global methods allowed class definition class MyApplication { ... } Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Main Main method is the application entry point 2: Basics Main Main method is the application entry point must be static method of some class any access level such as public or private is allowed Main can perform environment interaction can receive command line arguments as array of strings can return int to indicate success/failure class MyApplication { static void Main() ... } entry point Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Simple types Comprehensive set of simple types available Type 2: Basics Simple types Comprehensive set of simple types available Type Description Special format for literals bool Boolean true false char 16 bit Unicode character 'A' '\x0041' '\u0041' sbyte 8 bit signed integer none byte 8 bit unsigned integer short 16 bit signed integer ushort 16 bit unsigned integer int 32 bit signed integer uint 32 bit unsigned integer U suffix long 64 bit signed integer L or l suffix ulong 64 bit unsigned integer U/u and L/l suffix float 32 bit floating point F or f suffix double 64 bit floating point no suffix decimal 128 bit high precision M or m suffix string character sequence "hello" Boolean character integer floating point string Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Local variable declaration 2: Basics Local variable declaration Declare variables by specifying type and name names are case sensitive comma separated list for multiple variables end with semicolon class MyApplication { static void Main() double area; char grade; int x, y, z; string name; ... } variables Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Local variable initialization 2: Basics Local variable initialization Can initialize local variables when declared use literal value or expression compiler error to use without initializing class MyApplication { static void Main() int width = 2; int height = 4; int area = width * height; int x; int y = x * 2; ... } literals expression error, x not set Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Type conversion Some automatic type conversions available 2: Basics Type conversion Some automatic type conversions available from smaller to larger types Conversions which may lose information require cast syntax is type name inside parentheses int i = 5; double d = 3.2; d = i; i = (int)d; implicit conversion cast required Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Input Read input using ReadLine from Console class in System namespace 2: Basics Input Read input using ReadLine from Console class in System namespace returns entire input line as a string Typically then need to convert string to actual type conversion methods provided in Convert class read entire line string s = System.Console.ReadLine(); int i = System.Convert.ToInt32 (s); double d = System.Convert.ToDouble(s); convert string to int convert string to double Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Output Write output using Write and WriteLine 2: Basics Output Write output using Write and WriteLine from Console class in System namespace WriteLine adds line terminator in output overloaded versions allow printing of all types some versions take format string and data variable argument list version allows printing multiple values int i = 3; double d = 5.2; System.Console.WriteLine(i); System.Console.WriteLine(d); System.Console.WriteLine("first {0} second {1}", i, d); int double multiple format string placeholder value Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Library namespace Core standard library is System namespace 2: Basics Library namespace Core standard library is System namespace a using directive provides shorthand access using System; class MyApplication { static void Main() string s = Console.ReadLine(); int i = Convert.ToInt32(s); ... } using directive short names Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Comments Three comment styles available XML documentation comment /// 2: Basics Comments Three comment styles available XML documentation comment /// delimited code comment /* ... */ single line code comment // /// <summary> /// MyApplication is very simple.</summary> class MyApplication { static void Main() /* delimited comment can extend across multiple lines */ int x; // comment goes to end of line ... } documentation delimited single line Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Operators Comprehensive set of operators available int x = 5; 2: Basics Operators Comprehensive set of operators available Operator Description + addition - subtraction * multiplication / division % remainder << left shift >> right shift & bitwise and | bitwise or ^ bitwise xor ~ bitwise complement int x = 5; int y = 3; int z = x + y; addition Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Combination assignment 2: Basics Combination assignment Several combination assignment operators available perform both operation and assignment Operator Description += add / assign -= subtract / assign *= multiply / assign /= divide / assign %= remainder / assign <<= left shift / assign >>= right shift / assign &= bitwise and / assign |= bitwise or / assign ^= bitwise xor / assign int x = 5; x += 2; combination addition Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Shorthand operators A few shorthand operators available int x = 5; 2: Basics Shorthand operators A few shorthand operators available Operator Description ++ pre/post increment -- pre/post decrement ?: conditional int x = 5; int y = x++; int z = ++x; int x = 5; int y = 3; int max; max = x > y ? x : y; post-increment y = 5, x = 6 max set to greater of x and y pre-increment x = 7, z = 7 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Array Arrays provide efficient storage of multiple data elements 2: Basics Array Arrays provide efficient storage of multiple data elements create using new specify element type and array size access elements using operator [ ] total number of elements recorded in Length property valid indices are 0 to Length-1 IndexOutOfRangeException generated if index invalid create int[] a = new int[5]; a[0] = 17; a[1] = 32; int x = a[1]; int l = a.Length; element access number of elements Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Array element values Array elements have default values 2: Basics Array element values Array elements have default values 0 for numeric types false for bool '\x0000' for char null for references Programmer can supply initial values default to false bool[] a = new bool[10]; int[] b = new int[5]; int[] c = new int[5] { 48, 2, 55, 17, 7 }; default to 0 set to given values Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

If statement if statement provides conditional execution 2: Basics If statement if statement provides conditional execution Boolean expression is evaluated associated statement executed only if expression is true expression must be inside parentheses keywords such as "if" are case sensitive int temperature = 127; bool boiling = false; if (temperature >= 100) boiling = true; if statement Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

If/else statement if statement may provide optional else part 2: Basics If/else statement if statement may provide optional else part executed if expression is false int x = 3; int y = 5; int min; if (x < y) min = x; else min = y; else part Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Code block Block required for multiple statements in control construct 2: Basics Code block Block required for multiple statements in control construct use { ... } int x = 3; int y = 5; int min, max; if (x < y) { min = x; max = y; } else min = y; max = x; block block Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Comparison and logical operators 2: Basics Comparison and logical operators Comparison operators compare two values yield Boolean result Combine Boolean values with conditional logical operators int x; char c; if (x > 0 && x < 10) ... if (c == 'y' || c == 'Y') if (!Char.IsLetter(c)) == equal != not equal <, <= less >, >= greater && and || or ! not both must be true either can be true c can't be a letter Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

2: Basics Switch statement switch statement performs selection from a set of options expression evaluated and matching case executed case labels must be constant values end each case with keyword break optional default case executed if no label matches double total = 0.0; char grade = 'C'; switch (grade) { case 'A': total += 4.0; break; case 'B': total += 3.0; break; case 'C': total += 2.0; break; case 'D': total += 1.0; break; case 'F': total += 0.0; break; default: Console.WriteLine("Error"); break; } switch cases default Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Switch type Types allowed in switch are limited integral types string 2: Basics Switch type Types allowed in switch are limited integral types string string string color = "blue"; switch (color) { case "red" : Console.WriteLine("red"); break; case "blue" : Console.WriteLine("blue"); break; case "green": Console.WriteLine("green"); break; } strings Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

2: Basics Multiple labels Can associate several different labels with same action use separate case for each label place action in last case switch (grade) { case 'A': case 'B': case 'C': Console.WriteLine("pass"); break; case 'D': case 'F': Console.WriteLine("no pass"); } pass no pass Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

2: Basics Multiple actions Can perform multiple actions for match on single label must forward control to next desired case use goto case or goto default instead of break string level = "gold"; switch (level) { case "silver": priorityCheckIn = true; break; case "gold": priorityUpgrade = true; goto case "silver"; case "platinum": useOfLounge = true; goto case "gold"; } forward control to other case Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

while loop while loop runs as long as condition is true 2: Basics while loop while loop runs as long as condition is true statements repeatedly executed stops when condition becomes false int i = 0; while (i < 5) { ... i++; } loop while true Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

do-while loop do-while loop test condition located after body 2: Basics do-while loop do-while loop test condition located after body body executed at least once int x; do { string s = System.Console.ReadLine(); x = System.Convert.ToInt32(s); } while (x < 0); do test done after body Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

for loop for loop centralizes control information 2: Basics for loop for loop centralizes control information initialization, condition, update parts separated by semicolons done once at start loop runs while test is true done each time after body for (int k = 0; k < 5; k++) { ... } Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

2: Basics foreach loop Specialized foreach loop provided for collections like array reduces risk of indexing error provides read only access int[] data = new int[5] { 48, 2, 55, 17, 7 }; int sum = 0; foreach (int x in data) { sum += x; } foreach type value collection Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Break break statement exits enclosing statement 2: Basics Break break statement exits enclosing statement usable with switch, while, do, for, foreach int i = 0; bool error; while (i < 5) { ... if (error) break; } break Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Continue continue statement skips to end of current loop iteration 2: Basics Continue continue statement skips to end of current loop iteration does not exit loop usable with while, do, for, foreach int i = 0; bool skip; while (i < 5) { ... if (skip) continue; } continue Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Goto goto transfers control to the specified labeled statement 2: Basics Goto goto transfers control to the specified labeled statement label must be in current or outer scope label must be in same method int[,] data = new int[2,4]; for (int i = 0; i < data.GetLength(0); i++) { for (int j = 0; j < data.GetLength(1); j++) if (data[i,j] < 0) goto error; ... } error: Console.WriteLine("Error"); goto label Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Summary Class is basic unit of C# coding 2: Basics Summary Class is basic unit of C# coding Main defines application entry point Comprehensive set of types available Standard operators provided Arrays provide efficient way to store large amount of data Control constructs offer balance of convenience and safety Programming C# © 2003 DevelopMentor, Inc. 12/1/2003