COMPUTER PROGRAMMING II SUMMER 2011 Visual Basic to C#

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
Written by: Dr. JJ Shepherd
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
DECISION MAKING STRUCTURES Computer Programming 2.
True or false A variable of type char can hold the value 301. ( F )
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 5: Loops and Files.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
C++ for Engineers and Scientists Third Edition
VB .NET Programming Fundamentals
The switch Statement, DecimalFormat, and Introduction to Looping
5.05 Apply Looping Structures
By: Mr. Baha Hanene Chapter 3. Learning Outcomes We will cover the learning outcome 02 in this chapter i.e. Use basic data-types and input / output in.
Apply Sub Procedures/Methods and User Defined Functions
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
A Review of Programming and C++
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Why to Create a Procedure
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
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.
110-G1 Motivation: Within a program, may have to perform the same computation over and over Many programs share the same computation (e.g. sorting) To.
Flow of Control Part 1: Selection
CPS120: Introduction to Computer Science Decision Making in Programs.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
IMS 3253: Subroutines 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Procedures Subroutines Parameters –By Value.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Chapter 05 (Part III) Control Statements: Part II.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
COMPUTER PROGRAMMING II SUMMER 2011 Visual Basic to C#
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Applications Development
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Introduction to Programming Lecture Note - 2 Visual Basic Programming Fundamentals.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
COMPUTER PROGRAMMING I 5.04 Apply Decision Making Structures.
Written by: Dr. JJ Shepherd
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Controlling Program Flow with Decision Structures.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
5.02B Decision Making Structure (part 2). Compound Boolean Expressions.
C Language 1 Program Looping. C Language2 Topics Program looping Program looping Relational operators / expressions Relational operators / expressions.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Welcome to Computer Programming II! Computer Programming II Summer 2015.
5.04 Apply Decision Making Structures
User-Written Functions
Java Primer 1: Types, Classes and Operators
EGR 2261 Unit 4 Control Structures I: Selection
The Selection Structure
Arrays, For loop While loop Do while loop
Using C++ Arithmetic Operators and Control Structures
Presentation transcript:

COMPUTER PROGRAMMING II SUMMER 2011 Visual Basic to C#

Purpose This PowerPoint is for students that received instruction in Computer Programming I using the Visual Basic language. Computer Programming II uses the C# language. This lesson will introduces the differences between VB and C#.

Essential Standard This PowerPoint reviews variables, decision making statements, arrays, and methods (sub procedures). Major differences between C# and VB are also covered. C# is very different from VB in one KEY way. All statements MUST end with a semicolon (;). If you forget this, your code will not work. Exceptions: IF statements and loops The upside to this is two-fold:  1. Multiple coding statements may be on the same line  2. A long code segment can be spilt up without having to use an underscore like in VB.

Spacing C# Examples int intAge; string strName;  Two different statements- same line Long line of code:  string query whatever FROM tableName WHERE column = 1"; Both are perfectly valid statements in C#.

Semicolon Exceptions Two exceptions to the semicolon rule: if(x==b)  no semicolon here It is a “clause” - only part of the statement { y=7;  semicolon as normal } while(x< i)  no semicolon here either – again it is a “clause” { intGradeTotal=intGrade;  semicolon as normal }

Declaring a Variable In VB we use the Dim keyword to declare a variable:  Dim intAge as Integer C# handles this differently:  int intAge; In C# use the following format:  DataType variableName; All types are spelled out except integer (int) and character (char).

C# Examples string strName; char charGrade; int intAge; double dblTaxRate;

Coding Blocks In VB we use the End keyword to end coding blocks like IF statements or loops. If a = b Then b=c End If In C#, we use braces so this code block would be written: if(a==b) { b=c; }

Equality Check (==) You might of noticed something on the last slide- a == in the if statement. In VB the assignment operator and equality are the same (=). This is NOT true in C#. The equals sign is solely used for assignment. To check for equality you must use ==. Using = in an if statement to check for equality is a logic error. The code will run properly, but not produce the intended result. (It will always be false.)

Increment Counters In VB to add one to a counter we use varName += 1, for two we use +=2 and so on. (i+=1) This shorthand works in C# as well, but C# provides an additional way to add or subtract one from a counter. i++; i--; ++ adds 1 to the value of i while -- subtracts one. Remember the semicolon is required. To count by 2, or another number, we use the same shorthand is in VB (i+=2).

IF Statements In C# we do not use THEN keyword as in VB. The comparison is enclosed in ( ) after the if keyword. if (a < b) { Statements } All statements after the if (to be run if the if is true) that would be executed are enclosed in braces ( { } ).

IF..Then..Else Example if(a > b) { b=c; d= 7; } else { b=5;d=4; }

Else If C# handles multiple else if statements a little differently as well. There is a space between else and if unlike in VB. As in VB there can be multiple else ifs and a else (default) if all statements are false. if (a == b) {c = 12;} else if (a>b) {c=14;} else if (a < b) { c = 16; } else { c = 10; }

If Statements in Assignment Statements Like VB, C# supports an if statement in an assignment statement. However the format is completely different: string strName = (a < b) ? "less than 10" : "greater than 10"; ? is called the ternary operator.

And/Or & Short Circuiting In VB we use the And/Or keywords in compound if statements. C#  And = &  Or = | To short circuit the statement use && (and) or || (or).

Examples else if (number 5)  Using and else if(number > 50 | number < 25)  Usingor else if (number 5)  Using short circuit and else if(number > 50 || number < 25)  Using short circuit or

