Introduction to C# Applications

Similar documents
Introduction to C# Applications Pearson Education, Inc. All rights reserved.

C: How to Program. Week /Mar/05

Chapter 2 - Introduction to C Programming

IT 374 C# and Applications/ IT695 C# Data Structures

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Introduction to C# Apps

Chapter 2: Using Data

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

.Net Technologies. Components of.net Framework

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Visual C# Instructor s Manual Table of Contents

Chapter 1 & 2 Introduction to C Language

Introduction to Programming

Full file at C How to Program, 6/e Multiple Choice Test Bank

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Creating a C++ Program

6.096 Introduction to C++ January (IAP) 2009

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Introduce C# as Object Oriented programming language. Explain, tokens,

Getting started 7. Storing values 21. Creating variables 22 Reading input 24 Employing arrays 26 Casting data types 28 Fixing constants 30 Summary 32

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

C#: framework overview and in-the-small features

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Fundamental of Programming (C)

Programming in C++ 4. The lexical basis of C++

Course Outline. Introduction to java

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

Chapter 1 Introduction to Computers and C++ Programming

Programming. C++ Basics

Programming for Engineers Introduction to C

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.8. Decision Making: Equality and Relational Operators

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Fundamentals of Programming

Data types, variables, constants

Chapter 2: Using Data

Program Fundamentals

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Course PJL. Arithmetic Operations

BASIC ELEMENTS OF A COMPUTER PROGRAM

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

This tutorial has been prepared for the beginners to help them understand basics of c# Programming.

Introduction to Java Applications; Input/Output and Operators

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

DEPARTMENT OF MATHS, MJ COLLEGE

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 2, Part I Introduction to C Programming

Basic Types, Variables, Literals, Constants

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

IS 0020 Program Design and Software Tools

COMP 202 Java in one week

The C++ Language. Arizona State University 1

Copyright 1999 by Deitel & Associates, Inc. All Rights Reserved.

3. Java - Language Constructs I

Fundamentals of Programming Session 4

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Chapter 2: Using Data

Advanced Computer Programming

BITG 1233: Introduction to C++

