Programming I Lectures PDF
Document Details
Uploaded by GreatBowenite5307
Assiut University
Prof. Dr. Khaled F. Hussain
Tags
Summary
These lecture notes provide a foundational overview of computer languages. It begins by describing machine language, assembly language, and high-level languages, including examples using C#. Basic programming concepts are also introduced.
Full Transcript
Course Title: : Programming I Prof. Dr. Khaled F. Hussain An Overview of Computers and Programming Languages Computer Languages Machine language The language of a computer, called machine language, is a sequence of 0s and 1s. To see how instructions are written in machine language, su...
Course Title: : Programming I Prof. Dr. Khaled F. Hussain An Overview of Computers and Programming Languages Computer Languages Machine language The language of a computer, called machine language, is a sequence of 0s and 1s. To see how instructions are written in machine language, suppose you want to use the equation: wages = rate · hours to calculate weekly wages. Further, suppose that the binary code 100100 stands for load, 100110 stands for multiplication, and 100010 stands for store. In machine language, you might need the following sequence of instructions to calculate weekly wages: 100100 010001 100110 010010 100010 010011 Computer Languages (Cont.) Assembly language Using assembly language instructions, you can write the equation to calculate the weekly wages as follows: LOAD rate MULT hours STOR wages A program called an assembler translates the assembly language instructions into machine language. Computer Languages (Cont.) High-level languages FORTRAN, COBOL, C, C++, C#, Java, and Python In C#, you write the weekly wages equation as follows: wages = rate * hours; The instruction written in C# is much easier to understand. A program called a compiler translates instructions written in high-level languages into machine code. My first C# program using System; public class HelloWorld { public static void Main(string[] args) { Console.WriteLine ("My first C# program."); } } Sample Run: My first C# program. Processing a Program Use the compiler to: Check that the program obeys the rules Translate into machine language (object program) Linker: Combines object program with other programs to create executable code Loader: Loads executable program into main memory Processing a Program (Cont.) The Problem Analysis–Coding–Execution Cycle The Problem Analysis–Coding–Execution Cycle (Cont.) Compiler guarantees that the program follows the rules of the language (no syntax errors) Does not guarantee that the program will run correctly Graphic representation of the problem- solving process 11 Programming Tools Three tools are used to convert algorithms into computer programs: Flowchart - Graphically depicts the logical steps to carry out a task and shows how the steps relate to each other. Pseudocode - Uses English-like phrases with some Visual Basic terms to outline the program. Hierarchy chart - Shows how the different parts of a program relate to each other. 12 Algorithm A step-by-step series of instructions for solving a problem (a recipe is an example of an algorithm) 13 Example 1 Design an algorithm to find the perimeter and area of a rectangle Algorithm: Get length of the rectangle Get width of the rectangle Find the perimeter using the following equation: perimeter = 2 * (length + width) Find the area using the following equation: area = length * width Example 1 (Cont.) using System; class RectangleCalculator { static void Main() { double length = 6.0; double width = 4.0; double area; double perimeter; Console.WriteLine("Program to compute and output the perimeter and area of a rectangle."); perimeter = 2 * (length + width); area = length * width; Console.WriteLine("Length = " + length); Console.WriteLine("Width = " + width); Console.WriteLine("Perimeter = " + perimeter); Console.WriteLine("Area = " + area); } } Example 2 How many stamps do you use when mailing a letter? One rule of thumb is to use one stamp for every five sheets of paper or fraction. 16 Algorithm 1. Request the number of sheets of paper; call it Sheets. (input) 2. Divide Sheets by 5. (processing) 3. Round the quotient up to the next highest whole number; call it Stamps. (processing) 4. Reply with the number Stamps. (output) 17 Flowcharts Graphically depict the logical steps to carry out a task and show how the steps relate to each other. 18 Flowchart symbols 19 Flowchart symbols 20 Flowchart example 21 Pseudocode Uses English-like phrases with some C# terms to outline the task. 22 Pseudocode example Determine the proper number of stamps for a letter Read Sheets (input) Set the number of stamps to Sheets / 5 (processing) Round the number of stamps up to the next whole number (processing) Display the number of stamps (output) 23 Hierarchy charts example 24 Divide-and-conquer method Used in problem solving – take a large problem and break it into smaller problems solving the small ones first Breaks a problem down into modules 25 Examples Write a program to calculate the volume of material in a pipe. Examples (Cont.) An old-style movie theater has a simple profit function. Each customer pays 50 pounds per ticket. Every performance costs the theater 500 pounds, plus 5 pounds per attendee. Write a program to calculate how much income the attendees produce. Examples (Cont.) The program prompts the user to enter a Fahrenheit temperature; it then prints the equivalent Celsius temperature. Examples (Cont.) Draw the Flowchart and write the Pseudocode for solving two simultaneous linear equations in two unknowns. The equations to be solved are: Examples (Cont.) Draw the Flowchart and write the Pseudocode for a weather forecasting program that writes the text shown in the rows and columns of the following table, depending on values of temperature and pressure supplied by the user. Define high temperatures to be above 20.0°C and high pressures to be above 1000,0 millibar. High pressure Low pressure High temperature Clear skies and hot Warm with rain Low temperature Clear skies and cold Snow Examples (Cont.) Write a program that calculates the taxi fee. The fee below 1500 meters is 10 pounds and 5 pounds for each 500 meters above 1500. Write a program that finds the intersection between two lines: ax + by = c and dx+ey=f. Examples (Cont.) Checking Even or Odd using System; class EvenOddChecker { static void Main() { int num; Console.Write("Enter a number: "); num = int.Parse(Console.ReadLine()); if (num % 2 == 0) { Console.WriteLine(num + " is even."); } else { Console.WriteLine(num + " is odd."); } }} Examples (Cont.) Swapping Two Numbers using System; class SwapNumbers { static void Main() { int a, b, temp; Console.Write("Enter value for a: "); a = int.Parse(Console.ReadLine()); Console.Write("Enter value for b: "); b = int.Parse(Console.ReadLine()); Console.WriteLine("Before swapping: a = " + a+ ", b = " + b); temp = a; a = b; b = temp; Console.WriteLine("After swapping: a = " + a + ", b = " + b); }} Programming Methodologies Structured Programming Dividing a problem into smaller subproblems is called structured design. Each subproblem is then analyzed, and a solution is obtained to solve the subproblem. The solutions to all the subproblems are then combined to solve the overall problem. Object-Oriented Programming Object-oriented design (OOD) is a widely used programming methodology. In OOD, the first step in the problem-solving process is to identify the components called objects, which form the basis of the solution, and to determine how these objects interact with one another. For example, suppose you want to write a program that automates the dvd rental process for a local dvd store. The two main objects in this problem are the dvd and the customer. Course Title: : Programming I Prof. Dr. Khaled F. Hussain Basic Elements of C# Comments The program that you write should be clear not only to you, but also to the reader of your program. Comments are for the reader, not for the compiler. So, when a compiler compiles a program to check for the syntax errors, it completely ignores comments. There are two common types of comments in a C# program single-line comments Single-line comments begin with // and can be placed anywhere in the line. Console.WriteLine(" 7 + 8 = " + 15); //prints: 7 + 8 = 15 multiple-line comments. Multiple-line comments are enclosed between. The compiler ignores anything that appears between. Tokens The smallest individual unit of a program written in any language is called a token. C++’s tokens are divided into Special Symbols + - * /. ; ? , = Reserved Words (Keywords) int, float, double, char, const, void, return…etc. Identifiers Consist of letters, digits, and the underscore character (_) Must begin with a letter or underscore C++ is case sensitive The following are legal identifiers in C++: first conversion payRate Whitespaces Include blanks, tabs, and newline characters Can be used to make the program readable Data Types Integral Types: byte: 8-bit unsigned integer (0-255) sbyte: 8-bit signed integer (-128 to 127) short: 16-bit signed integer (-32,768 to 32,767) ushort: 16-bit unsigned integer (0-65,535) int: 32-bit signed integer (-2,147,483,648 to 2,147,483,647) uint: 32-bit unsigned integer (0-4,294,967,295) long: 64-bit signed integer (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807) ulong: 64-bit unsigned integer (0-18,446,744,073,709,551,615) Data Types (Cont.) Floating-Point Types: float: 32-bit floating-point number double: 64-bit floating-point number decimal: 128-bit floating-point number (suitable for financial calculations) Boolean Type: bool: Represents a boolean value (true or false) Character Type: char: Represents a single Unicode character Data Types (Cont.) Enumerated Types: Define a set of named constants. Classes Blueprints for creating objects. Structs Often used for simple data structures. Arrays Ordered collections of elements of the same type. Strings Represent sequences of characters. Arithmetic Operators, Operator Precedence, and Expressions C++ arithmetic operators: +,-,?*,/,% Operators can be unary or binary Mixed expression: Has operands of different data types Contains integers and floating-point 6 / 4 + 3.9 Type Conversion (Casting) Implicit type Conversion: when value of one type is automatically changed to another type int intValue = 10; double doubleValue = intValue; Cast operator: provides explicit type conversion double pi = 3.14159; int intValue = (int)pi; // intValue will be 3 Mixed Expression 3 / 2 + 5.5 = 1 + 5.5 = 6.5 15.6 / 2 + 5 = 7.8 + 5 = 12.8 Precedence Precedence (Cont.) i + j * k is equivalent to i + (j * k) -i * - j is equivalent to (-i) * (-j) +i + j / k is equivalent to (+i ) + (j / k) Expressions formulate the following expressions as programs: ab – c (m + n) (x + y) (ab / c) 3n2 +2n + 1 n2 + 10 (1/2) · n2 + 20 2 - (1/n) Assignment Operators i = 5; j = i; k =10*i+ j ; i = j = k = 0; // (i = (j = (k = 0))) Assignment Operators (Cont.) i=i+2; i+=2; v +=e adds v to e, storing the result in v v -= e subtracts e from v, storing the result in v v*= e multiplies v by e, storing the result in v v/= e divides v by , storing the result in v v%= e computes the remainder when v is divided by e, storing the result in v i+=j+=k; // i+=(j+=k); string Type In C#, a string is a sequence of characters. It's a reference type, meaning it stores a reference to the actual characters in memory. Strings are immutable, which means their content cannot be changed once created. string greeting = "Hello, world!"; Each character has relative position in string Position of first character is 0 “Faculty of" position of ‘F’ is 0 The length of “Faculty of" is 10 Allocating Memory with Constants and Variables Named constant: A memory location whose content is not allowed to change during program execution. const dataType identifier = value; const double CONVERSION = 2.54; const int NO_OF_STUDENTS = 20; const char BLANK = ' '; Allocating Memory with Constants and Variables (Cont.) Variable: A memory location whose content may change during program execution. The syntax for declaring one variable or multiple variables is: dataType identifier, identifier,...; double amountDue; int counter; char ch; int x, y; string name; Assignment Statement The assignment statement takes the following form: variable = expression; = is called the assignment operator int num1, num2; double sale; char first; string str; num1 = 4; num2 = 4 * 5 - 11; sale = 0.02 * 1000; first = 'D'; str = "It is a sunny day."; Input (Read) Statement Console.WriteLine("Enter your name:"); string name = Console.ReadLine(); Console.WriteLine("Hello, " + name + "!"); In this example, the Console.WriteLine method first displays a prompt asking the user to enter their name. Then, Console.ReadLine() waits for the user to type their name and press Enter. The entered name is stored in the name variable. Finally, another Console.WriteLine statement is used to greet the user using their name. Input (Read) Statement (Cont.) Reading Numeric Input: Console.WriteLine("Enter a number:"); int number = int.Parse(Console.ReadLine()); Console.WriteLine("You entered: " + number); In this example, Console.ReadLine() reads the user's input as a string. The int.Parse method then converts the string to an integer. If the input is not a valid integer, it will throw a FormatException. Handling Input Errors It's important to handle potential input errors gracefully. You can use a try-catch block to catch exceptions like FormatException if the user enters invalid input. Console.WriteLine("Enter a number:"); int number; try { number = int.Parse(Console.ReadLine()); Console.WriteLine("You entered: " + number); } catch (FormatException ex) { Console.WriteLine("Invalid input. Please enter a valid number."); } In this example, the try block attempts to parse the input as an integer. If the parsing fails, the catch block is executed, and an error message is displayed. Increment and Decrement Operators Pre-increment: ++variable Post-increment: variable++ Pre-decrement: --variable Post-decrement: variable-- What is the difference between the following? x = 10; x = 10; y = ++x; y = x++; Output Console.WriteLine("Hello, world!"); This code will output the message "Hello, world!" to the console. Formatting Output: You can format the output using placeholders and string interpolation. Using placeholders: int age = 30; string name = "John"; Console.WriteLine("My name is {0} and I'm {1} years old.", name, age); Output (Cont.) Using string interpolation: int age = 30; string name = "John"; Console.WriteLine($"My name is {name} and I'm {age} years old."); You can use Console.Write() to write text to the console without adding a newline character. Commonly Used Escape Sequences EXAMPLE string text = "This is a line.\nThis is another line."; Console.WriteLine(text); The output of the statements is: This is a line. This is another line. string quote = "He said, \"Hello there!\""; Console.WriteLine(quote); The output of the statements is: He said, "Hello there!" namespace Namespaces are a mechanism used to organize and group related classes, structs, and enums. They help prevent naming conflicts and improve code organization. Key Benefits of Using Namespaces: Avoid naming conflicts: By placing related types in separate namespaces, you can avoid naming conflicts that might occur if you had all your types in a single, flat namespace. Improve code organization: Namespaces provide a logical structure for your code, making it easier to navigate and understand. Encapsulate functionality: You can use namespaces to encapsulate related functionality within a specific context. Leverage the.NET Framework: The.NET Framework uses namespaces extensively to organize its classes and APIs. Simple and Compound Assignment Statement Simple Assignment Statement Compound Assignment Statement i = i + 5; i += 5; counter = counter + 1; counter += 1; sum = sum + number; sum += number; amount = amount * (interest + 1); amount *= interest + 1; x = x / ( y + 5); x /= y + 5; Course Title: : Programming I Prof. Dr. Khaled F. Hussain Control Structures Flow of execution A computer can process a program in one of the following ways: a) in sequence; b) selectively, which is also called a branch; c) repetitively, by executing a statement over and over; or d) by calling a function. Selection One-Way Selection Two-Way Selection Compound (Block of) Statements Multiple Selections: Nested if Comparing if...else Statements with a Series of if Statements Conditional statements if (score is greater than or equal to 90) grade is A if (hours worked are less than or equal to 40) wages = rate * hours otherwise wages = (rate * 40) + 1.5 *(rate *(hours – 40)) Relational Operators Each of the relational operators is a binary operator; that is, it requires two operands. They produce false or true when used in expressions. For example, the value of 10 < 11 is true : the value of 11 < 10 is false. ASCII table for the alphabet 'R' > 'T' is false 'A' = 5) && ('A' < 'B’) true (24 >= 35) && ('A' < 'B’) false (14 >= 5) || ('A' > 'B’) true (24 >= 35) || ('A' > 'B’) false ('A' = 60) grade = 'P’; if (number < 0) number = -number; Two-Way Selection if (expression) statement1 else statement2 if (hours > 40.0) wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); else wages = hours * rate; if (score >= 60) Console.WriteLine("Passing" ); Console.WriteLine(" Failing " ); if (score >= 60) Console.WriteLine("Passing" ); else Console.WriteLine(" Failing " ); Compound (Block of) Statements { statement_1 statement_2... statement_n } if (age >= 18) { Console.WriteLine("…..." ); Console.WriteLine("…..." ); } else { Console.WriteLine("…..." ); Console.WriteLine("…..." ); } Multiple Selections: Nested if if (balance > 50000.00) //Line 1 interestRate = 0.07; //Line 2 else //Line 3 if (balance >= 25000.00) //Line 4 interestRate = 0.05; //Line 5 else //Line 6 if (balance >= 1000.00) //Line 7 interestRate = 0.03; //Line 8 else //Line 9 interestRate = 0.00; //Line 10 C# associates an else with the most recent incomplete if—that is, the most recent if that has not been paired with an else. To avoid excessive indentation, the code can be rewritten as follows: if (balance > 50000.00) //Line 1 interestRate = 0.07; //Line 2 else if (balance >= 25000.00) //Line 3 interestRate = 0.05; //Line 4 else if (balance >= 1000.00) //Line 5 interestRate = 0.03; //Line 6 else //Line 7 interestRate = 0.00; //Line 8 if (month == 1) if (month == 1) Console.WriteLine("January" ); Console.WriteLine("January" ); else if (month == 2) if (month == 2) Console.WriteLine("February" ); Console.WriteLine("February" ); else if (month == 3) if (month == 3) Console.WriteLine("March" ); Console.WriteLine("March" ); else if (month == 4) if (month == 4) Console.WriteLine("April" ); Console.WriteLine("April" ); else if (month == 5) if (month == 5) Console.WriteLine("May" ); Console.WriteLine("May" ); else if (month == 6) if (month == 6) Console.WriteLine("June" ); Console.WriteLine("June" ); Short-Circuit Evaluation (i != 0) && (j / i > 0) To find the value of this expression, we must first evaluate (i ! = 0). If i isn‘t equal to 0, then we' ll need to evaluate (j / i > 0) to determine whether the entire expression is true or false. However, if i is equal to 0, then the entire expression must be false, so there's no need to evaluate (j / i > 0). The advantage of short circuit evaluation is apparent-without it. evaluating the expression would have caused a division by zero. i > 0 && ++j > 0 Although j is apparently incremented as a side effect of evaluating the expression, that isn't always the case. If i > 0 is false, then ++j > 0 is not evaluated, so j isn‘t incremented. Avoiding Bugs if (hours > 40.0); It is not a syntax error It is a logical error Conditional Operator (?:) if (a >= b) max = a; else max = b; max = (a >= b) ? a : b; switch Structures switch (expression) { case value1: statements1 break; case value2: statements2 break;... case valuen: statementsn break; default: statements } switch statement switch (grade) { case 'A': Console.WriteLine("The grade point is 4.0."); break; case 'B': Console.WriteLine("The grade point is 3.0."); break; case 'C': Console.WriteLine("The grade point is 2.0."); break; case 'D': Console.WriteLine("The grade point is 1.0."); break; case 'F': Console.WriteLine("The grade point is 0.0."); break; default: Console.WriteLine("The grade is invalid."); break; } while Looping (Repetition) Structure while (expression) statement i = 0; while (i = 1; i--) Console.WriteLine(i); You can increment (or decrement) the loop control variable by any fixed number. for (i = 1; i = 3, of this sequence is given by: an = an-1 + an-2 for (counter = 3; counter 5) return 2 * x; return 0; // Or you can throw an exception if you prefer } Simulate Dice Roll Example Write a function that rolls a pair of dice until the sum of the numbers rolled is a specific number. public static int SimulateDiceRoll(int targetNumber) { Random random = new Random(); int die1, die2, sum, rollCount = 0; do { die1 = random.Next(1, 7); die2 = random.Next(1, 7); sum = die1 + die2; rollCount++; } while (sum != targetNumber); return rollCount; } PALINDROME NUMBER Example public static bool IsNumPalindrome(int num) { int pwr = 0; if (num < 10) return true; else { while (num / (int)Math.Pow(10, pwr) >= 10) pwr++; while (num >= 10) { int tenTopwr = (int)Math.Pow(10, pwr); if ((num / tenTopwr) != (num % 10)) return false; else { num = num % tenTopwr; num = num / 10; pwr = pwr - 2; } } return true; } } Example Finding the largest of three numbers Example Reading two numbers and an operation: +, -, *, or / and printing the result. Example Write a while loop that has the same output as the following program segment: for (number = 1; number = 0; counter--) { Console.Write(item[counter] + " "); }}} Sample Run: In this sample run, the user input is shaded. Enter five numbers: 12 76 34 52 89 The sum of the numbers is: 263 The numbers in reverse order are: 89 52 34 76 12 Initialization During declaration: int[] numbers = new int { 10, 20, 30, 40, 50 }; After declaration: int[] numbers = new int; numbers = 10; numbers = 20; … Some Restrictions on Array Processing To copy one array into another array, you must copy it component-wise—that is, one component at a time. This can be done using a loop, such as the following: for (int index = 0; index < 5; index ++) yourList[index] = myList[index]; yourList = int.Parse(Console.ReadLine()); //illegal To read data into yourList, you must read one component at a time, using a loop such as the following: for (int index = 0; index < 5; index ++) yourList[index]= int.Parse(Console.ReadLine()); Arrays as Parameters to Functions In C#, you can pass entire arrays as arguments to functions. This allows you to manipulate the array elements within the function and potentially modify the original array. Syntax: void FunctionName(data_type[] arrayName) { // Function body} void PrintArray(int[] numbers) { foreach (int number in numbers) { Console.WriteLine(number); } } When you pass an array to a function, it's actually passed by reference. This means that any changes made to the array within the function will also be reflected in the original array. void ModifyArray(int[] numbers) { numbers = 100; } //... int[] myArray = { 1, 2, 3 }; ModifyArray(myArray); Console.WriteLine(myArray); // Output: 100 Base Address of an Array and Array in Computer Memory The base address of an array is the address (that is, the memory location) of the first array component. Consider the following statements: int[] myList = new int; The base address of the array myList is the address of the component myList. Suppose that the base address of the array myList is 1000. Then, the address of the component myList is 1000 Typically, the memory allocated for an int variable is four bytes. It follows that the starting address of myList is 1004, the starting address of myList is 1008, and so on Searching an Array for a Specific Item static int SeqSearch(int[] list, int listLength, int searchItem) { int loc; bool found = false; loc = 0; while (loc < listLength && !found) { if (list[loc] == searchItem) { found = true; } else { loc++; } } if (found) { return loc; } else { return -1; }} Program illustrates how to use a sequential search using System; class Program { const int ARRAY_SIZE = 10; static void Main(string[] args) { int[] intList = new int[ARRAY_SIZE]; int number; Console.WriteLine("Enter " + ARRAY_SIZE + " integers."); for (int index = 0; index < ARRAY_SIZE; index++) { intList[index] = int.Parse(Console.ReadLine()); } Console.WriteLine(); Console.Write("Enter the number to be searched: "); number = int.Parse(Console.ReadLine()); Console.WriteLine(); Program illustrates how to use a sequential search (Cont.) int pos = SeqSearch(intList, ARRAY_SIZE, number); if (pos != -1) { Console.WriteLine(number + " is found at position " + pos); } else { Console.WriteLine(number + " is not in the list."); } } } Parallel Arrays Two (or more) arrays are called parallel if their corresponding components hold related information. Suppose you need to keep track of students’ course grades, together with their ID numbers, The statements: int[] studentId = new int; char[] courseGrade = new char; declare these two arrays. Two- and Multidimensional Arrays Accessing Array Components The statement: sales[5, 3] = 25.75; stores 25.75 into row number 5 and column number 3 (that is, the sixth row and the fourth column) of the array sales Two-Dimensional Array Initialization During Declaration This statement declares matrix to be a two-dimensional array of three rows and four columns. Processing two-dimensional arrays Initialization Suppose that you want to initialize row number 4, that is, the fifth row, to 0. The following for loop does this: row = 4; for (col = 0; col < NUMBER_OF_COLUMNS; col++) matrix[row, col] = 0; If you want to initialize the entire matrix to 0 for (row = 0; row < NUMBER_OF_ROWS; row++) for (col = 0; col < NUMBER_OF_COLUMNS; col++) matrix[row, col] = 0; Processing two-dimensional arrays (Cont.) Print The following nested for loops print the components of matrix, one row per line: for (row = 0; row < NUMBER_OF_ROWS; row++) { for (col = 0; col < NUMBER_OF_COLUMNS; col++) Console.Write(matrix[row, col] + " "); Console.WriteLine(matrix[row, col] + " "); } Processing two-dimensional arrays (Cont.) Input The following for loop inputs the data into row number 4, that is, the fifth row of matrix: row = 4; for (col = 0; col < NUMBER_OF_COLUMNS; col++) matrix[row, col] = int.Parse(Console.ReadLine()); The following for loop inputs data into each component of matrix: for (row = 0; row < NUMBER_OF_ROWS; row++) for (col = 0; col < NUMBER_OF_COLUMNS; col++) matrix[row, col] = int.Parse(Console.ReadLine()); Processing two-dimensional arrays (Cont.) Sum by Row The following for loop finds the sum of row number 4 of matrix; that is, it adds the components of row number 4. sum = 0; row = 4; for (col = 0; col < NUMBER_OF_COLUMNS; col++) sum = sum + matrix[row, col]; Following is the C# code to find the sum of each individual row: //Sum of each individual row for (row = 0; row < NUMBER_OF_ROWS; row++) { sum = 0; for (col = 0; col < NUMBER_OF_COLUMNS; col++) sum = sum + matrix[row, col]; Console.WriteLine("Sum of row " + (row + 1 ) + " = " + sum ); } Processing two-dimensional arrays (Cont.) Sum by Column the following nested for loop finds the sum of each individual column: //Sum of each individual column for (col = 0; col < NUMBER_OF_COLUMNS; col++) { sum = 0; for (row = 0; row < NUMBER_OF_ROWS; row++) sum = sum + matrix[row, col]; Console.WriteLine("Sum of column " + (col + 1 ) + " = " + sum ); } Processing two-dimensional arrays (Cont.) Largest element in each row for (row = 0; row < NUMBER_OF_ROWS; row++) { largest = matrix[row, 0]; //Assume that the first element //of the row is the largest. for (col = 1; col < NUMBER_OF_COLUMNS; col++) if (largest < matrix[row, col]) largest = matrix[row, col]; Console.WriteLine(" The largest element in row " + (row + 1 ) + " = " + largest ); } Largest element in each column for (col = 0; col < NUMBER_OF_COLUMNS; col++) { largest = matrix[col]; //Assume that the first element //of the column is the largest. for (row = 1; row < NUMBER_OF_ROWS; row++) if (largest < matrix[row, col]) largest = matrix[row, col]; Console.WriteLine(" The largest element in column " + (col + 1 ) + " = " + largest ); } Course Title: : Programming I Prof. Dr. Khaled F. Hussain Records (structs) Records (structs) C# provides a structured data type called struct to group items of different types. Grouping components that are related but of different types offers several advantages. For example, a single variable can pass all the components as parameters to a function. The components of a struct are called the members of the struct. The general syntax of a struct in C# is: struct structName { public dataType1 identifier1; public dataType2 identifier2;... public dataTypen identifiern; }; Records (structs) (Cont.) The statement: struct employeeType { public string firstName; public string lastName; public string address1; public string address2; public double salary; public string deptID; }; defines a struct employeeType with six members. A struct is a definition, not a declaration. That is, it defines only a data type; no memory is allocated. Records (structs) (Cont.) struct studentType { public string firstName; public string lastName; public char courseGrade; public int testScore; public int programmingScore; public double GPA; }; //variable declaration studentType newStudent; studentType student; These statements declare two struct variables, newStudent and student, of type studentType. Accessing struct Members The syntax for accessing a struct member is: structVariableName.memberName The dot (.) is an operator called the member access operator. Suppose you want to initialize the member GPA of newStudent to 0.0. The following statement accomplishes this task: newStudent.GPA = 0.0; Similarly, the statements: newStudent.firstName = "John"; newStudent.lastName = "Brown"; The statement: newStudent.testScore = int.Parse(Console.ReadLine());; reads the testScore from the standard input device and stores it in: newStudent.testScore Assignment statement In fact, the assignment statement: student = newStudent; is equivalent to the following statements: student.firstName = newStudent.firstName; student.lastName = newStudent.lastName; student.courseGrade = newStudent.courseGrade; student.testScore = newStudent.testScore; student.programmingScore = newStudent.programmingScore; student.GPA = newStudent.GPA; Comparison (Relational Operators) To compare struct variables, you compare them member-wise. if (student.firstName == newStudent.firstName && student.lastName == newStudent.lastName)... if (student == newStudent) //illegal Input /Output No aggregate input/output operations are allowed on a struct variable. Data in a struct variable must be read one member at a time. Example using System; public class HelloWorld { struct Coordinate { public int x; public int y; } public static void Main(string[] args) { Coordinate point = new Coordinate(); Console.WriteLine(point.x); //output: 0 Console.WriteLine(point.y); //output: 0 }} Above, an object of the Coordinate structure is created using the new keyword. It calls the default parameterless constructor of the struct, which initializes all the members to their default value of the specified data type. If you declare a variable of struct type without using new keyword, it does not call any constructor, so all the members remain unassigned. Therefore, you must assign values to each member before accessing them, otherwise, it will give a compile-time error. Create Structure Without new Keyword using System; public class HelloWorld { struct Coordinate { public int x; public int y; } public static void Main(string[] args) { Coordinate point; Console.Write(point.x); // Compile time error }} Create Structure Without new Keyword (Cont.) using System; public class HelloWorld { struct Coordinate { public int x; public int y; } public static void Main(string[] args) { Coordinate point; point.x = 10; point.y = 20; Console.Write(point.x); //output: 10 Console.Write(point.y); //output: 20 } } Constructors in Structure A struct cannot contain a parameterless constructor. It can only contain parameterized constructors. using System; public class HelloWorld { struct Coordinate { public int x; public int y; public Coordinate(int x, int y) { this.x = x; this.y = y; }} public static void Main(string[] args) { Coordinate point = new Coordinate(10, 20); Console.WriteLine(point.x); //output: 10 Console.WriteLine(point.y); //output: 20 } } structs in Arrays struct EmployeeType { public string FirstName; public string LastName; public int PersonID; public string DeptID; public double YearlySalary; public double MonthlySalary; public double YearToDatePaid; public double MonthlyBonus; } EmployeeType[] employees = new EmployeeType; structs within a struct struct NameType { public string First; public string Middle; public string Last; } struct AddressType { public string Address1; public string Address2; public string City; public string State; public string Zip; } structs within a struct (Cont.) struct DateType { public int Month; public int Day; public int Year; } struct ContactType { public string Phone; public string Cellphone; public string Fax; public string Pager; public string Email; } structs within a struct (Cont.) struct EmployeeType { public NameType Name; public string EmpID; public AddressType Address; public DateType HireDate; public DateType QuitDate; public ContactType Contact; public string DeptID; public double Salary; } Example 1 using System; struct Rectangle { public int Width; public int Height; } class Program { static void Main() { Rectangle rect; rect.Width = 4; rect.Height = 5; int area = rect.Width * rect.Height; Console.WriteLine("Area of rectangle: " + area); } } Example 2 using System; struct Date { public int Year; public string Month; public int Day; } class Program { static void Main() { const int numDates = 3; Date[] dates = new Date[numDates]; // Array of Date structures // Initialize dates (replace with user input or calculations if needed) dates = new Date { Year = 2023, Month = "December", Day = 31 }; dates = new Date { Year = 2024, Month = "January", Day = 1 }; dates = new Date { Year = 2024, Month = "April", Day = 21 }; // Today's date (assuming April 21, 2024) for (int i = 0; i < numDates; i++) { Console.WriteLine($"{dates[i].Month} {dates[i].Day}, {dates[i].Year}"); } }} Example 3 #include #include using namespace std; struct Point { double x; double y; }; double distance(const Point& p1, const Point& p2) { return sqrt(std::pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2)); } int main() { Point p1 = {1.0, 2.0}; Point p2 = {4.0, 6.0}; double distance_between = distance(p1, p2); cout