0% found this document useful (0 votes)
2 views

Programming Fundamentals For Engineers CH. 1,2,3

The document covers the fundamentals of programming for engineers, including key concepts such as hardware vs. software, machine code, algorithms, memory types, and error handling. It also discusses the software development life cycle (SDLC), application architecture, and the differences between compiled and interpreted languages. Additionally, it provides insights into Visual Studio as a development environment and the role of intermediate languages in the .NET framework.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Programming Fundamentals For Engineers CH. 1,2,3

The document covers the fundamentals of programming for engineers, including key concepts such as hardware vs. software, machine code, algorithms, memory types, and error handling. It also discusses the software development life cycle (SDLC), application architecture, and the differences between compiled and interpreted languages. Additionally, it provides insights into Visual Studio as a development environment and the role of intermediate languages in the .NET framework.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Programming

Fundamentals
For Engineers
CH. 1,2,3
Prepared by
Aly Reda

@alyredaabdalla
Table of Content

Chapter 1 2
Introduction to Programming 2
Hardware vs. Software 2
Machine Code: The Language of Computers 3
What is Programming? 3
Algorithms 4
Memory types 4
Errors 5
Types of Applications 5
Software Development Life Cycle (SDLC) 6
Application Architecture 7
Compiled vs. Interpreted Languages 7
ASCII Table 9
Visual Studio 9
Chapter 2 10
Intermediate Language 10
.NET Framework 11
Desktop Applications 11
C# Structures 12
Console Application in Visual Studio using the .NET Framework 13
Variables 14
Data Types 14
Integers 15
Floats 15
Double 16
Maximum and Minimum Values of Data Types 16
Boolean 17
Strings 17
Characters 18
var 18
Type Conversion 18
Implicit Conversion 18
Explicit Conversion (Casting) 19
Non-Compatible Conversion (Parsing) 19
User Input 20
Mathematical Operators 20
Chapter 3 20
if Statement 21
Switch statement 22
Comments 22
Logical Operators 23
Loops 23
for Loop 23
while Loop 24
do-while Loop 24

1
Chapter 1
Introduction to Programming
Introduction to Programming is a fundamental topic that teaches the basics of writing code and
solving problems using a computer. It covers core concepts like variables, data types, control
structures, functions, and algorithms. Typically, beginners start with a simple programming
language like C#

Hardware vs. Software


A computer system is composed of two fundamental components: hardware and software.
• Hardware: The physical components that make up a computer system, such as the processor,
memory, storage devices, input/output devices, and motherboard. These components are tangible and
can be touched.
• Software: The intangible instructions or programs that dictate the behavior of the hardware. It is a set
of coded instructions that the computer executes to perform specific tasks. Software is not physical
and exists only as data stored on the hardware.

Software Controls Hardware


Software plays a crucial role in controlling the behavior of hardware. It provides the instructions that guide
the hardware in performing tasks, such as processing data, storing information, and interacting with the user.
Without software, hardware would be useless.

Types of Software
Software can be categorized into two main types:
1. Systems Software: This type of software manages the overall operation of a computer system. It
includes:

• Operating Systems: The core software that controls the hardware


and provides a platform for other software to run. Examples include
Windows, macOS, Linux, iOS, and Android.

2. Application Software: This type of software is designed to perform specific tasks for users. Examples
include:
• Database Management Systems: Used to store, manage, and retrieve data (e.g., Oracle,
MySQL).
• Design Software: Used for creating designs and graphics (e.g., Autodesk AutoCAD, Autodesk
Revit).

2
Machine Code: The Language of Computers
Understanding Binary Code
Computers understand a language of 0s and 1s, known as binary code. Each individual 0 or 1 is called a bit.
A group of 8 bits is called a byte.

Compilation and the Compiler


When you write a program in a high-level language (like Python, Java, or C++), it's not directly
understandable by the computer's hardware. To bridge this gap, we use a compiler.
• Compiler: A compiler is a software program that translates high-level code into machine code. It
breaks down the human-readable code into a series of instructions that the computer can execute.

The Compilation Process


