Variables and Expression COSC 315.101 Fall 2014 Bridget Blodgett.

Slides:



Advertisements
Similar presentations
True or false A variable of type char can hold the value 301. ( F )
Advertisements

Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Chapter 3 Assignment and Interactive Input. 2 Objectives You should be able to describe: Assignment Operators Mathematical Library Functions Interactive.
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.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 2: Introduction to C++.
ASP.NET Programming with C# and SQL Server First Edition
JavaScript, Third Edition
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
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.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
A Review of Programming and C++
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 3: Data Types and Operators JavaScript - Introductory.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Java Software Solutions Lewis and Loftus Chapter 5 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. More Programming Constructs.
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.
C++ Programming: Basic Elements of C++.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
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,
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Aside: Running Supplied *.java Programs Just double clicking on a *.java file may not be too useful! 1.In Eclipse, create a project for this program or.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
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.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 2 Computational Constructs Variables & Expressions Boolean Logic Conditionals: if & switch Branching & Looping Data Types & Type Conversion Structs,
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Information and Computer Sciences University of Hawaii, Manoa
Chapter 1.2 Introduction to C++ Programming
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Objectives In this chapter, you will:
Lecture 2 Data Types Richard Gesick.
Basic Elements of C++.
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.
2.1 Parts of a C++ Program.
Module 2: Understanding C# Language Fundamentals
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
Expressions and Assignment
Chapter 2: Introduction to C++.
2. Second Step for Learning C++ Programming • Data Type • Char • Float
Review of Previous Lesson
Presentation transcript:

Variables and Expression COSC Fall 2014 Bridget Blodgett

Basic C# Syntax C# compliers ignore whitespace in your code – Make good use of this to improve the readability of your code for yourself and others The code is made up of statements which are terminated with a semi-colon – If someone doesn’t compile double check your semi-colons! All statements are part of a block of code marked by curly brackets

Comments Besides using whitespace to make your code more understandable, comments can aid in comprehension { ; /* The above is an example of a statement */ /* The above is an example of a comment */ } The /* can be used for comments which span multiple lines. – C# will assume the comment keeps going until it sees the close comment mark */ If your comment is only one line you can also use //

Comments If you use /// in your code the C# compiler will read them just like a normal comment (i.e. ignore them when it compiles the code) – However, you can configure visual studio to extract this type of comment and make a documentation file It is also important to note that C# is case sensitive – So you need to make sure that you are using the correct case when calling functions or variables

Variables Variables are concerned with data storage. – The type of variable tells you what form of information it holds. To use a variable you must officially declare it and assign it a name and type – ; Failing to declare a variable that you are trying to use will cause your code to not compile.

Simple Types There are several simple types that are usually numbers and do not have any children or attributes (we’ll get to this later) – There are three ways of storing various integers: byte short int long – Floating-point values can be stored as: float double decimal

Simple Types There are also three non-numeric simple types available: TypeAlias ForAllowed Values charSystem.CharSingle Unicode character, stored as an integer between 0 and boolSystem.BooleanBoolean value, true or false stringSystem.StringA sequence of characters

static void Main(string[] args) { int myInteger; string myString; myInteger = 17; myString = “\”myInteger\” is”; Console.WriteLine(“{0} {1}.”. myString, myInteger); Console.ReadKey(); }

Variable Assignment Within this example you are assigning literal values to your variables. The = is the assignment operator You must also avoid certain words and characters. – The escape sequence ( \” ) is needed in this example to include the quotation marks around the string’s value – If you need to add a line break \n will do so in a string

Variable Naming When assigning names to variables it is important to select unique and relevant names. – If you have several different pieces of code all with a variable named myInteger it will quickly become confusing and useless to you Variable naming rules: – The first character must be a letter, an underscore ( _ ), or the at symbol ) – Subsequent characters may be letters, underscore characters, or numbers

Naming Examples myBigVar VAR1 _test 99BottlesofBeer namespace It’s-All-Over myVariable MyVariable MYVARIABLE

Additional Variable Info You can declare multiple variables of a type in one line – int highScore, lowScore; You can also declare and initialize a variable in the same line – int age = 25; Or declare and initialize multiple variables – int highScore = 25, lowScore = 0;

Expressions Expressions are the basic building blocks of computation – To form an expression combine an initialized variable with a literal value and operator Three categories: – Unary – Binary – Ternary Cover basic mathematical actions – +, -, *, /, %, signs

Expressions Only the + operator may be used with a string variable and bool will not allow you to use any You can also increment and decrement values with operators OperatorExample ExpressionResult ++var1 = ++var2;var1 is assigned the value of var var2 is incremented by 1. --var1 = --var2;Var1 is assigned the value of var2 – 1. var2 is decremented by 1. ++var1 = var2++;Var1 is assigned the value of var2. var2 is incremented by 1. --var1 = var2--;Var1 is assigned the value of var2. var2 is decremented by 1.

Assignment Operators Assignment operators result in the variable on the left side of the = being assigned the value of the operands and operators on the right – e.g. =, +=, -=, *=, /=, %=

Operator Precedence Operators follow a standard order of precedence – ++ (prefix), --, (), signs – *, /, % – +, - – =, *=, /=, %=, +=, -= – ++, -- (suffix)

More About Variables COSC Fall 2011 Bridget Blodgett

