COP 2360 – C# Programming Exam 1 Review. Programming Language Basics A way to store and retrieve information to and from memory. A way to communicate.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

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.
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
Lecture 2 Introduction to C Programming
Introduction to C Programming
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
Variables Pepper. Variable A variable –box –holds a certain type of value –value inside the box can change Example –A = 2B+1 –Slope = change in y / change.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
CMT Programming Software Applications
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Data types and variables
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
Introduction to C Programming
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
String Escape Sequences
Basic Elements of C++ Chapter 2.
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.
What is RobotC?!?! Team 2425 Hydra. Overview What is RobotC What is RobotC used for What you need to program a robot How a robot program works Framework.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Input & Output: Console
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
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.
Chapter 2: Using Data.
COP 2360 – C# Programming Chapter 2 – Sept 2, 2015.
CPS120: Introduction to Computer Science
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.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
Computer Science 1620 boolean. Types so far: Integer char, short, int, long Floating Point float, double, long double String sequence of chars.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
Copyright Curt Hill Variables What are they? Why do we need them?
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 4 Literals, Variables and Constants. #Page2 4.1 Literals Any numeric literal starting with 0x specifies that the following is a hexadecimal value.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
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.
Bill Tucker Austin Community College COSC 1315
Chapter # 2 Part 2 Programs And data
Information and Computer Sciences University of Hawaii, Manoa
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Java Variables and Types
Lecture 2 Data Types Richard Gesick.
Object Oriented Programming
Multiple variables can be created in one declaration
Variables and Primative Types
Chapter 7 Additional Control Structures
C++ Data Types Data Type
2. Second Step for Learning C++ Programming • Data Type • Char • Float
Primitive Types and Expressions
Variables in C Topics Naming Variables Declaring Variables
COP2360 – C# Programming Chapter 6 – Sept 23, 2015.
Presentation transcript:

COP 2360 – C# Programming Exam 1 Review

Programming Language Basics A way to store and retrieve information to and from memory. A way to communicate with the "outside world" A way to compute basic mathematics and store results A way to compare information and take action based on the comparison A way to iterate a process multiple times A way to reuse components.

A way to store and retrieve information to and from memory. Variables – A variable is a memory location whose contents may change during program execution. – C# has two different "Types" of Variables Value Types – The variable represent a place in memory that actually holds the value of the variable. Reference Types – The variable represents a place in memory that holds the ADDRESS of the value of the variable.

Value Variable Types The variable location IS the value Integral Data Type – int = Integer = 4 Bytes (+- 2 billion) – short = Integer = 2 Bytes (+- 32K) – long = Integer = 8 Bytes (64 bits) 16 digit precision – char = 16 bits (2 Bytes - Unicode) - Discuss – bool = Boolean (True/False) = (Not sure of length) Floating Point Data Types – Double precision (double) gives you 52 significant bits (15 digits), 11 bits of exponent, and 1 sign bit. (Default for literals) – Single precision (float) gives you 23 significant bits (7 digits), 8 bits of exponent, and 1 sign bit. (Literals need to have "F" appended) – WARNING WILL ROBINSON – Storing information as a Float will store an approximation of the number, not potentially the correct number..

Value Variable Types The variable location IS the value Decimal Types – New – Up to 28 digits of precision (128 bits used to represent the number) – Decimal place can be included But unlike Float or Decimal, there is no conversion The Precision and the Decimal place go together For literals, put an “M” at the end to state that the number is a decimal Boolean – Value of either true or false – You must use true or false, not 0, 1 or -1 Char – Single Unicode Character (2 Bytes) Unicode is the Universal Character Codes – up to 65,536 different values In Assignment, Single Quotes are used – Char bChar = ‘B’;

Variable/Identifier Names Numbers, Letters (upper or lower case) and the underscore (_) Must begin with either a letter or an underscore. Cannot be a reserved word Should be indicative of what the variable is storing Capitalization Counts!!! – Variable1, variable1 and VARIABLE1 are three different variables!!! Try not to use run on variable names – costofliving – use cost_of_living or costOfLiving – currentinterestrate – use current_interest_rate or currentInterestRate

String Type A string is a sequence of zero or more characters. Strings in C# are enclosed in double quotes – char on the other hand are enclosed in single quotes The character number in a string starts with 0 and goes to the length of the string -1. Spaces count!!

Mixed Expressions What if you don’t like the rules casting is a feature that can change the type of data so that the calculation performs as you want, not as the computer wants. (int) (expression) calculates the expression, then drops any digits to the right of the decimal (double) (expression) calculates the expression, then stores whatever the answer is in a floating point number

Named Constants Remember, numeric and character literal constants (3, “G”, “Stuff”, ) are usually not a good idea. – They hide what is being done – They are hard to understand by others – Whenever possible, use named constants where the name means what the constant is/does

A Word About a Variable’s Scope A variable “lives” in the curly braces in which it was created and “dies” when the flow of control goes beyond those curly braces. Once a variable is defined at a parent level, C# will not allow a child block to have a variable declared with the same name