Select Case The Select Case statement in VB do not exist in C#. Instead C# has the switch keyword. This operates similarly to Select Case, but has some key differences. Let’s refresh our memory with an example: Select case intGrades Case 90 to 100 strGrade= “A” Case 80 to 89 strGrade=“B” Case 70 to 79 strGrade=“C” Case 60 to 69 strGrade=“D” Case Is < 60 strGrade=“F” Else Messagebox.show(“Please input a valid number!”) End Select

Switch switch(intGrades) { case 10: case 9: strGrade="A"; break; case 8: strGrade="B"; break; case 7: strGrade = "C"; break; case 6: strGrade="D"; break; case 5: case 4: case 3: case 2: case 1: strGrade = "F"; break; } Notice instead of using the To keyword we can just assign multiple cases to a given statement. The break; as the end of each case is required or the program will continue to read through the statements. There could be multiple true cases in C# unlike VB which stops after finding ONE true case. Break prevents this which is almost always the desired outcome.

Switch 2 If all cases are false and we want an action to occur we use the default keyword: switch (caseSwitch) { case 1: Console.WriteLine("Case 1"); break; case 2: Console.WriteLine("Case 2"); break; default: Console.WriteLine("Default case"); break; }

Select Case vs. Switch The C# Switch statement does not allow ranges or comparisons like the Select Case statement in Visual Basic. It also does not allow Boolean comparison. This is one place where the VB implementation is superior to the C# one.

Loops VB and C# each support the following loops:  Do  While  For  For each In C# loops are written in the same syntax as an if statement: while (i< intNum)  remember no semicolon on this line { Code to run in the loop;  semicolon at the end of each code statement unless using a if statement }

Loop Examples while (i <= 50)//pretest loop { intResult = intResult + i; i++; } do { intResult = intResult + i; i ++; } while (i <= 50)//posttest loop

For Statements For statements are written completely differently in C#: for(i=0; i<=50; i++) { intResult = intResult + i; } VB: For i as Integer = 0 to 50 intResult = intResult + i Next i Modifier – increment or decrement Condition Initializer Condition Modifier – increment or decrement – Uses Step if other than add 1.

Step Keyword In VB to count by a value other than 1 we use the Step keyword. This is not supported in C#. To count by a value other than 1 we change the end of the statement. To count by 2’s upward for example: for(i=0; i<=50; i+=2) To decrease by 2: for(i=100; i>=50; i-=2)

For each The for each loop is handled differently in C# as well. foreach(int j in intArray)//no space { lstGrades.Items.Add(j); } VB: For Each j In intArray lstGrades.Items.Add(j) Next j

Arrays In VB we use ( ) in array statements. In C# [ ] are used instead. Dim intArray = New Integer(4) {1, 2, 3, 4, 5} (VB) int[] intArray = new int[5] {1,2,3,4,5}; (C#) In VB we put in 1 less than the number of elements we want in the array. This is NOT the case in C#. If we want five elements we use a 5. Arrays are still index-based starting at 0.

COMPUTER PROGRAMMING I SUMMER 2011 Applying Functions/Methods in C#

Breaking it Up As programs gets more complex- they become longer and harder to debug or even figure out what exactly is going on. Functions, also called Methods, provide a way to break up long coding segments and reduce repeated code.

Declare a Method When you declare a method, you will follow a specific formula for the method header access_modifier return_type Name () Access Modifier  We will only use the public in this course.  You can use private which would restrict use of the method. Return Type  The return type will either be void, if there is no value being returned, or it will be the data type of the value being returned.

Declare a Method Method Header Example: public void Signature() { lblResult.Text = “Created by J Smith”; } To use the method, you will “Call” it when wanted. Signature();

Methods with Parameters Parameters provide information to a method that is necessary to do its job. The method call provides the values – called actual arguments. You will add the “formal arguments” or “parameters” to the method header. public void Signature(string Name )

Methods with Parameters Method: public void Signature(string Name ) { lblResult.Text = “Written by: ” + Name; } Call: Signature(strName); The arguments and parameters MUST match in order, data type and number.

Methods that Return a Value When you specify a return type you will add a return statement. Method Header Example: public string Signature() { return “Created by J Smith”; } Return data type and what is returned MUST match. Return Type

Methods that Return a Value When a method returns a value, the method call must be part of an assignment statement. Method Call Example: lblResult.Text = Signature();

Two Ways to Pass Arguments There are two ways to pass arguments.  Pass-by-Value  Pass-by-Reference Pass-by-Value is how we passed the variable strName earlier.

Pass-By-Value This is the default way to pass arguments in C#. A copy of the value is made and sent to the method. Any changes are not passed back to the call. Think of this as a one way street; the value only moves in one direction.

Pass-By-Reference The method has the ability to access and modify the original variable from the call. Reference-type variables store references to objects. Think of it as sending the actual address of the object for the method to access the value. The method can then manipulate that value and send it back.

Pass-By-Reference To pass a variable by reference use the keyword ref. Apply the ref keyword to the parameter declaration allows you to pass that variable by reference. The ref keyword is used for variables that already have been initialized in the calling method.  It must be initialized, otherwise the compiler will generate an error.

Pass-By-Reference public void Calculate(int num1, ref int num2) { num2 = num1 + 1; } private void btnCalc_Click(object sender, EventArgs e) { int n1 = 0; int n2 = 0; Calculate(n1, ref n2); lblResult.Text = n2.ToString(); //displays 1 in label }

Conclusion This PowerPoint provided an overview of creating methods in C#. Next step is to practice with sample programs the skilled students have learned! The Unpacked Content will provide some sample programs. For more information on this topic  us/library/aa645760(v=VS.71).aspx us/library/aa645760(v=VS.71).aspx