Industrial Informatics Course 2 C basics DeliaAlexandrina Mitrea
Industrial Informatics Course 2 C# basics Delia-Alexandrina Mitrea, Assoc. Prof. , Eng. , Ph. D
Topics • Constants and literals - Integer literals, floating point literals, character constants, string literals, defining constants • Operators - Arithmetic operators, relational operators, logical operators, bitwise operators, assignment operators, miscellaneous operators, operator precedence • C# control structures - Decision making: if statements, the ? : (conditional) operator - Loops: while, for, do-while • Arrays in C#
Constants and literals q Integer literals • an integer literal – a decimal, octal or hexadecimal constant • can also have a suffix that is a combination of U and L unsigned and long; can be uppercase or lowercase; order is not important ØExamples of integer literals 212 215 u 0 x. Fee. L 078 032 UU /* Legal */ /* Illegal: 8 is not an octal digit */ /* Illegal: cannot repeat a suffix */
Ø Other examples of Integer literals: 85 0213 0 x 4 b 30 30 u 30 l 30 ul /* /* decimal */ octal */ hexadecimal */ int */ unsigned int */ long */ unsigned long */ • Octal: starts with “ 0” • Hexadecimal: starts with “ 0 x”
q Floating point literals Ø Has an integer part, a decimal point, a fractional part, and an exponent part Ø You can represent floating point literals either in decimal form or exponential form Ø Examples of floating point literals 3. 14159 /* Legal */ - decimal form 314159 E-5 L /* Legal */ - exponential form 510 E /* Illegal: incomplete exponent */ 210 f /* Illegal: no decimal or exponent */. e 55 /* Illegal: missing integer or fraction */ - decimal form
q Character constants • enclosed in single quotes – ex. : ‘x ‘ • can be stored in a single variable of char type • can be a plain text: ‘x’, an escape sequence: ‘t’ or a universal character ‘u 02 C 0’ • some characters are preceded by a backslash: ‘’
Ø Example: =>
q String literals • String literals or constants - enclosed in double quotes "" or with @"". • A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. • can break a long line into multiple lines using string literals and separating the parts using white-spaces Ø Example: "hello, dear" "hello, @"hello dear" " "d" "ear" dear"
q Declaring a constant const <data_type> <constant_name> = value; Ø Example:
Operators Ø Arithmetic Operators Ø Relational Operators Ø Logical Operators Ø Bitwise Operators Ø Assignment Operators Ø Miscellaneous Operators
q Arithmetic operators
q The Increment Operator (Unary) • Allows incrementing the value of a variable by 1. • The timing of the effect of this operator depends upon which side of the expression it's on • A post-increment (postfix) example: int count; int index = 6; count = index++; // count = 6, index = 7 • The ++ operator comes after the expression index => it's called a post-increment operator. • First the assignment takes place, and then index is incremented. • An example of a pre-increment (prefix) operator: • First the index is incremented, then the assignment takes place int count; int index = 6; count = ++index; // count = 7, index = 7 q The Decrement Operator (Unary) • Allows decrementing the value of a variable. The timing of the effect of this operator again depends upon which side of the expression it is on • A post-decrement (postfix) example: int count; int index = 6; count = index--; // count = 6, index = 5 • The -- operator comes after the expression index, and that's why it's called a post-decrement (postfix) operator. • Here's an example of a pre-decrement (prefix) operator: int count; int index = 6; count = --index; // count = 5, index = 5
q The Unary Plus (+) Operator • Has no effect on the expression it's used with. • Why would a language have an operator that has no effect? => For consistency (most C# operators have a logical complement) => unary plus is the complement of unary minus. • Examples: int negative = -1; int positive = 1; int result; result = +negative; // result = -1 result = +positive; // result = 1 q The Unary Minus (-) Operator • Allows the negation of a variable's value. • In integer and decimal types, the result is the number subtracted from 0. • For floating-point types, the “–” operator inverts the sign of the number. • When a value is Na. N (not a number), the result is still Na. N. • Examples: int neg. Int = -1; decimal pos. Dec = 1; float neg. Flt = -1. 1 f; double nan. Dbl = Double. Na. N; int res. Int; decimal res. Dec; float res. Flt; double res. Dbl; res. Int = -neg. Int; // res. Int = 1 res. Dec = -pos. Dec; // res. Dec = -1 res. Flt = -neg. Flt; // res. Flt = 1. 1 res. Dbl = -nan. Dbl; // res. Dbl = NAN
q Relational operators
q Logical operators
q Bitwise operators
Ø The truth tables for &, | and ^ • Assume if A = 60; and B = 13, then in the binary format they are as follows: A = 0011 1100 B = 0000 1101 --------A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011
q Assignment operators
q Assignment operators
q Miscellaneous operators
q Operator precedence
q Operator precedence
Decision making Ø The general form of a typical decision making structure:
Ø The following types of decision making statements:
q The If Statement if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } q The If-else Statement if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ }
q The if. . . else Statement if(boolean_expression 1) { /* Executes when the boolean expression 1 is true */ } else if( boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } else if( boolean_expression 3) { /* Executes when the boolean expression 3 is true */ } else { /* executes when the none of the above condition is true */ }
q Nested If statements if(boolean_expression 1) { /* Executes when the boolean expression 1 is true */ if(boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } }
q The Switch Statement • Syntax: switch(expression){ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s); }
Ø Rules (Switch statement): The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type. � You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. � The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. q When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. � When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. � Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. � A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
Ø Example (Switch statement) using System; namespace Decision. Making { class Program { static void Main(string[] args) { /* local variable definition */ char grade = 'B'; switch (grade) { case 'A': Console. Write. Line("Excellent!"); break; case 'B': case 'C': Console. Write. Line("Well done"); break; case 'D': Console. Write. Line("You passed"); break; case 'F': Console. Write. Line("Better try again"); break; default: Console. Write. Line("Invalid grade"); break; } Console. Write. Line("Your grade is {0}", grade); Console. Read. Line(); } } } => Well done Your grade is B
q The ? : Operator (The conditional operator) • can be used to replace if. . . else statements Ø General form: Exp 1 ? Exp 2 : Exp 3; • Exp 1, Exp 2, Exp 3 - expressions Ø The value of a ? expression is determined as follows: • Exp 1 is evaluated. • If it is true, then Exp 2 is evaluated and becomes the value of the entire ? expression. • If Exp 1 is false, then Exp 3 is evaluated and its value becomes the value of the expression.
Loops A loop statement - allows us to execute a statement or a group of statements multiple times Ø The general form of a loop statement in most of the programming languages: Ø
Ø The following types of loops in C#: § While loop: It repeats a statement or a group of statements while a given condition is true. It tests the condition before executing the loop body. § For loop: It executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. § Do. . . while loop: similar to a while statement, except that it tests the condition at the end of the loop body § Nested loops: You can use one or more loops inside any another while, for or do. . while loop.
Ø The While Loop • repeatedly executes a target statement (or group of statements) as long as a given condition is true • Syntax: while(condition) { statement(s); } § Statement(s) may be a single statement or a block of statements. § The condition - may be any expression, and true is any non-zero value. § The loop iterates while the condition is true. § When the condition becomes false, program control passes to the line immediately following the loop.
Ø Example: using System; namespace Loops { class Program { static void Main(string[] args) { /* local variable definition */ int a = 10; /* while loop execution */ while (a < 20) { Console. Write. Line("value of a: {0}", a); a++; } Console. Read. Line(); } } }
Ø The For Loop • a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times § Syntax: for(init; condition; increment) { statement(s); }
q The flow of control in a for loop: 1. The init step - executed first, and only once. It allows you to declare and initialise any loop control variables. You are not required to put a statement here, as long as a semicolon appears. 2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. 3. After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. 4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again testing for a condition). • After the condition becomes false, the for loop terminates.
Ø Example: using System; namespace Loops { class Program { static void Main(string[] args) { /* for loop execution */ for (int a = 10; a < 20; a = a + 1) { Console. Write. Line("value of a: {0}", a); } Console. Read. Line(); } } }
Ø The Do…While Loop • The do. . . while loop checks its condition at the end of the loop • Similar to a while loop, except that a do. . . while loop is guaranteed to execute at least one time • Syntax do { statement(s); }while( condition ); § The conditional expression appears at the end of the loop => the statement(s) in the loop execute once before the condition is tested. • If the condition is true => the flow of control jumps back up to do, and the statement(s) in the loop execute again. The process repeats until the condition becomes false.
Arrays An array - stores a fixed-size sequential collection of elements of the same type. • An array - used to store a collection of data • It is often more useful to think of an array as a collection of variables of the same type • All arrays consist of contiguous memory locations; The lowest address corresponds to the first element and the highest address to the last element • Ø Declaring arrays datatype[] array. Name; datatype is used to specify the type of elements in the array. [ ] specifies the rank of the array. The rank specifies the size of the array. Name specifies the name of the array. Ø Example: double[] balance;
Ø Initialising an array Declaring an array - does not initialize the array in the memory • When the array variable is initialised => you can assign values to the array • Array - a reference type => you need to use the new keyword to create an instance of the array • Example: • double[] balance = new double[10]; Ø Assigning values to an array • You can assign values to individual array elements, by using the index number: double[] balance = new double[10]; balance[0] = 4500. 0; • You can assign values to the array at the time of declaration: double[] balance = { 2340. 0, 4523. 69, 3421. 0};
Ø Create and initialise an array as shown: int [] marks = new int[5] { 99, 98, 92, 97, 95}; Ø The size of the array might also be omitted: int [] marks = new int[] { 99, 98, 92, 97, 95}; Ø You can copy an array variable into another target array variable • Both the target and source point to the same memory location: int [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks; Ø When an array is created in C# => the compiler implicitly initialises each array element to a default value depending on the array type. • For example, for an int array, all elements are initialised to 0.
Ø Accessing array elements • An element is accessed by indexing the array name placing the index of the element within square brackets after the name of the array. • Example, double salary = balance[9]; • Example: using System; namespace Array. Application { class My. Array { static void Main(string[] args) { int [] n = new int[10]; int i, j; /* initialize elements of array n */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; } /* output each array element's value */ for (j = 0; j < 10; j++ ) { Console. Write. Line("Element[{0}] = {1}", j, n[j]); } Console. Read. Key(); } } }
§ Use the Foreach loop • Use the foreach statement to iterate through an array: using System; namespace Array. Application { class My. Array { static void Main(string[] args) { int [] n = new int[10]; int i, j; /* initialize elements of array n */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; } /* output each array element's value */ foreach (int j in n ) { int i = j-100; Console. Write. Line("Element[{0}] = {1}", i, j); i++; } Console. Read. Key(); }//main }//class }//namespace
References • „C# Programming, object-oriented programming”, Copyright Tutorials. Point, 2014, http: //www. tutorialspoint. com/csharp_tutorial. pdf
Thank you for your attention!
- Slides: 46