This is the process of converting the source code into machine code. A compiler is the software tool
that performs this conversion. The compiler breaks down the source code into smaller parts, analyzes
its meaning, and generates a sequence of machine instructions that the computer can execute.

Source File and Machine Code


• Source File: This is the original human-readable code written by the programmer. It contains the
instructions and logic of the program.
• Machine Code: This is the output of the compilation process. It is a sequence of 0s and 1s that the
computer can directly execute.

What is Programming?
Programming is the process of creating instructions for a computer to follow. These instructions, written in a
programming language, tell the computer what to do, how to do it, and when to do it.

Computers only understand binary: At the most fundamental level, computers understand only binary
code, which is a sequence of 0s and 1s.

High-level programming languages: These languages are designed to be more human-readable and easier to
work with. They abstract away the complexities of machine code, allowing programmers to focus on
problem-solving without needing to worry about the underlying hardware. Examples of high-level languages
include Python, Java, C#, and JavaScript.

3
Low-level programming languages: These languages are closer to the machine's native language (binary
code). They offer more control over hardware but are more complex to learn and use. Assembly language is a
common example of a low-level language. It provides direct control over the computer's instructions but
requires a deep understanding of the hardware architecture.

Algorithms
An algorithm is a sequence of well-defined instructions to solve a particular problem. It's essentially a recipe
or blueprint for accomplishing a specific task.

Characteristics of Algorithms
• Definiteness: Each step should be precisely defined and unambiguous.
• Finiteness: The algorithm should terminate after a finite number of steps.
• Effectiveness: Each step should be feasible and should lead to a solution.
• Input: An algorithm takes input data to process.
• Output: An algorithm produces output, which is the solution to the problem.

Tools for Representing Algorithms


• Flowcharts: A visual representation of an algorithm using boxes, arrows, and symbols to depict the
flow of control.
• Pseudocode: A simplified, informal language that combines elements of programming languages with
plain English to describe an algorithm.

Memory types
Types of Computer Memory
RAM (Random Access Memory)
• Volatile: Its contents are lost when the computer is turned off.
• Fast: It's used for temporary storage of data and instructions that the
CPU is currently using.
• Addresses: Each memory location in RAM has a unique address, allowing the CPU to access data
directly.
Hard Disk Drive (HDD)
• Non-volatile: Its contents persist even when the computer is powered off.
• Slow: Compared to RAM, HDDs are much slower.
• Storage: Used for long-term storage of data and programs.
Processor (CPU)
• Central Processing Unit: It's the brain of the computer.
• Calculations: The processor performs all arithmetic and logical operations.
• Control Unit: It manages the flow of data between the processor, memory, and other components.

4
Errors
Errors in programming can be broadly categorized into three main types:
1. Syntax Errors
• Definition: These occur when the code violates the specific rules of the programming language's
syntax. It's like grammatical mistakes in human language.
• Examples: Missing parentheses, incorrect variable names, or typos in keywords.
• Detection: Usually detected by the compiler or interpreter during the compilation or interpretation
process.
2. Logical Errors (Bugs)
• Definition: These are errors in the logic or algorithm of the code. The program may run without
crashing, but it produces incorrect results.
• Examples: Incorrect calculations, infinite loops, or incorrect decision-making.
• Detection: Often difficult to find, as they don't cause immediate crashes. Debugging tools and careful
testing can help identify and fix logical errors.
3. Runtime Errors
• Definition: These errors occur while the program is running, often due to unexpected conditions or
invalid input.
• Examples: Dividing by zero, accessing an array index out of bounds, or trying to open a file that
doesn't exist.
• Detection: Can lead to program crashes or unexpected behavior. Runtime error messages can provide
clues about the cause of the error.

Debugging: The process of finding and fixing errors in a program. It involves using tools like debuggers,
print statements, and careful analysis of the code to identify the root cause of the problem.

Types of Applications
Applications can be broadly categorized based on their primary platform or use case:
Web Applications
• Accessed via a web browser: Users interact with these applications through a web interface.
• Examples: BIM 360, Google, Amazon, YouTube
Desktop Applications
• Installed on a local computer: These applications run directly on the user's device.
• Examples: Autodesk Revit, AutoCAD, CSI, Primavera
Mobile Applications
• Designed for smartphones and tablets: These applications are optimized for smaller screens and
touch interfaces.
• Examples: WhatsApp, Uber, Careem, Google Maps