Type Conversion When dealing with simple types we’ve only used variables that contain the correct form of data for that type However, often you need to convert data between different types. – Implicit Conversion – Explicit Conversion

Explicit Conversion When you need to formally ask or tell the compiler to do a conversion it is an explicit conversion – The compiler will fail with an error about type conversion if you try to implicitly convert a variable that requires an explicit conversion Casting a variable into the type you want often fulfills this requirement – eg. (byte)sourceVar

Overflow If you attempt to cast a variable which is too large for the type you have selected it will often still compile – However, information will be lost in the process – This is called overflow You can set overflow checking context for an expression to: checked or unchecked – checked((byte)sourceVar); – The default behavior of the compiler can be changed to always check

Using Convert Commands We have used Convert.ToDouble() and Convert.ToInt32() several times – These commands work for strings which contain numbers as their input – The number must also fit within the type you are converting to These convert commands are always overflow checked

Complex Variable Types Beyond the simple types there are three complex types within C# – Enumerations (enums) – Structs (structures) – arrays

Enumerations Accepts one of a finite set of defined values as input You must declare the type and the acceptable values enum { } Declare variables like normal – ; Assign them values in a slightly different manner – =. ;

Enumerations By default the values in an enumeration are stored as int s – Specify a different type during the declaration: – enum : … Each value is assigned a underlying type value automatically in order of definition starting at 0 You can use the assignment operator to override the default and assign custom values

Structs Structs are data structures composed of several pieces of data Allows programmers to define types of variables that follow this structure struct { ; } Call data members within the struct using the period. = ;

Arrays[] Arrays[] allow you to store multiple values within a single variable Arrays are indexed lists of variables stored in a single array type variable – You call an individual value by specifying their index in the array – friendNames[ ]; – The index is a int starting with 0 and counting up until the last value in the array is stored All the values saved in an array shared a base type

Arrays[] Any simply type may be made into an array by appending the [] to the end of the type declaration – int[] myIntArray; – myIntArray[10] = 5; – Int[] myIntArray = {5,9,10,2,99}; – Int[] myIntArray = new int[5]; – Int[] myIntArray = new int[arraySize]; The variable which defines the array size must be declared a constant (include const in its declaration)

Loops and Looping Looping refers to the repeated execution of statements – It reduces the amount of code that needs to be written to repeat operations Also allows for specific conditions which will end the loop behavior

do Loops The code within the loop is executed until the bool test evaluates to false do { ; } while ( ); This is when the increment/decrement operators are the most useful ( ++ / -- ) Console.WriteLine(“In {0} year{1} you’ll have a balance of {2}.”, totalYears, totalYears == 1 ? “”: “s”, balance); Required!

if and do Wrapping a do loop in an if statement ensures that the do loop will only run if certain conditions are met – Otherwise the loop will always execute once – Not the most efficient way to perform this job

while Loops The boolean test is performed at the start of a while loop not at the end If the test evaluates to false the loop is not executed – The program goes onto the next piece of code after the loop while ( ) { ; } What happens when we try example 5 without validation?

for Loops Unlike other loops for loops execute a certain number of times before automatically exiting – The loop maintains its own counter For ( ; ; ) { ; } Specifying all the details of the loop in a single location make it easier to read/understand – This includes initializing the counter variable – Incrementing occurs after the code is executed!

foreach Loops Foreach loop enables each element in an array to be accessed foreach( in ) { //use for each element }

Interrupting Loops Knock, Knock…Who’s there?... Interrupting Cow…. Interrupting Cow- Moo! break – loop ends immediately continue – current loop ends and continues with next loop goto – jumps out of a loop to a specific position return – exits loop AND containing function

Infinite Loops Good for locking up computers! Occurs occasionally through errors that are legitimate Must force the program to quit manually (why break statements are good!) int i = 1; while (i<= 10) { If ((I %2) == 0) Continue; Console.WriteLine(“{0}, i++); }

Why Use Functions? Functions are pieces of code which can be used and reused many times Use instead of copying and pasting the same piece of code into your program each time it is needed Reduce the size of the program Increase ease of making changes Can perform the same operation on many different inputs (output)Can be used and manipulated like a variable

Defining a Function class Program { static void Write() { Console.WriteLine(“Text output from function.”); } static void Main(string[] args) { Write(); Console.ReadKey(); }

Function Definition Keywords: static – accessed from the class that defines them void – function does not return a value The Main() Function The basic function that is needed in every C# program for it to compile and execute Often calls the other functions, cases, or files to be used in the program

Returning Values A function which can be called is useful but doesn't add much to a program Sending and receiving variables or values increases the functionality Functions which return values may be used in expressions as if they were the value that they return string myString;double myVal; myString = GetString();double multiplier = 5.3; MyVal = GetVal()*multiplier;

Functions and Returns To return a value: Specify the type of value in the declaration (omit void) Use the return keyword to end the Function and transfer the value and control back to the calling code static double GetVal() { If (checkVal < 5) //stuff happens return 4.7; return 3.2; }

Taking Input When a Function accepts parameters (input) specify: The list of accepted parameters and their types Matching list of parameters in each function call static double Product(double param1, double param2) { return param1*param2; }

Variable Scope Scope is limited to the block in which they are defined and any sub-blocks Local variables are limited in scope to one function Global variables cover multiple functions These are defined outside of a function The static (or const) keyword is required The variable must be called with the. when there are multiple variables with the same name