Scope of Variables Global/Class – Variables defined before any method definitions are made – Should be used VERY SPARINGLY – Can be accessed by any method at any level within a class. Local/Method – Variables defined within a method (but not inside an if, while, do, for or any other type of block.) – Can only be accessed by that method. Another method cannot “see” the variables in the first method. – Once the method returns, all local variables are destroyed. – Parameters create local variables – Local Variables can hide Global Variables, but the Global Variables can be accessed by prefacing them with :: Block – Variables defined within an if, while, do, for or any other type of block. – they exist only for the life of the block, and are destroyed when the block is completed. – C# will not let Block Variables hide Local Variables

Bradley’s Variable Name Rules All local variables (except simple loop variables like i or n) will start with a prefix letter followed by a proper cased variable name or an all cap constant name. – n = integerf = floatd = decimal – c = characterb = boolean – s = string nCounterbContinuesLastName cLetterGradefVALUE_OF_PI All global variables and constants will preface the above with the letter “g” followed by the variable name. gnLineCountergsAUTHORS_NAME All parameter variables should preface the above with the letter “p”. pnLengthpsGrade Block variables should only be used for intermediate results that are not needed to be retained, or for looping. They should not include any prefix for variable type. A lot of computer shops frown on Bradley’s rules, and others have implemented more stringent rules.

A way to communicate with the "outside world" Console.ReadLine() – Reads a String from the console and puts it into a String variable. – Once in the variable, parsing functions can be applied to cast the string as something else. String sInput = Console.ReadLine(); int nNumber = int.Parse(sInput); Also – Console.ReadKey() // reads one character – Console.Read() // Returns one character in it’s numeric equivalent

A way to communicate with the "outside world" Console.WriteLine(Expression) – Outputs the value of Expression to Console Console.WriteLine(“Format Codes {0} {1}”,Expression1, Expression 2) – Outputs the value of Expression1 and Expression 2 based on formatting specifics and text