5
Software Development Life Cycle (SDLC)
The Software Development Life Cycle (SDLC) is a systematic approach to creating high-quality software. It
outlines a series of phases that software development teams typically follow.

Phases of the SDLC


1. Planning:
• Define project goals: Clearly outline the objectives and scope of the software.
• Identify stakeholders: Determine who will be involved in the project.
• Create a project plan: Develop a timeline, budget, and resource allocation plan.
2. Analysis:
• Gather requirements: Understand the needs and expectations of the users.
• Create use cases: Describe how users will interact with the software.
• Develop functional specifications: Define the specific features and functionality of the
software.
3. Design:
• Create architectural design: Determine the overall structure and components of the software.
• Design user interface: Develop the look and feel of the software.
• Design data structures: Define how data will be stored and organized.
4. Implementation:
• Write code: Develop the software using the chosen programming language.
• Unit testing: Test individual components of the software.
• Integration testing: Test how different components work together.
5. Testing & Integration:
• System testing: Test the entire software system to ensure it meets requirements.
• User acceptance testing (UAT): Validate the software with end-users.
• Integration testing: Ensure that different components of the software work together
seamlessly.
6. Maintenance:
• Bug fixing: Address any issues or defects that are discovered.
• Enhancements: Add new features or improve existing ones.
• Support: Provide assistance to users and maintain the software.

6
Application Architecture
Application architecture refers to the high-level structure and design of a software application. It defines how
different components of the application interact with each other to achieve its goals.

One common architectural pattern is the layered architecture. This pattern divides the application into
distinct layers, each with specific responsibilities:
Presentation Layer
• Purpose: Handles the user interface and interaction.
• Components: User interface elements (e.g., buttons, text boxes), event handling, and view logic.
Business Logic Layer
• Purpose: Encapsulates the core business rules and logic of the application.
• Components: Classes, functions, and algorithms that implement the application's functionality.
Data Access Layer
• Purpose: Interacts with databases or other data storage systems.
• Components: Data access objects (DAOs), database connections, and query execution.

Compiled vs. Interpreted Languages


The primary difference between compiled and interpreted languages lies in how they are executed by the
computer:

Compiled Languages
• Translation Process: The entire source code is translated into machine code by a compiler before
execution.
• Execution: The compiled machine code is then directly executed by the computer's processor.
• Examples: C, C++

7
• Advantages:
• Faster execution: Compiled programs are generally faster because they are directly executed
by the hardware.
• Better performance: Optimized for specific hardware architectures.
• Disadvantages:
• Slower development: The compilation process can be time-consuming, especially for large
projects.
• Less portable: Compiled programs may need to be recompiled for different platforms.

Interpreted Languages
• Translation Process: The source code is translated into machine code line by line during execution
by an interpreter.
• Execution: The interpreter reads and executes each line of code sequentially.
• Examples: Python, JavaScript
• Advantages:
• Faster development: Changes to the code can be tested immediately without recompilation.
• More portable: Interpreted programs can often run-on different platforms without
modification.
• Disadvantages:
• Slower execution: Interpreted languages can be slower than compiled languages due to the
overhead of the interpreter.
• Less efficient: Interpreters may not be as efficient at optimizing code as compilers.

Hybrid Languages
• Combination of both: These languages combine elements of compiled and interpreted languages.
• Examples: C#, Java
• Process: The source code is first compiled into an intermediate representation (bytecode). This
bytecode is then executed by a virtual machine, which translates it into machine code at runtime.
• Advantages:
• Faster development: Can benefit from the rapid development cycle of interpreted languages.
• Better performance: Can achieve performance improvements through compilation.

In summary:
• Compiled languages: Faster execution, but slower development and less portable.
• Interpreted languages: Slower execution, but faster development and more portable.
• Hybrid languages: Balance the advantages and disadvantages of both compiled and interpreted
languages.

8
ASCII Table
ASCII (American Standard Code for Information Interchange) is a character encoding standard that assigns a
unique numerical code to each character, including letters, numbers, punctuation marks, and control
characters.

