BIM313 – Advanced Programming Techniques C# Basics 1.

Slides:



Advertisements
Similar presentations
Introduction to Control Statements Presented by: Parminder Singh BCA 5 th Sem. [ Batch] PCTE, Ludhiana 5/12/ Control Statements.
Advertisements

IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
Chapter 2: Introduction to C++.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
CPS120: Introduction to Computer Science Lecture 8.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
1. 2 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decisions { class.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Outline Variables 1.
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
2440: 211 Interactive Web Programming Expressions & Operators.
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
BİL528 – Bilgisayar Programlama II Making Decisions, Loops, Debugging, Designing Objects Using Classes 1.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
CSC204 – Programming I Lecture 4 August 28, 2002.
BIM313 – Advanced Programming Techniques Flow Control 1.
 Simple C# program  Console applications input and output text in a console window, which in Windows XP and Windows Vista is known as the Command Prompt.
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.
C Derived Languages C is the base upon which many build C++ conventions also influence others *SmallTalk is where most OOP comes Java and Javascript have.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
CPS120: Introduction to Computer Science
1 Advanced Programming IF. 2 Control Structures Program of control –Program performs one statement then goes to next line Sequential execution –Different.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
THE BASICS OF A C++ PROGRAM EDP 4 / MATH 23 TTH 5:45 – 7:15.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Computer Engineering 1 st Semester Dr. Rabie A. Ramadan 3.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
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.
ICT Introduction to Programming Chapter 4 – Control Structures I.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
1 Advanced Programming IF. 2 Control Structures Program of control –Program performs one statement then goes to next line Sequential execution –Different.
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: รัฐภูมิ เถื่อนถนอม
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.
Variables and Expression COSC Fall 2014 Bridget Blodgett.
Lecture 2 Computational Constructs Variables & Expressions Boolean Logic Conditionals: if & switch Branching & Looping Data Types & Type Conversion Structs,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Data types Data types Basic types
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Sachin Malhotra Saurabh Choudhary
Chapter 3: Understanding C# Language Fundamentals
Introduction to C Programming
Statements, Comments & Simple Arithmetic
CET 3640 – Lecture 2 Java Syntax Chapters 2, 4, 5
Starting JavaProgramming
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
2.1 Parts of a C++ Program.
Basics of ‘C’.
Introduction to C Programming
Chapter 2: Introduction to C++.
Visual Programming COMP-315
Chap 2. Identifiers, Keywords, and Types
Presentation transcript:

BIM313 – Advanced Programming Techniques C# Basics 1

Contents Variables and Expressions – Comments – Variables – Expressions – Operators – Namespaces Flow Control – if, switch – while, do-while, for, foreach – Binary operators 2

Basic C# Syntax White spaces (space, carriage return, tab) are ignored by the C# compiler Statements are terminated with a semicolon (;) C# code is case-sensitive C# is a block-structured language and blocks are delimited with curly brackets (‘{’ and ‘}’) Please indent your code so that your code becomes more readable Write comments while writing the codes 3

Comments Type I /* Single line comment */ /* Multi- Line Comment */ Type II // Another single line comment a = 0; // Initialize the count Type III /// Special comments used for documentation 4

Variables Think variables as boxes to store data in them Variables have types, names, and values int num = 5; Here, int is the type, num is the name, and 5 is the value of the variable All variables should be declared before using them 5

Simple Types Simple types include types such as numbers and Boolean (true or false) values There are several types to represent numbers, because different amount of bytes are required for each type 6

Integer Types TypeAlias forAllowed Values# of bytes sbyteSystem.SByteInteger between –128 and 1271 byteSystem.ByteInteger between 0 and 2551 shortSystem.Int16Integer between –32768 to ushortSystem.UInt16Integer between 0 and intSystem.Int32 Integer between –2,147,483,648 and 2,147,483,647 4 uintSystem.UInt32Integer between 0 and 4,294,967,2954 longSystem.Int64 Integer between – and ulongSystem.UInt64 Integer between 0 and u: unsigneds: signed

Floating-Point Value Types TypeAlias forRange# of bytes floatSystem.Single4 doubleSystem.Double8 decimalSystem.Decimal16 8

Precisions TypePrecision float7-8 digits double15-16 digits decimal28 digits 9 The decimal value type is generally used in currencies which require more precision!

Other Simple Types TypeAlias forAllowed Values charSystem.Char Single Unicode character, stored as an integer between 0 and boolSystem.Booleantrue or false stringSystem.StringA sequence of characters 10 Note that char type is stored in 2 bytes and it is Unicode!

Variable Declaration, Assignment, and Printing Example static void Main(string[] args) { int myInteger; string myString; myInteger = 17; myString = "\"myInteger\" is"; Console.WriteLine("{0} {1}.", myString, myInteger); } 11 Two variables are declared here Values are assigned to the variables Variables are displayed on the screen. "myInteger" is 17.

Printing Variable Values Use Console.Write() or Console.WriteLine() methods to display variable values on the screen Console.WriteLine() method adds a new line at the end of the line The methods have several faces to print several types; use the most suitable one 12

Some Console.WriteLine() Faces 13

Printing an int on the screen int x = 17, y = 25; Console.WriteLine(x); Console.WriteLine(x.ToString()); Console.Write(“x = ”); Console.WriteLine(x); Console.WriteLine(“x = ” + x); Console.WriteLine(“x = ” + x.ToString()); Console.WriteLine(“x = {0}, y = {1}.”, x, y); x = 17 x = 17, y = 25.

Variable Naming The first character must be either a letter, or an underscore character (_) Subsequent characters may be letters, underscore character, or numbers. Reserved words can’t be used as variable names – If you want a reserved word as variable name, you can put an at character at the beginning 15

Example: Valid Variable Names myBigVar VAR1 _test i myVariable MyVariable MYVARIABLE 16

Example: Invalid Variable Names a+b 99bottles namespace double my-result 17

Keywords abstractconstexternintoutshorttypeof ascontinuefalseinterfaceoverridesizeofuint basedecimalfinallyinternalparamsstackalloculong booldefaultfixedisprivatestaticunchecked breakdelegatefloatlockprotectedstringunsafe bytedoforlongpublicstructushort casedoubleforeachnamespacereadonlyswitchusing catchelsegotonewrefthisvirtual charenumifnullreturnthrowvoid checkedeventimplicitobjectsbytetruevolatile classexplicitinoperatorsealedtrywhile 18

C# Contextual Keywords addascendingasyncawaitbydescendingdynamic equalsfromgetglobalgroupininto joinletonorderbypartialremoveselect setvaluevarwhereyield 19 Contextual keyword are used in certain language constructs. They can’t be used as identifier in those constructs. Otherwise, they can be used as identifiers.

Variable Naming Conventions Hungarian Notation Camel Case Pascal Case 20

Hungarian Notation Place a lowercase prefix which shows the type of the variable – nAge – iAge – fDelimeter – btnClick – txtName 21

Camel Case Begin first word with lowercase, others with uppercase – age – firstName – lastName – birthDay 22

Pascal Case Start all words with uppercase letters – Age – FirstName – LastName – WinterOfDiscontent 23

Escape Sequences Escape SequenceCharacter ProducedUnicode Value \’Single quotation mark0x0027 \”Double quotation mark0x0022 \\Backslash0x005C \0Null0x0000 \aAlert (causes a beep)0x0007 \bBackspace0x0008 \fForm feed0x000C \nNew line0x000A \rCarriage return0x000D \tHorizontal tab0x0009 \vVertical tab0x000B 24

More About Strings… You can use Unicode values after \u – “Karli\’s string” – “Karli\u0027s string” If you place character before a string, all escape sequences are ignored. – “C:\\inetpub\\wwwroot\\” – “A short list:\nitem 1\nitem 2” short list: item 1 item 2” 25

Variable Declaration and Assignment int age; age = 25; int age = 25; int xSize, ySize; int xSize = 4, ySize = 5; int xSize, ySize = 5; 26

Operators Addition, subtraction, etc. are made using operators Three types of operators: – Unary – Act on single operand – Binary – Act on two operands – Tertiary – Act on three operands 27

Mathematical Operators OperatorCategoryExample +Binaryvar1 = var2 + var3; –Binaryvar1 = var2 – var3; *Binaryvar1 = var2 * var3; /Binaryvar1 = var2 / var3; %Binaryvar1 = var2 % var3; +Unaryvar1 = +var2; –Unaryvar1 = –var2; 28 % : Remainder operator Example: 8 % 3 gives 2.

Increment and Decrement Operators OperatorCategoryExample ++ Unary var1 = ++var2; -- Unary var1 = --var2; ++ Unary var1 = var2++; -- Unary var1 = var2--; 29 Increment first, assign next Assign first, increment next

Exercise int var1, var2 = 5, var3 = 6; var1 = var2++ * --var3; Console.WriteLine("var1={0}, var2={1}, var3={2}", var1, var2, var3); 30 How?

Printing Variable Values int var1 = 3, var2 = 5; Console.WriteLine("var1 = {0}, var2 = {1}", var1, var2); 31 var1 = 3, var2 = 5

Printing Variable Values int var1 = 3, var2 = 5; Console.WriteLine("{0}{1}{0}{1}{1}", var1, var2);

Reading Strings string userName; Console.Write("Your name: "); userName = Console.ReadLine(); Console.WriteLine("Welcome {0}!", userName); 33 Your name: Muzaffer Welcome Muzaffer!

Reading Integers int age; Console.WriteLine("Your age: "); age = int.Parse(Console.ReadLine()); Console.WriteLine("Your age is {0}.", age); 34 Equivalent code: Convert.ToInt32(Console.ReadLine());

Reading Doubles double w; Console.WriteLine("Your weight (in kg.): "); w = double.Parse(Console.ReadLine()); Console.WriteLine("You weigh {0} kg.", w); 35 Equivalent code: Convert.ToDouble(Console.ReadLine());

Assignment Operators OperatorExampleEquivalent =var1 = var2; +=var1 += var2;var1 = var1 + var2; -=var1 -= var2;var1 = var1 – var2; *=var1 *= var2;var1 = var1 * var2; /=var1 /= var2;var1 = var1 / var2; %=var1 %= var2;var1 = var1 % var2; 36

Operator Precedence PrecedenceOperators Highest++, -- (used as prefixes), +, - (unary) *, /, % +, - =, *=, /=, %=, +=, -= Lowest++, -- (used as suffixes) 37

Namespaces.NET way of providing containers – Header files in C and C++ – Packages in Java.NET classes are grouped in namespaces – Sin, Cos, Atan, Acos, Pi, Sqrt, etc. in Math namespace – Int32, Double, etc. in System namespace – Windows Forms classes in System.Windows.Forms – Registry operations in Microsoft namespace You also can write your programs or DLLs in a separate namespace, e.g. using your company name 38

Flow Control Branching (if, switch, ternary operator) Looping (for, while, do-while, foreach) 39

Comparison Operators OperatorMeaning ==equal to !=not equal to <less than >greater than <=less than or equal to >=greater than or equal to 40

Boolean Variables A Boolean variable may take values true or false – bool isWhite = true; – isWhite = false; Comparison results can be stored in Boolean variables – bool isLong = (height > 195); – bool isWhite = (color == Color.White); 41

Fundamental Logical Operators OperatorNameExample &&AND(a > 0) && (a < 10) ||OR(a = 10) !NOT!(a < 100) 42

The ‘if’ Statement int height; Console.Write("Enter your height (in cm.) "); height = int.Parse(Console.ReadLine()); if (height > 190) Console.WriteLine("You are a tall person!"); else Console.WriteLine("Your height is normal!"); 43

if Statement if (expression) ; if (expression) { ; } 44

if..else if (expression) ; else ; If there are more statements, use curly brackets. 45

Some Notes on ‘if’ Parentheses are required, they can’t be omitted Curly braces (‘{’ and ‘}’)should be used if there are more than one statements: if (test) { statement1; statement2; } else part can be omitted if statements can be nested 46

Example: Finding the smallest of 3 integers int a, b, c, min; Console.WriteLine("Enter 3 integers:"); Console.Write("a = "); a = int.Parse(Console.ReadLine()); Console.Write("b = "); b = int.Parse(Console.ReadLine()); Console.Write("c = "); c = int.Parse(Console.ReadLine()); if (a < b) { if (a < c) min = a; else min = c; } else { if (b < c) min = b; else min = c; } Console.WriteLine("The smallest one is {0}.", min); 47

Checking Conditions if (var1 == 1) { // Do something. } else { if (var1 == 2) { // Do something else. } else { if (var1 == 3 || var1 == 4) { // Do something else. } else { // Do something else. } if (var1 == 1) { // Do something. } else if (var1 == 2) { // Do something else. } else if (var1 == 3 || var1 == 4) { // Do something else. } else { // Do something else. } 48

Common Mistakes if (var1 = 1) {…} if (var1 == 1 || 2) {…} 49

The ‘switch’ Statement switch ( ) { case : == > break; case : == > break;... case : == > break; default: != comparisonVals> break; } 50

Example 1 switch (var1) { case 1: // Do something. break; case 2: // Do something else. break; case 3: case 4: // Do something else. break; default: // Do something else. break; } 51

Example 2 switch (option) { case 1: Console.WriteLine(“You select 1”); break; case 2: Console.WriteLine(“You select 2”); break; case 3: Console.WriteLine(“You select 3”); break; default: Console.WriteLine(“Please select an integer between 1 and 3.”); break; } 52

switch Example switch (strProfession) { case "teacher": MessageBox.Show("You educate our young"); break; case "programmer": MessageBox.Show("You are most likely a geek"); break; case "accountant": MessageBox.Show("You are a bean counter"); break; default: MessageBox.Show("Profession not found in switch statement"); break; } 53 In C, only integer values can be used as the expression but in C#, strings can be used too. Don’t forget to use breaks!

Example 3 switch (strAnimal) { case “bird”: Console.WriteLine(“It has 2 legs.”); break; case “horse”: case “dog”: case “cat”: Console.WriteLine(“It has 4 legs.”); break; case “centipede”: Console.WriteLine(“It has 40 legs.”); break; case “snake”: Console.WriteLine(“It has no legs.”); break; default: Console.WriteLine(“I don’t know that animal!”); break; } 54

The Ternary Operator ? : Tertiary operator because it acts on 3 operands (remember unary and binary operators acting on 1 and 2 operands resp.) Example: – if (a < b) min = a; else min = b; – min = (a < b) ? a : b; 55

Looping 56

for Loop for (initializers; check_condition; modifying_expressions) { } Example: for (i = 0; i < 10; i++) { Console.WriteLine("i = " + i.ToString()); } 57

while Loop while (expression) { } 58

do-while Loop do { } while (expression); 59

foreach Loop foreach ( in ) { } 60

Displaying Months using for Loop string[] months = new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; for (int i = 0; i < months.Length; i++) { MessageBox.Show(months[i]); } 61

Displaying Months using foreach string[] months = new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; foreach (string month in months) { MessageBox.Show(month); } 62

Exercise Display first ten prime numbers. 63

Interrupting Loops break – ends the loop immediately continue – ends the current loop cycle return – jumps out of the function goto – jumps to the specified location (don’t use) 64

Infinite Loops while (true) { … } 65

Example int num; while (true) { Console.Write(“Enter a number between 1 and 100: ”); num = Convert.ToInt32(Console.ReadLine()); if (num >= 1 && num <= 100) break; else { Console.WriteLine(“It should be between 1 and 100.”); Console.WriteLine(“Please try again!\n”); } 66

Bitwise Operators & (Bitwise AND) | (Bitwise OR) ~ (Bitwise NOT) ^ (Bitwise XOR) 67

Examples 0110 & 0101 = 0100 (1&1=1, otherwise 0) 0110 | 0101 = 0111 (0|0=0, otherwise 1) 0110 ^ 0101 = 0011 (same  0, different  1) ~0110 = 1001 (0  1, 1  0) 68

Examples option = Location.Left | Location.Bottom; if (option & Location.Left != 0) MessageBox.Show(“Indented to left.”); if (option & Location.Bottom != 0) MessageBox.Show(“Indented to right.”); 69

Shift Operators >> (Shift right) << (Shift left) >>= <<= 70

Examples int a = 16; int b = a >> 2; // b becomes 4 int c = a << 4; // c becomes 256 a >>= 2; // a becomes 4 a <<= 4; // a becomes 64 71