Write and WriteLine Methods Simple format for a single variable: – Console.WriteLine (Variable Name) Also – Console.WriteLine (Format String, Variable List) – The two different formats means that the WriteLine method is Overloaded!! Write and WriteLine do the same thing – The only difference is that the WriteLine method includes a CRLF (Carriage Return/Line Feed) at the end of the variables. Remember, the Format String is any text (or other string variables) you want to print out along with format codes – {#,W:F} – # = variable number, W = width (optional) F = Format

A way to compute basic mathematics and store results Assignment Statements – Variable = Expression With assignment statements, the expression on the right side of the equal signs is completely computed, and the result is then stored in the variable on the left hand side. The equal sign does NOT mean that the two sides are equal. It is telling the compiler to do the computation, take the final value and place it in the variable. – number = number + 1

A way to compute basic mathematics and store results There are two main variable types that we have used so far – Integral – Exact representation of a number of a single character – Float/Double – Approximate representation of a number using an exponent and a mantissa? If Anything on the right side of a assignment statement includes a float, the result will be a float. Only if ALL of the variables on the right side are integral will the result be integral. Even with that said, pieces of the expression may be one or the other depending upon variable types BUT – regardless of what happens on the right side of an assignment statement, the final variable type is dependant on the variable type on the left of the assignment statement: – Int stuff; – Stuff = 3.0 * 4.3 * 2.0 / 1.1 Stuff = which is truncated to 23 C# MAY require you to cast an int to a double to show that you understand you may be loosing precision.

A way to compare information and take action based on the comparison A "logical Boolean expression" is a C# statement that has a value of either true or false Boolean Expressions compare two or more variables/objects and determine the relationship between the variable. Comparisons are based on relational operators: – == equals!=not equal – < less than<=less than or equal – > greater than>=greater than or equal Notice that "equal to" is TWO equal signs – a = b is as assignment statement. The value of b is stored in address b. – a == b is a conditional statement. If a is the same as b, the statement evaluates to true otherwise false

Logical Boolean Expressions Simple Data Types - Integers Numbers are pretty straight forward – 5 < 7 ? – 6 != 3+3 ? – 2.5 > 5.8 ? – 5.9 <= ? Notice a Boolean Expression can have other expressions (arithmetic for example) embedded within the expression. We’ll talk about float numbers in a little bit. You have to be careful!!

Logical Boolean Expressions Strings Strings are compared character by character using the Unicode characters The only direct operator available though is "==“ and “!=“. As soon as there is a difference between the two strings, that character is going to determine the logical relationship between the two strings. – "Bee" == "Before" ?? The determination is made on the third character. "e" Not = "f"

Logical Boolean Operators Logical Expressions can be connected together with Logical Operators. – ! is not – reverse the Boolean value of an expression (unary operator) – && is and – The entire expression is true if and only if both sides of the && are true (a > b) && (a > c) implies than – Both b and c are less than a What does (a >b) && (a==b) imply? – || is or – The entire expression is true if the left side is true or the right side is true (a > b) || (a > c) implies that – a is greater than b or a is greater than c or a is greater than both of them

New Order of Precedence with Logical Operators 1. Unary operators (- + ! ++ --) 2. Multiplication/Division (/ * %) 3. Addition/Subtraction (+ -) 4. Relational GT/LT( >=) 5. Relational Equals (== !=) 6. And (&&) 7. Or (||) 8. Assignment (=) What takes precedence over all of these? (Parenthesis) If you have operators at the same order, what is done first? (left to right) What happens with multiple "=". 1. This is a weird one. Multiple = are computed RIGHT TO LEFT!!

Basic “if” statement The syntax for "if" statements in C# is: – if (logical Boolean expression) – { C# commands – } – Else – { More C# Commands – { A "logical Boolean expression" is a C# statement that has a value of either true or false.

What About Floats Checking for Tolerance As we have seen, floating point numbers may not always actually "be" what they "seem" Unlike integers, one may want to consider a tolerance for when one can say that two floats are the "same". – For example, if we are dealing with money, maybe we can say that two floats (X AND Y) are the same if their difference is less than.0001 if (fabs(x - y) < )

Basic switch statement switch (expression) { case value1; statements break; case value 2; statements break; case value n; statements break; default; statements break; } Although multiple statements can be placed after each case statement without requiring curly braces, each case statement must end with the break command OR the next command will also be executed until a break is hit.

Typical switch command switch (nGradePoints/10) { case 0: case 1: case 2: case 3: case 4: case 5: Console.WriteLine ("You Failed"); break; case 6: Console.WriteLine ("gotta D"); break; case 7: Console.WriteLine ("gotta C"); break; case 8: Console.WriteLine("gotta B"); break; case 9: case 10: Console.WriteLine("gotta A"); break; default: Console.WriteLine ("bad grade"); break; }

A way to iterate a process multiple times Control Structures - Repetition – Two Main Methods “for” loop – iterate based on modifying a variable so that the loop is performed a certain number of times “while” loop – iterate based on the value of an expression or variable

Let’s look at the “for” loop for (initial statement; loop condition; update statement) { statements to execute } This is another instance when a single statement can be specified without the curly braces, but (as you already know) ALWAYS USE THE CURLY BRACES!!

Some comments on “for” if the initial condition is false, then for statement is skipped. C# allows the use of float variables for the for loop variables, but it is recommend that these not be used? Why? If the loop condition of a “for” statement is left blank, then it is assumed to be true. (As a matter of fact, all three pieces of a “for” can be left blank…What do you think this does?) for (;;) { Console.WriteLine(“Help Me!!!”); } The three pieces of the “for” do not necessarily have to reference the same variable: – for (i=1;j<10;k++) is valid, but it assumes that something in the body of the “for” handles the updating of “j” so that the loop will stop;

While Loops Come in two different flavors: – Pre-test loops – a condition is checked BEFORE any statements are executed. – Post-test loops – a condition is checked AFTER the statements are executed.

Let’s Look at the Pre-Test while while (conditional expression) { statement1; statement2; statementn; } many times while loops make use of a “loop control variable” – The variable would be initialized before starting the while loop. – It would be referenced in the conditional expression. – It would then be modified in the body of the while.

The post-test while loop do { statement1; statement2; statement3; } while (conditional expression) Using this format of the while, the condition is tested AFTER the commands are executed. This means that the statements are executed at least one time regardless of the conditional.

break and continue sometimes you may want to “get out of a loop” because of an error, or some other condition is met. break – completely stops the current loop – Often times done to report an error. – Many times used when doing a look-up. Once the value is found, stop looking. More on this when we get into arrays. – Control starts after the end of the current block of code (“}”) continue – returns control back to the beginning of the loop – while would NOT have their condition updated (unless it was done before the continue) – for would have the condition updated since it is part of the for syntax

A way to reuse components. Methods A method is a group of code that (may or may not) accept parameters and (may or may not) produce a result We have been writing a Method static void Main(string[] args)method which – Accepts a parameter named args that is a string array – Returns nothing – Is a Static Method – Is the starting place for our programs Another name for “Method” could be: – Function (what a method is called in C and C++) – SubProgram (what a method with nothing to return is called in VB.Net)

The Concept of Methods Methods are usually blocks of code that are accessed multiple times in a program. – So they allow for code to be reused – They accept parameters so that their results are flexible. Methods with the same name can have different sets of parameters and can return different types. This feature is called overloading. Methods are members of Classes. Methods that return a value can be used as a variable on the right side of an expression (like a constant)

Classes Classes are structures that combine data and processing into one component and are the basis of object oriented programming All data types in C# are really instances of classes. – Strings are a good example of the abilities of classes with all of the methods available to anything that is typed a String Classes are composed of Variables (Nouns), Properties (Adjectives) and Methods (functions and subroutines/Verbs.)