Visual Studio
Visual Studio is a comprehensive Integrated Development Environment (IDE) created
by Microsoft. It provides a comprehensive set of tools and features for software
development, making it a popular choice for developers working on various platforms
and languages.

Components of Visual Studio


• Code Editor: A sophisticated text editor that supports syntax highlighting, code completion, and
refactoring.
• Debugger: A tool for finding and fixing errors in your code. It allows you to step through code, set
breakpoints, and inspect variables.

9
• GUI Designer: A visual tool for creating graphical user interfaces (GUIs) without writing extensive
code.
• Compiler and Build Tools: Built-in tools for compiling and building your projects.
• Source Control Integration: Supports integration with version control systems like Git, allowing you
to manage your code effectively.
• Team Collaboration Features: Enables collaboration among developers, including code reviews,
shared projects, and task management.
• Extensibility: Can be customized with extensions to add new features and functionality.

Chapter 2
Intermediate Language
Intermediate Language (IL)
• Definition: IL is a low-level, platform-independent language that is generated by compilers from
high-level languages like C#. It serves as a common language for the .NET Framework.
• Purpose: IL acts as a bridge between the high-level source code and the underlying hardware. It
provides a layer of abstraction, making .NET applications more portable.
C# Compiler
• Role: The C# compiler translates C# source code into IL.
• Output: The compiled output of a C# program is typically an assembly file with a .dll or .exe
extension, containing the IL code and metadata.
JIT Compiler (Just-In-Time Compiler)
• Purpose: The JIT compiler converts IL code into machine code at runtime, specifically for the target
hardware platform.
• Optimization: JIT compilers often perform optimizations to improve the performance of the
generated machine code.
.exe
• Definition: A .exe file is an executable file that contains the compiled machine code of a program.
• Execution: When you double-click a .exe file, the operating system loads it into memory and the
processor executes the machine code.

The Process
1. C# Source Code: A C# programmer writes the source code.
2. C# Compiler: The C# compiler translates the source code into IL and stores it in a .dll or .exe file.
3. .NET Runtime: When the .exe file is executed, the .NET runtime loads it into memory.
4. JIT Compilation: The JIT compiler converts the IL code into machine code specific to the target
hardware.
5. Execution: The machine code is executed by the processor.

10
.NET Framework
The .NET Framework is a powerful platform developed by Microsoft that provides a runtime environment
and a rich set of class libraries for building applications.
Common Language Runtime (CLR)
• Core Component: The CLR is the heart of the .NET Framework. It manages the execution of .NET
applications.
• Functions:
• Compilation: The CLR includes a Just-In-Time (JIT) compiler that translates Intermediate
Language (IL) code into machine code at runtime, optimizing performance.
• Memory Management: The CLR handles memory allocation and garbage collection, freeing
developers from manual memory management.

Framework Class Library (FCL)


• Collection of Classes: The FCL is a vast collection of reusable classes and components that provide a
wide range of functionality.

Desktop Applications
Desktop applications are software programs designed to run on a personal computer's desktop. These
applications typically have a graphical user interface (GUI) and are installed directly on the user's device.

Characteristics of Desktop Applications


• Standalone: They don't require a constant internet connection to function.
• GUI: They provide a visual interface for users to interact with.
• File-Based: They often work with files stored on the local computer.
• Platform-Specific: Desktop applications are usually designed for a specific operating system (e.g.,
Windows, macOS, Linux).

Types of Desktop Applications


• Console Applications: These applications run in a text-based console window. They are often used
for utility programs or scripting tasks.
• Windows Forms Applications: These applications use the Windows Forms framework to create
graphical user interfaces with windows, buttons, text boxes, and other controls.
• Windows Presentation Foundation (WPF) Applications: WPF is a newer framework that provides
a more flexible and scalable way to create GUIs. It uses XAML for declarative markup and can be
used to create both desktop and web applications.

11
Developing Desktop Applications with Visual Studio
Visual Studio is a popular IDE (Integrated Development Environment) for developing desktop applications. It
provides tools and templates for creating different types of desktop applications, including:

• Console Applications: Create text-based applications for tasks like scripting or data processing.
• Windows Forms Applications: Build applications with traditional Windows-style GUIs.
• WPF Applications: Create modern, visually appealing GUIs with XAML and C#.

C# Structures
C# structures are value types that can hold multiple related fields. They are similar to classes, but they have
some key differences:
• Value Types: Structures are passed by value, meaning a copy of the structure's data is created when
it's passed to a method or assigned to a new variable. This is different from classes, which are passed
by reference.
• No Inheritance: Structures cannot inherit from other classes or structures, but they can implement
interfaces.
• Default Constructor: Structures have a default constructor that initializes all fields to their default
values.
• Stack Allocation: Structures are typically allocated on the stack, which is a region of memory that is
automatically managed by the runtime.

Components of a C# Structure
1. Namespace: A namespace is used to organize code and prevent naming conflicts. It's optional but
recommended for larger projects.
2. Class or Structure Declaration: The keyword struct is used to declare a structure.
3. Fields: Fields are variables that store data within the structure.
4. Methods: Methods are functions that can be defined within a structure to perform operations on its
data.
5. Properties: Properties provide a way to access and modify the values of fields in a controlled manner.

Importance of Curly Braces {}


The braces {} in C# are used to define the scope of a block of code. In the context of structures, they enclose
the definition of the structure's fields and methods. This ensures that the code within the braces is associated
with the structure and can access its members.

12
Console Application in Visual Studio using the .NET Framework
Create a console application in Visual Studio using the .NET Framework. Here's a step-by-step guide:
1. Open Visual Studio: Launch Visual Studio on your computer.
2. Create a New Project:
• Go to File -> New -> Project.
• Select Visual C# from the left pane and choose Console App (.NET Framework).
• Give your project a name and choose a location, then click OK.

XML (eXtensible Markup Language)


• Purpose: XML is a markup language used to store and transport data. It provides a flexible and
structured way to represent information.
• Structure: XML documents consist of elements, attributes, and text content. Elements are enclosed in
angle brackets (<element>...</element>), attributes are specified within elements (<element
attribute="value">), and text content is placed between elements.

DLL (Dynamic Link Library)


• Definition: A DLL is a file format used to store compiled code and data. It's a reusable component
that can be shared by multiple applications.
• Purpose: DLLs help in code modularization, reusability, and efficient memory management.
• Usage: When an application needs to use the functionality provided by a DLL, it loads the DLL at
runtime and calls its functions.

Console.WriteLine()
• Purpose: This method is used to write text to the console output. It's commonly used in console
applications to display information to the user.
• Syntax:
Console.WriteLine(message);
Where message is the text to be written to the console.

Console.ReadLine()
• Purpose: This method is used to read a line of text from the console input. It's often used to get user
input.
• Syntax:
string input = Console.ReadLine();
The ReadLine() method returns a string containing the text entered by the user.

13
Variables
In programming, variables are like placeholders in memory that store values. They are used to represent data
that can change during the execution of a program.

Types of Variables
Variables can be classified based on their data types, which determine the kind of values they can hold:
• Numeric Variables:
• Integer: Stores whole numbers (e.g., int, long, short, byte).
• Floating-Point: Stores decimal numbers (e.g., float, double).
• Boolean: Stores true or false values (bool).
• Character Variables: Stores a single character (char).
• String Variables: Stores a sequence of characters (string).
• Other Types: There are various other data types depending on the programming language, such as
arrays, objects, and custom data types.
Declaring Variables
To declare a variable, you specify its data type and a name. The name is used to refer to the variable's value.
int Number =1;
const int Number = 3.14;

Data Types
Data types define the kind of values a variable can hold and the operations that can be performed on them. In
programming, data types are crucial for ensuring correct data handling and preventing errors.

Primitive Data Types


Primitive data types represent basic values and are directly supported by the programming language. Common
primitive data types include:
• Numbers:
• Signed: Can represent both positive and negative values (e.g., int, long, short, byte, float,
double).
• Unsigned: Can represent only positive values (e.g., uint, ulong, ushort, sbyte).
• Characters: Represents a single character (char).
• Booleans: Represents true or false values (bool).

Non-Primitive Data Types