Computer Components. Software{ User Programs. Operating System. Hardware

Objectives. In this chapter, you will:

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS242 COMPUTER PROGRAMMING

UNIT- 3 Introduction to C++

Programming and Data Structures

Section 2.2 Your First Program in Java: Printing a Line of Text

Java Notes. 10th ICSE. Saravanan Ganesh

DigiPen Institute of Technology

A Fast Review of C Essentials Part I

Lecture 3 Tao Wang 1

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Chapter 6. Simple C# Programs

C# Fundamentals. built in data types. built in data types. C# is a strongly typed language

Unit 3. Operators. School of Science and Technology INTRODUCTION

LECTURE 02 INTRODUCTION TO C++

Basics of Java Programming

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Introduction to Programming

UEE1302 (1102) F10: Introduction to Computers and Programming

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

Full file at

Tokens, Expressions and Control Structures

Chapter 2 Elementary Programming

Chapter 02: Using Data

Data Types and Variables in C language

Computers and Programming Section 450. Lab #1 C# Basic. Student ID Name Signature

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Language Fundamentals Summary

Transcription:

1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making statements. To use relational and equality operators. // indicates the remainder 1 // Fig. 3.1: Welcome1.cs of the line is a using comment directive 2 // Text-printing application. helps compiler Begins a class locate a class declaration 5 public class Welcome1 6 { Main is the 7 // Main method begins execution of C# application starting point of 8 public static void Main( string[] args ) every application 9 { 10 Console.WriteLine( "Welcome to C# Programming!" ); 11 } // end method Main 12 } // end class Welcome1 Welcome to C# Programming! Print a string 3 1 // Fig. 3.1: Welcome1.cs 2 // Text-printing application. Comments start with: // Comments ignored during program execution Document and describe code Provides code readability Traditional comments: /*... */ 5 6 Keyword: using Helps the compiler locate a class that program will use Identifies pre-defined class All using directives must appear before any other code (except comments) in a C# source code file; otherwise a compilation error occurs. Blank line Makes program more readable Blank lines, spaces, and tabs are white-space characters Ignored by compiler 5 public class Welcome1 Begins class declaration for class Welcome1 Every C# program has at least one user-defined class Keyword: words reserved for use by C# class keyword followed by class name Naming classes: capitalize every word SampleClassName 1

C# Keywords abstract as Base bool break byte case Catch char checked class const Continue decimal default delegate do Double else enum event explicit Extern false finally fixed float For foreach goto if implicit In int interface internal is Lock long namespace new null Object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while 7 C# identifier Series of characters consisting of letters, digits and underscores ( _ ) Does not begin with a digit, has no spaces Valid: Welcome1, identifier, _value, button7 7button is invalid C# is case sensitive (capitalization matters) a1 and A1 are different 8 Fig. 3.2 C# keywords. 7 public 7 public static void Main( void string[] Main( args ) string[] args ) 9 10 Console.WriteLine("Welcome to C# Programming!"); 10 Part of every C# console application Applications begin executing at Main Parentheses indicate Main is a method (Ch. 3 and 6) C# applications contain one or more methods Exactly one method must be called Main Methods can perform tasks and return information void means Main returns no information Instructs computer to perform an action Prints string of characters String: series characters inside double quotes White-spaces in strings are not ignored by compiler Method Console.WriteLine Standard output Print to command window (i.e., MS-DOS prompt) Displays line of text This line is known as a statement Statements must end with semicolon ; 3. Modifying Your Simple C# Application 11 12 1 // Fig. 3.1: Welcome2.cs 2 // Printing one line of text with multiple statements. 5 public class Welcome2 6 { 7 // Main method begins execution of C# application 8 public static void Main( string[] args ) 9 { 10 Console.Write( "Welcome to " ); Cursor stays on same line after outputting 11 Console.WriteLine( "C# Programming!" ); 12 } // end method Main Cursor moves to next line after outputting 13 } // end class Welcome2 Welcome to C# Programming! Escape sequence Description \n Newline. Positions the screen cursor at the beginning of the next line. \t Horizontal tab. Moves the screen cursor to the next tab stop. \r Carriage return. Positions the screen cursor at the beginning of the current line does not adsvance the cursor to the next line. Any characters output after the carriage return overwrite the characters previously output on that line. \\ Backslash. Used to place a backslash character in a string. \" Double quote. Used to place a double-quote character (") in a string. For example, Console.Write( "\"in quotes\"" ); displays "in quotes" Escape characters Backslash ( \ ) Indicates special characters be output 2

1 // Fig. 3.18: Addition.cs 2 // Displaying the sum of two numbers input from the keyboard. using declaration imports necessary components from the System 5 public class Addition namespace. 6 { 7 // Main method begins execution of C# application 8 public static void Main( string[] args ) 9 { 10 int number1; // declare first number to add 11 int number2; // declare second number to add 12 int sum; // declare sum of number1 and number2 13 1 Console.Write( "Enter first integer: " ); // prompt user 15 // read first number from user 16 number1 = Convert.ToInt32( Console.ReadLine() ); 17 18 Console.Write( "Enter second integer: " ); // prompt user 19 // read second number from user 20 number2 = Convert.ToInt32( Console.ReadLine() ); 21 22 sum = number1 + number2; // add numbers 23 2 Console.WriteLine( "Sum is {0}", sum ); // display sum 25 } // end method Main 26 } // end class Addition Enter first integer: 5 Enter second integer: 72 Sum is 117 Declare variables number1, number2 and sum. Convert user s input into an int, and assign it to number1. Convert user s next input into an int, and assign it to number2. Calculate the sum of the variables number1 and number2, assign result to sum. 13 Integers Variables Location in memory that stores a value Declare with name and type before use Variable name: any valid identifier Declarations end with semicolons ; Initialize variable in its declaration Equal sign: int a = 1; 1 Display the sum using formatted output. 10 int number1; // first number to add 11 int number2; // second number to add 12 int sum; // second number to add Declare variable number1, number2 and sum of type int int holds integer values (whole numbers): i.e., 0, -, 97 Types float, double and decimal can hold decimal numbers Type char can hold a single character: i.e., x, $, \n, 7 int, float, double, decimal and char are simple types Can add comments to describe purpose of variables int number1, // first number to add number2, // second number to add sum; // second number to add Can declare multiple variables of the same type in one declaration Use comma-separated list 15 1 Console.Write("Enter first integer: " );//prompt user Message called a prompt: directs user to perform an action 16 number1 = Convert.ToInt32( Console.ReadLine() ); ReadLine waits for user to type a string of characters Convert.ToInt32 method converts the sequence of characters into data of type int Result of call to ReadLine given to number1 using assignment operator = Assignment statement = is a binary operator - takes two operands Expression on right evaluated and assigned to variable on left Read as: number1 gets the value of Convert.ToInt32( Console.ReadLine() ); 16 18 Console.Write("Enter second integer: " ); // prompt user Similar to previous statement Prompts the user to input the second integer 20 number2 = Convert.ToInt32( (Console.ReadLine() ); Similar to previous statement Assign variable number2 to second integer input 22 sum = number1 + number2; // add numbers Assignment statement Calculates sum of number1 and number2 (right hand side) Uses assignment operator = to assign result to variable sum Read as: sum gets the value of number1 + number2 number1 and number2 are operands 17 2Console.WriteLine( "Sum is {0}: ", sum ); //display sum Use Console.WriteLine to display results {0} is placeholder for sum Console.WriteLine( "Sum is {0} ",(number1 + number2) ); Calculations can also be performed inside WriteLine Parentheses around the expression number1 + number2 are not required 18 3

3.7 Memory Concepts 19 20 Variables Every variable has a name, a type, a size and a value Name corresponds to location in memory When new value is placed into a variable, replaces (and destroys) previous value Reading variables from memory does not change them number1 5 Fig. 3.19 Memory location showing the name and value of variable number1. 21 22 number1 5 number1 5 number2 72 number2 72 sum 117 Fig. 3.20 Memory locations after storing values for number1 and number2. Fig. 3.21 Memory locations after calculating and storing the sum of number1 and number2. 23 2 3.8 Arithmetic Arithmetic calculations used in most programs Usage C# operation Arithmetic operator Algebraic expression C# expression Addition + f + 7 f + 7 * for multiplication / for division % for remainder +, - Subtraction p c p c Multiplication * b m b * m Division / x / y or x y or x y x / y Integer division truncates remainder 7 / 5 evaluates to 1 Remainder operator % returns the remainder Remainder % r mod s r % s 7 % 5 evaluates to 2 Fig. 3.22 Arithmetic operators.

3.8 Arithmetic (Cont.) Operator precedence Some arithmetic operators act before others (i.e., multiplication before addition) Use parenthesis when needed or for clarity Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: ( a + b + c ) / 3 25 Operator(s) Operation(s) Order of evaluation (associativity) Evaluated first * / % Evaluated next + - Multiplication Division Remainder Addition Subtraction If there are several operators of this type, they are evaluated from left to right. If there are several operators of this Stype, they are evaluated from left to right. 26 Fig. 3.23 Precedence of arithmetic operators. 3.9 Decision Making: Equality and Relational Operators Condition Expression can be either true or false if statement Simple version in this section, more detail later If a condition is true, then the body of the if statement executed Control always resumes after the if statement Conditions in if statements can be formed using equality or relational operators (Fig. 3.25) 27 Standard algebraic equality and relational operators C# equality or relational Soperator Sample C# condition Meaning of C# condition Equality operators = == x == y x is equal to y!= x!= y x is not equal to y Relational operators > > x > y x is greater than y < < x < y x is less than y >= x >= y x is greater than or equal to y <= x <= y x is less than or equal to y 28 Fig. 3.25 Equity and relational operators. 1 // Fig. 3.26: Comparison.cs 2 // Comparing integers using if statements, equality operators, 3 // and relational operators. using System; 5 6 public class Comparison 7 { 8 // Main method begins execution of C# application 9 public static void Main( string[] args ) 10 { Outline Comparison.cs (1 of 2) 29 30 31 if ( number1 > number2 ) 32 Console.WriteLine( "{0} > {1}", number1, number2 ); 33 Compares two numbers 3 if ( number1 <= number2 ) using relational operator >, 35 Console.WriteLine( "{0} <= {1}", number1, number2 ); 36 <= and >=. 37 if ( number1 >= number2 ) 38 Console.WriteLine( "{0} >= {1}", number1, number2 ); 39 } // end method Main Outline Comparison.cs (2 of 2) 30 11 int number1; // declare first number to compare 0 } // end class Comparison 12 int number2; // declare second number to compare 13 Enter first integer: 2 1 //prompt user and read first number 15 Console.Write( "Enter first integer: " ); 16 number1 = Convert.ToInt32( Console.ReadLine() ); 17 Enter second integer: 2 2 == 2 2 <= 2 2 >= 2 18 //prompt user and read second number 19 Console.Write( "Enter second integer: " ); 20 number2 = Convert.ToInt32( Console.ReadLine() ); 21 22 if ( number1 == number2 ) 23 Console.WriteLine( "{0} == {1}", number1, number2 ); 2 25 if ( number1!= number2 ) 26 Console.WriteLine( "{0}!= {1}", number1, number2 ); 27 28 if ( number1 < number2 ) 29 Console.WriteLine( "{0} < {1}", number1, number2 ); Test for equality, display result using WriteLine. Compares two numbers using relational operator <. Enter first integer: 1000 Enter second integer: 2000 1000!= 2000 1000 < 2000 1000 <= 2000 Enter first integer: 2000 Enter second integer: 1000 2000!= 1000 2000 > 1000 2000 >= 1000 5

3.9 Decision Making: Equality and Relational Operators (Cont.) 31 3.9 Decision Making: Equality and Relational Operators (Cont.) 32 Line 6: begins class Comparison declaration Lines 11-12: declare int variables Lines 15-16: prompt the user to enter the first integer and input the value Lines 19-20: prompt the user to enter the second integer and input the value 22 if ( number1 == number2 ) 23 Console.WriteLine( {0} == {1}", number1, number2 ); if statement to test for equality using (==) If variables equal (condition true) Line 23 executes If variables not equal, statement skipped No semicolon at the end of if statement Empty statement No task is performed Lines 25-26, 28-29, 31-32, 3-35 and 37-38 Compare number1 and number2 with the operators!=, <, >, <= and >=, respectively 33 3 Common Programming Error 3.8 Common Programming Error 3.9 Confusing the equality operator, ==, with the assignment operator, =, can cause a logic error or a syntax error. The equality operator should be read as is equal to, and the assignment operator should be read as gets or gets the value of. To avoid confusion, some people read the equality operator as double equals or equals equals. It is a syntax error if the operators ==,!=, >= and <= contain spaces between their symbols, as in = =,! =, > = and < =, respectively. Reversing the operators!=, >= and <=, as in =!, => and =<, is a syntax error. 6