Non-primitive data types are more complex and often represent collections of values or objects. They are
typically built on top of primitive data types. Examples of non-primitive data types include:
• Strings: Represent sequences of characters (string).
• Arrays: Store collections of elements of the same data type.
• Objects: Represent instances of classes, which can contain properties, methods, and events.
• Custom Data Types: You can define your own data types using classes or structures.

14
Overflow
Overflow occurs when a variable is assigned a value that is outside of its valid range. For example, if an int
variable is assigned a value that is too large, it may overflow and wrap around to a negative value.

Integers
In programming, integers are data types used to represent whole numbers (numbers without decimal points).
They are commonly used for counting, indexing, and performing mathematical operations.

Size and Range


The size of an integer data type determines the range of values it can store. In most programming languages,
integers are typically 4 bytes in size, which means they can represent numbers from -2,147,483,648 to
2,147,483,647.

int x = 35; // Declares an integer variable named "x" and initializes it with the value 35
int y = 10000; // Declares an integer variable named "y" and initializes it with the value 10000

Variable names must be unique within their scope.

Floats
Floating-point numbers, or simply floats, are data types used to represent numbers with decimal points. They
are essential for handling values that require precision beyond what integers can offer.

Size and Range


In many programming languages, floating-point numbers are typically 4 bytes (32 bits) in size. This limits
their precision and range compared to larger data types like double. The specific range of values that can be
represented by a float depends on the underlying hardware and the implementation of the floating-point
standard.

float a = 0.25f; // Declares a float variable named "a" and initializes it with the value 0.25

Using f Suffix
The f suffix is used to explicitly indicate that a number should be treated as a float. Without the f, the
compiler may interpret the number as a double, which is a larger data type with greater precision.

15
Double
• Size: 8 bytes
• Purpose: Used to represent double-precision floating-point numbers, which have a wider range and
higher precision compared to float values.

double a = 15;
double b = 0.25;

In the example, both a and b are declared as double variables. When initializing a double variable with a
decimal number, you don't need to use the f suffix as it's implied that the value is a double.

• double provides greater precision and a wider range than float.


• It's suitable for calculations that require high accuracy, such as scientific computations or financial
calculations.
• The f suffix is not necessary for double values.

Maximum and Minimum Values of Data Types


In programming, it's often useful to know the maximum and minimum values that a particular data type can
hold. This information helps prevent overflow errors and ensures that your code handles values appropriately.

Integer Data Types


• int:
• Maximum value: int.MaxValue (2,147,483,647)
• Minimum value: int.MinValue (-2,147,483,648)
• uint:
• Maximum value: uint.MaxValue (4,294,967,295)
• Minimum value: uint.MinValue (0)
Floating-Point Data Types
• double:
• Maximum value: double.MaxValue (approximately 1.7976931348623157E+308)
• Minimum value: double.MinValue (approximately -1.7976931348623157E+308)
Example Usage

Console.WriteLine(int.MaxValue);
Console.WriteLine(int.MinValue);
Console.WriteLine(double.MaxValue);
Console.WriteLine(double.MinValue);
Console.WriteLine(uint.MaxValue);
Console.WriteLine(uint.MinValue);
This code will output the maximum and minimum values for the specified data types.

16
• The maximum and minimum values of a data type are determined by its size and representation.
• Understanding these values is important for preventing overflow errors and ensuring correct data
handling.
• You can use the MaxValue and MinValue properties of data types to access their respective maximum
and minimum values.

Boolean
The bool data type in C# is used to represent Boolean values, which can be either true or false. Boolean values
are often used in conditional statements and logical expressions.

bool a = true;
bool b = false;

In this example, a and b are declared as Boolean variables and initialized with the values true and false,
respectively.
Uses of Boolean Values
• Conditional statements: To control the flow of execution based on conditions.
• Logical operations: To perform logical operations like AND, OR, and NOT.
• Flags: To indicate the state of a variable or condition.

Strings
Strings in programming are used to store sequences of characters. They can hold anything from a single letter
to entire paragraphs, including numbers, symbols, and spaces.

string message = "Hello World";


• string: This is the data type that specifies the variable will store a sequence of characters.
• message: This is the name of the variable.
• "Hello World": This is the actual string value that will be stored in the message variable.
So, the variable message will now contain the text "Hello World". This is a string that consists of 12
characters, including the space.

• Strings are enclosed in double quotes (").


• They can store multiple characters.
• Strings are immutable, meaning their contents cannot be changed once they are created. If you need to
modify a string, you'll need to create a new one.

17
Characters
Characters in programming are used to store single characters. They are typically represented by a single
letter, number, or symbol.

char a = 'a';
char b = 'b';
• char: This is the data type that specifies the variable will store a single character.
• a and b: These are the names of the variables.
• 'a' and 'b': These are the actual character values that will be stored in the a and b variables,
respectively.
So, the variable a will now contain the character 'a', and the variable b will contain the character 'b'.

• Characters are enclosed in single quotes (').


• They can store only a single character.
• Characters are often used for representing individual letters, numbers, or symbols.

var
The var keyword in C# is used to implicitly type variables, meaning you don't need to explicitly specify their
data type. The compiler infers the data type based on the value assigned to the variable.

var x = 25; //Declares an integer variable named x and initializes it with the value 25.
var s = 0.25; //Declares a floating-point variable named s and initializes it with the value 0.25.
var b = 0.25f; //Declares a single-precision floating-point variable named b and initializes it with the value
0.25.
var name = "Ahmed"; //Declares a string variable named name and initializes it with the string "Ahmed".

Type Conversion
Type conversion refers to the process of transforming data from one data type to another. This is a common
operation in programming, allowing you to work with different data types and perform various calculations or
operations.

Types of Conversion
Implicit Conversion
• Occurs automatically by the compiler when it can safely convert a value from one type to
another without data loss.
• Examples:
▪ Converting a smaller integer type (e.g., byte) to a larger one (e.g., int).
▪ Converting a numeric type (e.g., int) to a floating-point type (e.g., double).
▪ Converting a character (char) to an integer (int).

18
• Limitations:
▪ Cannot convert between incompatible types (e.g., string to int).
▪ May result in data loss if the target type cannot represent all values of the source type
(e.g., converting a double to an int).
byte x=10; //1 byte
int y=x; //4 bytes
double z=y; //8 bytes

Explicit Conversion (Casting)


• Requires manual intervention using the cast operator ((type)).
• Can be used to convert between compatible types, even if it might result in data loss.
• Examples:
▪ Converting a double to an int (may truncate the decimal part).
▪ Converting an int to a char (may truncate the value if it's outside the valid range of
char).
• Limitations:
▪ If the target type cannot represent all values of the source type, data loss may occur.
▪ Requires careful consideration to avoid unexpected results.
double x=10; //8 bytes
int y =x; //4 bytes
So we use
int y = (int)x;

Non-Compatible Conversion (Parsing)


• Used to convert string representations of values to their corresponding numeric types.
• Involves parsing the string using methods like int.Parse(), double.Parse(), etc.
• Examples:
▪ Converting "123" to an int.
▪ Converting "3.14" to a double.
• Limitations:
▪ Requires a valid string format.
▪ May throw an exception if the string cannot be parsed successfully.

String num1= “10”;


String num2= “10”;
String sum= num1+num2;
Sum = “1010”

19
User Input
User input refers to the process of obtaining data from the user through various means, such as the console,
text fields, or file uploads. In C#, the most common way to obtain user input is through the console using the
Console.ReadLine() method.

Console.ReadLine() Method:
• Reads a line of text from the console and returns it as a string.
• The string contains the characters entered by the user up to the next newline character.
• Can be used to capture various types of input, such as numbers, text, or even simple commands.

Console.ReadLine();
String name=ReadLine();
Int x = int.parse(name);

Mathematical Operators
Mathematical operators are used to perform arithmetic operations on numeric values. In C#, there are several
common mathematical operators:
• Addition (+): Adds two numbers.
• Subtraction (-): Subtracts the second number from the first.
• Multiplication (*): Multiplies two numbers.
• Division (/): Divides the first number by the second.
• Modulus (%): Returns the remainder of the division between the first and second numbers.

int num1 = 10;


int num2 = 5;

int sum = num1 + num2; // 15


int sub = num1 - num2; // 5
int mul = num1 * num2; // 50
int div = num1 / num2; // 2
int rem = num1 % num2; // 0

Chapter 3
THIS CHAPTER DOESN’T INCLUDE DEMO VIDEOS CONTENT OR SUMMARY PLEASE
RETURN TO VIDEOS TO WATCH IT

Thanks for understanding

20
if Statement
• The condition is evaluated to a Boolean value (true or false).
• If the condition is true, the code within the if block is executed.
• If the condition is false, the code within the if block is skipped.
• OPERATIONS == , != , < , > ,<= , >=
Syntax:
if (condition)
{
// Code to be executed if the condition is true
}
else Statement
• Used to provide an alternative block of code to execute if the if condition is false.
• The else statement must follow an if statement.
Syntax:
if (condition)
{
// Code to be executed if the condition is true
}
else
{
// Code to be executed if the condition is false
}
Nested if Statements
• You can nest if statements within other if statements to create more complex conditional logic.
Example:
int number = 10;
if (number > 0)
{
if (number < 100)
{
Console.WriteLine("The number is positive and less than 100.");
}
else
{
Console.WriteLine("The number is positive and greater than or equal to 100.");
}
}
else
{
Console.WriteLine("The number is negative.");
}

21
Switch statement
• Used to execute different code blocks based on the value of an expression.
• The expression is evaluated to a value, and the case that matches the value is executed.
• If no case matches, the default case (if present) is executed.

Syntax:
switch (expression)
{
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
default:
// Code to be executed if no case matches
break;
}

• The expression can be of any data type that supports comparison (e.g., int, char, string).
• The case values must be constants or literals.
• The break statement is essential to prevent fall-through to the next case.
• The default case is optional but recommended for handling unexpected values.
• You can use multiple case labels with the same code block if you want to execute the same code for
multiple values.

Comments
Comments are non-executable statements that are used to explain or document code. They are ignored by the
compiler, making them a valuable tool for improving code readability and maintainability.

Single-Line Comments
• Start with // and continue to the end of the line.
• Can be used to add brief explanations or notes to a specific line of code.
int x = 5; // This line assigns the value 5 to the x variable

Multiple-Line Comments:
• Start with /* and end with */.
• Can be used to add more detailed explanations or block comments that span multiple lines.

22
Example:
/*
This is a multi-line comment.
It can be used to explain a larger section of code.
*/

Logical Operators
Logical operators are used to combine boolean expressions and evaluate the overall result. They are essential
for creating complex conditional statements and making decisions in your C# code.

&& Operator (Logical AND)


• Returns true only if both operands are true.
• If either operand is false, the result is false.
|| Operator (Logical OR)
• Returns true if at least one operand is true.
• If both operands are false, the result is false.
! Operator (Logical NOT)
• Reverses the Boolean value of its operand.
• If the operand is true, the result is false.
• If the operand is false, the result is true.

Loops
Loops are control flow statements that allow you to repeatedly execute a block of code until a certain
condition is met. They are essential for performing repetitive tasks and iterating over collections of data.

for Loop
• Used when you know in advance how many times you want to repeat the loop.
• Consists of three parts: initialization, condition, and increment/decrement.

Syntax:
for (initialization; condition; increment/decrement)
{
// Code to be executed
}

Example:
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Iteration: " + i);
}

23
while Loop
• Used when you don't know the exact number of iterations beforehand, but you have a condition to
check at the beginning of each iteration.

Syntax:
while (condition)
{
// Code to be executed
}

Example:
int count = 0;
while (count < 10)
{
Console.WriteLine("Count: " + count);
count++;
}

do-while Loop
• Similar to the while loop, but the condition is checked at the end of each iteration, ensuring that the
code block is executed at least once.
Syntax:
do
{
// Code to be executed
} while (condition);

Example:
int x = 1;
do
{
Console.WriteLine("x: " + x);
x++;
} while (x <= 5);

Additional Considerations:
• You can use the break statement to exit a loop prematurely.
• You can use the continue statement to skip the current iteration and proceed to the next one.
• Nested loops are allowed, where one loop is contained within another.

24

You might also like