For More :
https://www.facebook.com/Computer-Programming-Assignments-826290177441561/
-
https://www.facebook.com/A-Tech-and-Software-Development-1683037138630673/
The document discusses files and file operations in C/C++. It defines a file as a collection of bytes stored on a secondary storage device. There are different types of files like text files, data files, program files, and directory files. It describes opening, reading, writing, appending, and closing files using functions like fopen(), fread(), fwrite(), fclose(), etc. It also discusses random and sequential file access and modifying file contents using functions like fseek(), fread(), fwrite().
The document discusses file management in C. It defines a file as a collection of related data treated as a single unit by computers. C uses the FILE structure to store file attributes. The document outlines opening, reading, writing and closing files in C using functions like fopen(), fclose(), fread(), fwrite(), fseek(), ftell() and handling errors. It also discusses reading/writing characters using getc()/putc() and integers using getw()/putw() as well as formatted input/output with fscanf() and fprintf(). Random access to files using fseek() is also covered.
This document discusses arrays in the C programming language. It begins by defining an array as a collection of elements of the same data type. It then covers key topics such as declaring and initializing one-dimensional and multi-dimensional arrays, accessing array elements using indexes, and performing input and output operations on arrays. Examples are provided to demonstrate how to declare, initialize, read from, and print arrays. The document serves as an introduction to working with arrays in C.
The document discusses dynamic memory allocation in C. It describes the four main functions for dynamic allocation - malloc(), calloc(), free(), and realloc(). malloc() allocates a block of memory of a specified size and returns a pointer. calloc() allocates multiple blocks of memory and initializes them to zero. free() releases previously allocated memory. realloc() changes the size of previously allocated memory. The document provides examples of using each function.
This document provides an introduction to data structures. It defines data structures as a way of organizing data so that it can be used efficiently. The document then discusses basic terminology, why data structures are important, how they are studied, and how they are classified as simple or compound, and linear or non-linear. It proceeds to describe common data structures like arrays, stacks, queues, linked lists, trees, and graphs, and how they support basic operations. The document concludes by discussing how to select an appropriate data structure based on the problem constraints and required operations.
A stack is a linear data structure that follows the last-in, first-out (LIFO) principle. Elements are inserted and removed from one end called the top. The basic operations are push, which inserts an element at the top, and pop, which removes the top element. Stacks have many real-world applications like piles of books and evaluating mathematical expressions. An array can be used to implement a stack by storing elements from index 0 to the top index, and incrementing or decrementing the top index during push and pop operations.
The document discusses various primitive data types including integer, floating point, decimal, boolean, and character. It describes the evolution of character encoding from EBCDIC to ASCII to Unicode. It also covers string operations and different implementations of strings in languages. The document discusses ordinal types like enumeration and subrange. It provides details about array types including static, dynamic, and associative arrays. It compares array implementations across languages.
The document discusses files and file operations in C/C++. It defines a file as a collection of bytes stored on a secondary storage device. There are different types of files like text files, data files, program files, and directory files. It describes opening, reading, writing, appending, and closing files using functions like fopen(), fread(), fwrite(), fclose(), etc. It also discusses random and sequential file access and modifying file contents using functions like fseek(), fread(), fwrite().
The document discusses file management in C. It defines a file as a collection of related data treated as a single unit by computers. C uses the FILE structure to store file attributes. The document outlines opening, reading, writing and closing files in C using functions like fopen(), fclose(), fread(), fwrite(), fseek(), ftell() and handling errors. It also discusses reading/writing characters using getc()/putc() and integers using getw()/putw() as well as formatted input/output with fscanf() and fprintf(). Random access to files using fseek() is also covered.
This document discusses arrays in the C programming language. It begins by defining an array as a collection of elements of the same data type. It then covers key topics such as declaring and initializing one-dimensional and multi-dimensional arrays, accessing array elements using indexes, and performing input and output operations on arrays. Examples are provided to demonstrate how to declare, initialize, read from, and print arrays. The document serves as an introduction to working with arrays in C.
The document discusses dynamic memory allocation in C. It describes the four main functions for dynamic allocation - malloc(), calloc(), free(), and realloc(). malloc() allocates a block of memory of a specified size and returns a pointer. calloc() allocates multiple blocks of memory and initializes them to zero. free() releases previously allocated memory. realloc() changes the size of previously allocated memory. The document provides examples of using each function.
This document provides an introduction to data structures. It defines data structures as a way of organizing data so that it can be used efficiently. The document then discusses basic terminology, why data structures are important, how they are studied, and how they are classified as simple or compound, and linear or non-linear. It proceeds to describe common data structures like arrays, stacks, queues, linked lists, trees, and graphs, and how they support basic operations. The document concludes by discussing how to select an appropriate data structure based on the problem constraints and required operations.
A stack is a linear data structure that follows the last-in, first-out (LIFO) principle. Elements are inserted and removed from one end called the top. The basic operations are push, which inserts an element at the top, and pop, which removes the top element. Stacks have many real-world applications like piles of books and evaluating mathematical expressions. An array can be used to implement a stack by storing elements from index 0 to the top index, and incrementing or decrementing the top index during push and pop operations.
The document discusses various primitive data types including integer, floating point, decimal, boolean, and character. It describes the evolution of character encoding from EBCDIC to ASCII to Unicode. It also covers string operations and different implementations of strings in languages. The document discusses ordinal types like enumeration and subrange. It provides details about array types including static, dynamic, and associative arrays. It compares array implementations across languages.
The document discusses data structures and lists in Python. It begins by defining data structures as a way to organize and store data for efficient access and modification. It then covers the different types of data structures, including primitive structures like integers and strings, and non-primitive structures like lists, tuples, and dictionaries. A large portion of the document focuses on lists in Python, describing how to perform common list manipulations like adding and removing elements using various methods. These methods include append(), insert(), remove(), pop(), and clear(). The document also discusses accessing list elements and other list operations such as sorting, counting, and reversing.
Python is an open source programming language created by Guido van Rossum in 1991. It is named after the comedy group Monty Python and is based on the ABC language. Python supports both procedural and object-oriented programming and can be used for web development, data analysis, artificial intelligence, and more. It has a simple syntax and large standard library that make it easy to learn and use for various applications.
Introduction to Selection control structures in C++ Neeru Mittal
The document discusses various control structures in C++ that alter the sequential flow of program execution. It describes selection statements like if, if-else which execute code conditionally based on boolean expressions. Iterative statements like for, while, do-while loops repeat code execution. The switch statement provides a selection from multiple options. Control structures allow solving problems by choosing the appropriate combination of decision making and repetition.
Type conversion in C provides two methods: implicit type conversion which occurs automatically during expressions, and explicit type conversion using cast expressions. Implicit conversion occurs when different types are used in expressions, such as when an int is used in a calculation with a float. The usual arithmetic conversions implicitly promote operands to the smallest type that can accommodate both values. Explicit casting uses cast operators to force a type conversion.
Functions allow programmers to break programs into smaller, reusable parts. There are two types of functions in C: library functions and user-defined functions. User-defined functions make programs easier to understand, debug, test and maintain. Functions are declared with a return type and can accept arguments. Functions can call other functions, allowing for modular and structured program design.
Dynamic memory allocation allows programs to request memory from the operating system at runtime. This memory is allocated on the heap. Functions like malloc(), calloc(), and realloc() are used to allocate and reallocate dynamic memory, while free() releases it. Malloc allocates a single block of uninitialized memory. Calloc allocates multiple blocks of initialized (zeroed) memory. Realloc changes the size of previously allocated memory. Proper use of these functions avoids memory leaks.
The document discusses functions in C programming. It defines functions as self-contained blocks of code that perform a specific task. Functions make a program more modular and easier to debug by dividing a large program into smaller, simpler tasks. Functions can take arguments as input and return values. Functions are called from within a program to execute their code.
BRANCHING STATEMENTS
if statement
if – else statement
if – else if ladder
Nested if
Goto
Switch case
programs
output
flowchart
Branching / Decision Making Statements
The statements in the program that helps to transfer the control from one part to other parts of the program.
Facilitates program in determining the flow of control
Involves decision making conditions
See whether the condition is satisfied or not
If statement; Execute a set of command line or one command line when the logical condition is true.
It has only one option
syntax with flowchart
If else if ladder; Number of logical statements are checked for executing various statement
If the first condition is true the compiler executes the block followed by first if condition.
If false it skips the block and checks for the next logical condition followed by else if.
Process is continued until a true condition is occurred or an else condition is satisfied.
Switch case; Multiway branch statement
It only requires one argument of any type, which is checked with number of cases.
If the value matches with the case constant, that particular case constant is executed. If not the default statement is executed.
Break statement – used to exit from current case structure
Nested if else; When a series of decisions are involved we use more than one if-else statement.
If condition is true control passes to first block i.e., if block. In this case there may be one more if block.
If condition is false control passes to else block. There we may have one more if block.
This document discusses switch-case statements in C programming. It explains that switch-case allows programmers to make decisions from multiple choices based on an integer expression. Each case must have a different constant value. The break statement is used to terminate a switch. Expressions and char values can be used in cases if they are constant. Switch statements are useful for menu-driven programs. They have advantages over if-else statements in that compilers generate jump tables, making switches faster at execution time.
This document discusses different types of pointers in C programming:
1. Void pointers - Can point to objects of any data type. They are declared using the void keyword.
2. Wild pointers - Pointers that have not been initialized, resulting in undefined behavior.
3. Dangling pointers - Point to memory that has been freed, leading to potential errors.
It also describes pointer types in Turbo C like near, far, and huge pointers which allow accessing different memory segments on 8085 microprocessor-based systems. Near pointers access the first 64KB data segment while far and huge pointers can access all memory segments.
The static keyword in Java is used for memory management and can be applied to variables, methods, blocks, and nested classes. Static variables and methods belong to the class rather than objects. A static variable is loaded when the class is loaded and there is only one copy per class, while instance variables are loaded each time an object is created. The main method must be static since it is called before any objects are created to start the program execution. Static blocks are used to initialize static variables and are executed when the class is loaded.
This document provides an overview of trees as a non-linear data structure. It begins by discussing how trees are used to represent hierarchical relationships and defines some key tree terminology like root, parent, child, leaf, and subtree. It then explains that a tree consists of nodes connected in a parent-child relationship, with one root node and nodes that may have any number of children. The document also covers tree traversal methods like preorder, inorder, and postorder traversal. It introduces binary trees and binary search trees, and discusses operations on BSTs like search, insert, and delete. Finally, it provides a brief overview of the Huffman algorithm for data compression.
This document provides an overview of basic concepts related to data structures and algorithms. It discusses key topics such as the definition of a data structure as an organization of data and how it relates to algorithms. The document also covers classifications of data structures into primitive and non-primitive types as well as linear and non-linear structures. Specific data structures like arrays, stacks, queues, linked lists, trees and graphs are introduced. It provides examples of contiguous structures like arrays and structures, as well as non-contiguous structures like linked lists.
This document provides an overview of string operations in C including:
- How strings are stored in memory with a null terminator
- Input and output of strings using scanf and printf
- Common string library functions like strcpy, strcat, and strlen
- Examples of justifying and manipulating strings
This document discusses different searching methods like sequential, binary, and hashing. It defines searching as finding an element within a list. Sequential search searches lists sequentially until the element is found or the end is reached, with efficiency of O(n) in worst case. Binary search works on sorted arrays by eliminating half of remaining elements at each step, with efficiency of O(log n). Hashing maps keys to table positions using a hash function, allowing searches, inserts and deletes in O(1) time on average. Good hash functions uniformly distribute keys and generate different hashes for similar keys.
Top down parsering and bottom up parsering.pptxLaibaFaisal3
Top-down parsing constructs a parse tree from the root node down to the leaf nodes by starting with the start symbol and transforming it according to grammar rules. It is a leftmost derivation. Recursive descent parsing is a common form of top-down parsing that uses recursive procedures to process the input but can suffer from backtracking if a derivation fails. Bottom-up parsing starts with the input symbols and constructs the tree going upwards, applying grammar rules in reverse to reach the start symbol. It is a rightmost derivation.
This document provides an overview of algorithms and recursion from a lecture. It discusses performance analysis using Big O notation. Common time complexities like O(1), O(n), O(n^2) are introduced. The document defines an algorithm as a set of well-defined steps to solve a problem and categorizes algorithms as recursive vs iterative, logical, serial/parallel/distributed, deterministic/non-deterministic, exact/approximate, and quantum. Examples of recursive algorithms like factorials, greatest common divisor, and the Fibonacci sequence are presented along with their recursive definitions and code implementations.
The document discusses primitive data types in C#, including integer, floating-point, boolean, character, and string types. It defines each type, provides examples of declaring variables of each type and assigning values, and describes literals that can be used to represent values of different types. Key points covered include the name, size, and default value of each primitive type as well as demonstrations of declaring and initializing variables in C#.
The document provides an overview of the C# programming language, covering topics such as data types, operators, expressions, statements, console I/O, loops, arrays, and methods. It describes the various primitive data types in C#, including integer, floating-point, fixed-point, boolean, character, string, and object types. It also discusses variables and identifiers in C#, explaining how to declare variables and the syntax rules for identifiers.
The document discusses data structures and lists in Python. It begins by defining data structures as a way to organize and store data for efficient access and modification. It then covers the different types of data structures, including primitive structures like integers and strings, and non-primitive structures like lists, tuples, and dictionaries. A large portion of the document focuses on lists in Python, describing how to perform common list manipulations like adding and removing elements using various methods. These methods include append(), insert(), remove(), pop(), and clear(). The document also discusses accessing list elements and other list operations such as sorting, counting, and reversing.
Python is an open source programming language created by Guido van Rossum in 1991. It is named after the comedy group Monty Python and is based on the ABC language. Python supports both procedural and object-oriented programming and can be used for web development, data analysis, artificial intelligence, and more. It has a simple syntax and large standard library that make it easy to learn and use for various applications.
Introduction to Selection control structures in C++ Neeru Mittal
The document discusses various control structures in C++ that alter the sequential flow of program execution. It describes selection statements like if, if-else which execute code conditionally based on boolean expressions. Iterative statements like for, while, do-while loops repeat code execution. The switch statement provides a selection from multiple options. Control structures allow solving problems by choosing the appropriate combination of decision making and repetition.
Type conversion in C provides two methods: implicit type conversion which occurs automatically during expressions, and explicit type conversion using cast expressions. Implicit conversion occurs when different types are used in expressions, such as when an int is used in a calculation with a float. The usual arithmetic conversions implicitly promote operands to the smallest type that can accommodate both values. Explicit casting uses cast operators to force a type conversion.
Functions allow programmers to break programs into smaller, reusable parts. There are two types of functions in C: library functions and user-defined functions. User-defined functions make programs easier to understand, debug, test and maintain. Functions are declared with a return type and can accept arguments. Functions can call other functions, allowing for modular and structured program design.
Dynamic memory allocation allows programs to request memory from the operating system at runtime. This memory is allocated on the heap. Functions like malloc(), calloc(), and realloc() are used to allocate and reallocate dynamic memory, while free() releases it. Malloc allocates a single block of uninitialized memory. Calloc allocates multiple blocks of initialized (zeroed) memory. Realloc changes the size of previously allocated memory. Proper use of these functions avoids memory leaks.
The document discusses functions in C programming. It defines functions as self-contained blocks of code that perform a specific task. Functions make a program more modular and easier to debug by dividing a large program into smaller, simpler tasks. Functions can take arguments as input and return values. Functions are called from within a program to execute their code.
BRANCHING STATEMENTS
if statement
if – else statement
if – else if ladder
Nested if
Goto
Switch case
programs
output
flowchart
Branching / Decision Making Statements
The statements in the program that helps to transfer the control from one part to other parts of the program.
Facilitates program in determining the flow of control
Involves decision making conditions
See whether the condition is satisfied or not
If statement; Execute a set of command line or one command line when the logical condition is true.
It has only one option
syntax with flowchart
If else if ladder; Number of logical statements are checked for executing various statement
If the first condition is true the compiler executes the block followed by first if condition.
If false it skips the block and checks for the next logical condition followed by else if.
Process is continued until a true condition is occurred or an else condition is satisfied.
Switch case; Multiway branch statement
It only requires one argument of any type, which is checked with number of cases.
If the value matches with the case constant, that particular case constant is executed. If not the default statement is executed.
Break statement – used to exit from current case structure
Nested if else; When a series of decisions are involved we use more than one if-else statement.
If condition is true control passes to first block i.e., if block. In this case there may be one more if block.
If condition is false control passes to else block. There we may have one more if block.
This document discusses switch-case statements in C programming. It explains that switch-case allows programmers to make decisions from multiple choices based on an integer expression. Each case must have a different constant value. The break statement is used to terminate a switch. Expressions and char values can be used in cases if they are constant. Switch statements are useful for menu-driven programs. They have advantages over if-else statements in that compilers generate jump tables, making switches faster at execution time.
This document discusses different types of pointers in C programming:
1. Void pointers - Can point to objects of any data type. They are declared using the void keyword.
2. Wild pointers - Pointers that have not been initialized, resulting in undefined behavior.
3. Dangling pointers - Point to memory that has been freed, leading to potential errors.
It also describes pointer types in Turbo C like near, far, and huge pointers which allow accessing different memory segments on 8085 microprocessor-based systems. Near pointers access the first 64KB data segment while far and huge pointers can access all memory segments.
The static keyword in Java is used for memory management and can be applied to variables, methods, blocks, and nested classes. Static variables and methods belong to the class rather than objects. A static variable is loaded when the class is loaded and there is only one copy per class, while instance variables are loaded each time an object is created. The main method must be static since it is called before any objects are created to start the program execution. Static blocks are used to initialize static variables and are executed when the class is loaded.
This document provides an overview of trees as a non-linear data structure. It begins by discussing how trees are used to represent hierarchical relationships and defines some key tree terminology like root, parent, child, leaf, and subtree. It then explains that a tree consists of nodes connected in a parent-child relationship, with one root node and nodes that may have any number of children. The document also covers tree traversal methods like preorder, inorder, and postorder traversal. It introduces binary trees and binary search trees, and discusses operations on BSTs like search, insert, and delete. Finally, it provides a brief overview of the Huffman algorithm for data compression.
This document provides an overview of basic concepts related to data structures and algorithms. It discusses key topics such as the definition of a data structure as an organization of data and how it relates to algorithms. The document also covers classifications of data structures into primitive and non-primitive types as well as linear and non-linear structures. Specific data structures like arrays, stacks, queues, linked lists, trees and graphs are introduced. It provides examples of contiguous structures like arrays and structures, as well as non-contiguous structures like linked lists.
This document provides an overview of string operations in C including:
- How strings are stored in memory with a null terminator
- Input and output of strings using scanf and printf
- Common string library functions like strcpy, strcat, and strlen
- Examples of justifying and manipulating strings
This document discusses different searching methods like sequential, binary, and hashing. It defines searching as finding an element within a list. Sequential search searches lists sequentially until the element is found or the end is reached, with efficiency of O(n) in worst case. Binary search works on sorted arrays by eliminating half of remaining elements at each step, with efficiency of O(log n). Hashing maps keys to table positions using a hash function, allowing searches, inserts and deletes in O(1) time on average. Good hash functions uniformly distribute keys and generate different hashes for similar keys.
Top down parsering and bottom up parsering.pptxLaibaFaisal3
Top-down parsing constructs a parse tree from the root node down to the leaf nodes by starting with the start symbol and transforming it according to grammar rules. It is a leftmost derivation. Recursive descent parsing is a common form of top-down parsing that uses recursive procedures to process the input but can suffer from backtracking if a derivation fails. Bottom-up parsing starts with the input symbols and constructs the tree going upwards, applying grammar rules in reverse to reach the start symbol. It is a rightmost derivation.
This document provides an overview of algorithms and recursion from a lecture. It discusses performance analysis using Big O notation. Common time complexities like O(1), O(n), O(n^2) are introduced. The document defines an algorithm as a set of well-defined steps to solve a problem and categorizes algorithms as recursive vs iterative, logical, serial/parallel/distributed, deterministic/non-deterministic, exact/approximate, and quantum. Examples of recursive algorithms like factorials, greatest common divisor, and the Fibonacci sequence are presented along with their recursive definitions and code implementations.
The document discusses primitive data types in C#, including integer, floating-point, boolean, character, and string types. It defines each type, provides examples of declaring variables of each type and assigning values, and describes literals that can be used to represent values of different types. Key points covered include the name, size, and default value of each primitive type as well as demonstrations of declaring and initializing variables in C#.
The document provides an overview of the C# programming language, covering topics such as data types, operators, expressions, statements, console I/O, loops, arrays, and methods. It describes the various primitive data types in C#, including integer, floating-point, fixed-point, boolean, character, string, and object types. It also discusses variables and identifiers in C#, explaining how to declare variables and the syntax rules for identifiers.
What is Data Type?
Primitive Types in C#: Integer Types, Floating-Point Types, Decimal Type, Boolean Type, Character Types, Strings, Objects
Value Types and Reference Types
Variables. Using Variables: Declaring, Initializing, Assigning Value, Accessing Value
Literals: The Values of the Variables in the Source Code. Boolean Literals. Integer Literals. Floating-Point Literals, Decimal Literals, String Literals and Escaping Sequences
Exercises: Working with Primitive Types and Variables
This document provides an overview of C# data types, operators, expressions, and statements. It describes primitive data types like integers, floats, booleans, characters, and strings. It also covers literals for representing values of these types. Additionally, it discusses various categories of operators in C# like arithmetic, logical, comparison, assignment, and bitwise operators. Examples are provided to demonstrate how to use each data type and operator.
This document provides an overview of C# data types, operators, expressions, statements, and other fundamental concepts. It discusses the different primitive data types in C#, including integer, floating-point, boolean, character, and string types. It also covers literals, variables, operators such as arithmetic, logical, comparison, and assignment, and shows examples of using each concept. The document is intended to teach basic C# syntax and semantics.
This document discusses data types and variables in JavaScript. It describes the main data types - integer, floating-point, boolean, and string. It explains that variables are used to store and manipulate data in memory, and have a name, type, and value. The document also covers declaring variables with the var keyword, assigning values to variables, and initializing variables before use.
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
The document discusses Java syntax and concepts including:
1. It introduces primitive data types in Java like int, float, boolean and String.
2. It covers variables, operators, and expressions - how they are used to store and manipulate data in Java.
3. It explains console input and output using Scanner and System.out methods for reading user input and printing output.
4. It provides examples of using conditional statements like if and if-else to control program flow based on conditions.
This document discusses basic C++ programming concepts such as:
1) The differences between C and C++ including input/output statements, data types, arithmetic operators, and header files.
2) C++ is a superset of C and was originally called "C with classes".
3) A basic C++ program structure includes preprocessor directives like #include, namespaces, main functions that return integers, and input/output streams for user input.
The document provides an introduction to data types in C++ programming language. It discusses the different levels of programming languages, common uses of C/C++, its character set, whitespace characters, and defines what a data type is. It then lists the primitive/built-in data types in C++ like integer, float, boolean, etc. and describes variables types and memory used. It also covers rules for constructing identifiers, variable declaration, and the four types of C/C++ instructions.
Python is a popular programming language used in a variety of applications, including data analysis, web development, and artificial intelligence. Here's an introduction to the Basics of Python - A Beginners Guide! Whether you're new to programming or looking to brush up on your skills, this video covers the basics of Python programming language. From data types and operators to loops, functions and libraries, you'll get a solid foundation to start coding in Python.
Visit us: https://www.elewayte.com/
The document discusses various C++ programming concepts including variables, data types, input/output streams, and expressions. It defines variables as memory locations that can store values, and describes different data types like int, double, char. It also covers input with cin, output with cout, and formatting output values.
The document provides information on fundamental C data types including bits, bytes, words, integers, floating point numbers, enumerated types, variables, type conversions, constants, and basic operators. It defines common data types like char, int, float, and double. It also covers typecasting, variable declaration, and basic arithmetic, logical, relational, and bitwise operators.
Data Type is a basic classification which identifies.docxtheodorelove43763
Data Type is a basic classification which identifies different types of data.Data Types helps in:Determining the possible values of a variablePossible operations which can be executed on the typeMeaning of the dataDifferent ways to store the data
Data Types are of different types:
Primitive data Types
Composite Data Types
*
Primitive data types are those data types which are not defined in terms of other data types.
Examples are:
Integer
Floating Point
Boolean
Character
*
NOTE: primitive here is not the same as how we use it when referring to the primitive types in Java even though they are mostly the same types. By primitive, we mean directly supported by hardware. Strings do not appear in this list because strings are rarely supported directly in hardware, instead they are stored as individual characters and linked together through some mechanism implemented by the programming language (usually as arrays of characters).
What about pointer types? You’ll notice that they do not appear above. Typically, pointers are just unsigned int values. But we treat pointers differently than ints because we do not permit pointer arithmetic (except in a few languages) and require dereferencing of some kind. Dereferencing may be directly supported in hardware by having indirect addressing modes.
Integers are used to hold integer values only.This is further categorized into:
byte
short
int
long
signed
Unsigned
Examples are:
unsigned int x = 21234;
unsigned int y = 31234;
unsigned int z;
z = x + y;
This data type contains decimal points.Examples are:
float f = 20.0 / 3.0;
Current standard version of floating-point
Single-precision (float)
One word: 1 sign bit, 23 bit fraction, 8 bit exponent
Positive range: 1.17549435 × 10-38 … 3.40282347 × 10+38
Double-precision (double)
Two words: 1 sign bit, 52 bit fraction, 11 bit exponent
Positive range: 2.2250738585072014 × 10-308 … 1.7976931348623157 × 10+308
*
Boolean Data type is used to store logical value.It can have either True or False value.It is a one bit representation0 represents false value1 represents true valueExample: Boolean a;
a=true;
Roman alphabet, punctuation, digits, and other symbols:Can encode within one byte (256 symbols)
In C:
char a_char = ’a’;
char newline_char = ’\n’;
char tab_char = ’\t’;
char backslash_char = ’\\’;
These data types are derived from more than one primitive data type.Examples are:
Arrays
Records
Structure
Union
Arrays are a finite sequence of variables of the same data type These are commonly implemented by the compiler generating array descriptors for each array
here we have
descriptors for
1-D and multi-D
arrays
*
Records are Varied aggregate of data elementsThe elements of a record are known as fields or membersRecords were introduced in COBOLThis data type is used in many languages.In Java, the functionality of records are achieved through the use of classes
Examples:
COBOL (nested structure.
The document provides an outline of topics for a C/C++ tutorial, including a "Hello World" program, data types, variables, operators, conditionals, loops, arrays, strings, functions, pointers, command-line arguments, data structures, and memory allocation. It gives examples and explanations of key concepts in C/C++ programming.
The document discusses operators and casts in C#. It covers various types of operators like arithmetic, comparison, conditional, etc. It explains implicit and explicit type conversions between primitive and reference types. It also discusses overloading operators for custom types and implementing user-defined casts.
This document discusses data representation in Python programming. It begins by noting the vast amount of data being created and analyzed today. The chapter will look at how data is represented using Python, including numeric and string literals. Numeric literals represent integer and floating-point values, while string literals represent text enclosed in single or double quotes. Various encoding schemes are used to represent character values numerically. Formatted strings can be used to control display formatting. Variables are also introduced which allow operating on different values each time a program is run.
The document discusses various topics related to tokens, variables, data types, and operators in C programming. It defines tokens as the smallest elements identified by the compiler, such as keywords, identifiers, string literals, and operators. It describes different variable types like local variables, global variables, and static variables. It also explains various data types in C like integer, float, char, etc and their sizes and ranges. Finally, it discusses various arithmetic, relational, logical, and assignment operators in C and their precedence.
Similar to Primitive Data Types and Variables Lesson 02 (20)
Tourism is a big growth business in all countries. Bus Reservation System deals with maintenance of records details of each passenger. It also includes maintenance of information such as timetable and details in each bus.
For More :
https://www.facebook.com/Computer-Programming-Assignments-826290177441561/
-
https://www.facebook.com/A-Tech-and-Software-Development-1683037138630673/
Stacks, Queues, and Deques describes different data structures and their properties. Stacks follow LIFO order with insertion and removal at the same end. Queues follow FIFO order with insertion at one end and removal at the other. Deques allow insertion and removal at both ends. These structures can be implemented using arrays or linked lists.
The document summarizes the findings of a survey conducted of software houses to determine what they offer to freshly graduated computer science students and the skills required for jobs. The survey found that software houses offer permanent jobs, contract-based jobs, and opportunities through third parties. They are looking for graduates with skills like quickly learning new concepts, problem solving, communication, and teamwork. Specific software houses like INBOX and FOLIO3 were visited and offer internships while requiring skills and qualifications like expertise in programming languages, GPA, and problem solving.
This document describes a traffic light controller project using an AT89C51 microcontroller. It provides the history of traffic lights, descriptions of red, yellow, and green light meanings. The project uses LED lights controlled by a microcontroller on specific ports to automatically change the light signals after a time interval. It includes components like the microcontroller, LED lights, resistors, and diagrams of the circuit and block designs. The microcontroller is programmed to set bits to glow the LED lights in sequence with delays to control the traffic light signals.
This document describes a Canteen Store Department (CSD) project that aims to develop software to manage a CSD store. The software will allow users to track products in stock, record purchases and sales, manage payments and accounts, and maintain employee records. It will use the waterfall model for development. The software is intended to help CSD stores address current issues like maintaining daily records, calculating profits and sales, and finding specific products. It will be developed in Java using Netbeans as the IDE, and will incorporate a SQL Server 2008 database to store data. The software is targeted towards small CSD stores and aims to automate their manual record keeping processes.
The document outlines the key developmental stages of a chicken embryo over a 21-day period within an egg. It notes the formation of major organs from days 1-15, including the eyes, heart, reproductive organs, feathers, beak, toes, and intestines. By day 16, the embryo is fully covered with feathers and nearly finished growing. On day 20, it becomes a chick and starts breathing air. Finally, on day 21, the chick uses its egg tooth to pip through the shell and hatch.
Keyboards are external input devices used to type data into computers and include alphabetic, numerical, and symbol keys. They connect to devices via serial or USB ports. Mice are also input devices that send click information to computers and offer an alternative to keyboard interaction. Typical mice have two buttons and a scroll wheel. The motherboard connects all computer parts like the CPU, memory, drives, and ports and acts as the computer's backbone. Processors are microchips that process instructions from software and come from manufacturers like Intel and AMD, with higher gigahertz capacities providing faster processing. Printers are external devices that take computer data and print hard copies of text, images, and photos. Speakers receive audio input from sound cards
The document discusses various topics related to banking. It defines banks and their role in facilitating financial transactions. It describes the basic business model of banks, which involves taking deposits and providing loans. It also outlines the key functions of banks such as payment processing, offering different account types, generating revenue, managing risks, and more. The document also discusses computerized banking systems and how they can improve efficiency.
This document discusses a proposed information system for a bank management system. It outlines the goals of allowing customers to access their accounts online to view balances, transaction histories, statements and transfer money. It also discusses weaknesses in the current system like slow transactions and a lack of rural access. The proposed system aims to improve customer satisfaction, save time and protect privacy by enabling online banking and transactions through increased technology and automation while maintaining security. A SWOT analysis identifies strengths like existing infrastructure but also weaknesses in customer service and opportunities in growing markets and new technologies.
The bank management system is an application that allows customers to create and manage bank accounts. It provides functionality for customers to open new accounts, deposit and withdraw funds, and view reports on all accounts. The document outlines the requirements, functionality, and design of the system.
Villages in Sindh province typically consisted of hundreds to thousands of residents, mostly farmers, with houses, barns, and animal pens clustered around a central area surrounded by fields. Village life was influenced by outside market and landlord pressures, and many residents eventually moved to larger cities. Sindh province was home to one of the world's earliest civilizations and today village life provides a calm environment with green spaces and fresh water compared to busy city living.
The document discusses different definitions and types of media. It defines media as something that serves as an intermediary for transferring information from various sources to people. Media has evolved over time from printed materials to a large industry encompassing different types of media like broadcast, digital, and electronic media. The document also notes that media can influence people's knowledge, behavior, attitudes, emotions, and political views, but it can also be manipulated to spread false information. It concludes by discussing the role of media in society and some steps that could help ensure the credibility of media.
This document provides an overview of wound healing, its functions, stages, mechanisms, factors affecting it, and complications.
A wound is a break in the integrity of the skin or tissues, which may be associated with disruption of the structure and function.
Healing is the body’s response to injury in an attempt to restore normal structure and functions.
Healing can occur in two ways: Regeneration and Repair
There are 4 phases of wound healing: hemostasis, inflammation, proliferation, and remodeling. This document also describes the mechanism of wound healing. Factors that affect healing include infection, uncontrolled diabetes, poor nutrition, age, anemia, the presence of foreign bodies, etc.
Complications of wound healing like infection, hyperpigmentation of scar, contractures, and keloid formation.
Gender and Mental Health - Counselling and Family Therapy Applications and In...PsychoTech Services
A proprietary approach developed by bringing together the best of learning theories from Psychology, design principles from the world of visualization, and pedagogical methods from over a decade of training experience, that enables you to: Learn better, faster!
Leveraging Generative AI to Drive Nonprofit InnovationTechSoup
In this webinar, participants learned how to utilize Generative AI to streamline operations and elevate member engagement. Amazon Web Service experts provided a customer specific use cases and dived into low/no-code tools that are quick and easy to deploy through Amazon Web Service (AWS.)
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...EduSkills OECD
Andreas Schleicher, Director of Education and Skills at the OECD presents at the launch of PISA 2022 Volume III - Creative Minds, Creative Schools on 18 June 2024.
This presentation was provided by Rebecca Benner, Ph.D., of the American Society of Anesthesiologists, for the second session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session Two: 'Expanding Pathways to Publishing Careers,' was held June 13, 2024.
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...indexPub
The recent surge in pro-Palestine student activism has prompted significant responses from universities, ranging from negotiations and divestment commitments to increased transparency about investments in companies supporting the war on Gaza. This activism has led to the cessation of student encampments but also highlighted the substantial sacrifices made by students, including academic disruptions and personal risks. The primary drivers of these protests are poor university administration, lack of transparency, and inadequate communication between officials and students. This study examines the profound emotional, psychological, and professional impacts on students engaged in pro-Palestine protests, focusing on Generation Z's (Gen-Z) activism dynamics. This paper explores the significant sacrifices made by these students and even the professors supporting the pro-Palestine movement, with a focus on recent global movements. Through an in-depth analysis of printed and electronic media, the study examines the impacts of these sacrifices on the academic and personal lives of those involved. The paper highlights examples from various universities, demonstrating student activism's long-term and short-term effects, including disciplinary actions, social backlash, and career implications. The researchers also explore the broader implications of student sacrifices. The findings reveal that these sacrifices are driven by a profound commitment to justice and human rights, and are influenced by the increasing availability of information, peer interactions, and personal convictions. The study also discusses the broader implications of this activism, comparing it to historical precedents and assessing its potential to influence policy and public opinion. The emotional and psychological toll on student activists is significant, but their sense of purpose and community support mitigates some of these challenges. However, the researchers call for acknowledging the broader Impact of these sacrifices on the future global movement of FreePalestine.
A Visual Guide to 1 Samuel | A Tale of Two HeartsSteve Thomason
These slides walk through the story of 1 Samuel. Samuel is the last judge of Israel. The people reject God and want a king. Saul is anointed as the first king, but he is not a good king. David, the shepherd boy is anointed and Saul is envious of him. David shows honor while Saul continues to self destruct.
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptxCapitolTechU
Slides from a Capitol Technology University webinar held June 20, 2024. The webinar featured Dr. Donovan Wright, presenting on the Department of Defense Digital Transformation.
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
Primitive Data Types and Variables Lesson 02
1. Primitive DataPrimitive Data
Types andVariablesTypes andVariables
Creating and RunningYour First C# ProgramCreating and RunningYour First C# Program
Arshman SaleemArshman Saleem
A Tech & Software DevelopmentA Tech & Software Development
2. Table of ContentsTable of Contents
1.1. Primitive Data TypesPrimitive Data Types
IntegerInteger
Floating-Point / Decimal Floating-PointFloating-Point / Decimal Floating-Point
BooleanBoolean
CharacterCharacter
StringString
ObjectObject
1.1. Declaring and Using VariablesDeclaring and Using Variables
IdentifiersIdentifiers
Declaring Variables and Assigning ValuesDeclaring Variables and Assigning Values
LiteralsLiterals
1.1. NullableNullable typestypes
2
4. How Computing Works?How Computing Works?
Computers are machines that process dataComputers are machines that process data
Data is stored in the computer memory inData is stored in the computer memory in
variablesvariables
Variables haveVariables have namename,, data typedata type andand valuevalue
Example of variable definition and assignmentExample of variable definition and assignment
in C#in C#
int count = 5;int count = 5;
Data typeData type
Variable nameVariable name
Variable valueVariable value
4
5. What Is a Data Type?What Is a Data Type?
AA data typedata type::
Is a domain of values of similar characteristicsIs a domain of values of similar characteristics
Defines the type of information stored in theDefines the type of information stored in the
computer memory (in a variable)computer memory (in a variable)
Examples:Examples:
Positive integers:Positive integers: 11,, 22,, 33,, ……
Alphabetical characters:Alphabetical characters: aa,, bb,, cc,, ……
Days of week:Days of week: MondayMonday,, TuesdayTuesday,, ……
5
6. Data Type CharacteristicsData Type Characteristics
A data type has:A data type has:
Name (C# keyword or .NET type)Name (C# keyword or .NET type)
Size (how much memory is used)Size (how much memory is used)
Default valueDefault value
Example:Example:
Integer numbers in C#Integer numbers in C#
Name:Name: intint
Size: 32 bits (4 bytes)Size: 32 bits (4 bytes)
Default value: 0Default value: 0
6
8. What are Integer Types?What are Integer Types?
Integer types:Integer types:
Represent whole numbersRepresent whole numbers
May be signed or unsignedMay be signed or unsigned
Have range of values, depending on the size ofHave range of values, depending on the size of
memory usedmemory used
The default value of integer types is:The default value of integer types is:
00 – for integer types, except– for integer types, except
0L0L – for the– for the longlong typetype
8
9. Integer TypesInteger Types
Integer types are:Integer types are:
sbytesbyte (-128 to 127): signed 8-bit(-128 to 127): signed 8-bit
bytebyte (0 to 255): unsigned 8-bit(0 to 255): unsigned 8-bit
shortshort (-32,768 to 32,767): signed 16-bit(-32,768 to 32,767): signed 16-bit
ushortushort (0 to 65,535): unsigned 16-bit(0 to 65,535): unsigned 16-bit
intint (-2,147,483,648 to 2,147,483,647): signed(-2,147,483,648 to 2,147,483,647): signed
32-bit32-bit
uintuint (0 to 4,294,967,295): unsigned 32-bit(0 to 4,294,967,295): unsigned 32-bit
9
10. Integer Types (2)Integer Types (2)
More integer types:More integer types:
longlong (-9,223,372,036,854,775,808 to(-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807): signed 64-bit9,223,372,036,854,775,807): signed 64-bit
ulongulong (0 to 18,446,744,073,709,551,615):(0 to 18,446,744,073,709,551,615):
unsigned 64-bitunsigned 64-bit
10
11. Measuring Time – ExampleMeasuring Time – Example
Depending on the unit of measure we may useDepending on the unit of measure we may use
different data types:different data types:
byte centuries = 20; // Usually a small numberbyte centuries = 20; // Usually a small number
ushort years = 2000;ushort years = 2000;
uint days = 730480;uint days = 730480;
ulong hours = 17531520; // May be a very big numberulong hours = 17531520; // May be a very big number
Console.WriteLine("{0} centuries is {1} years, orConsole.WriteLine("{0} centuries is {1} years, or
{2} days, or {3} hours.", centuries, years, days,{2} days, or {3} hours.", centuries, years, days,
hours);hours);
11
14. What are Floating-Point Types?What are Floating-Point Types?
Floating-point types:Floating-point types:
Represent real numbersRepresent real numbers
May be signed or unsignedMay be signed or unsigned
Have range of values and different precisionHave range of values and different precision
depending on the used memorydepending on the used memory
Can behave abnormally in the calculationsCan behave abnormally in the calculations
14
15. Floating-Point TypesFloating-Point Types
Floating-point types are:Floating-point types are:
floatfloat (±1.5 × 10(±1.5 × 10−45−45
to ±3.4 × 10to ±3.4 × 103838
): 32-bits,): 32-bits,
precision of 7 digitsprecision of 7 digits
doubledouble (±5.0 × 10(±5.0 × 10−324−324
to ±1.7 × 10to ±1.7 × 10308308
): 64-bits,): 64-bits,
precision of 15-16 digitsprecision of 15-16 digits
The default value of floating-point types:The default value of floating-point types:
IsIs 0.0F0.0F for thefor the floatfloat typetype
IsIs 0.0D0.0D for thefor the doubledouble typetype
15
16. PI Precision – ExamplePI Precision – Example
See below the difference in precision when usingSee below the difference in precision when using
floatfloat andand doubledouble::
NOTE: The “NOTE: The “ff” suffix in the first statement!” suffix in the first statement!
Real numbers are by default interpreted asReal numbers are by default interpreted as doubledouble!!
One shouldOne should explicitlyexplicitly convert them toconvert them to floatfloat
float floatPI = 3.141592653589793238f;float floatPI = 3.141592653589793238f;
double doublePI = 3.141592653589793238;double doublePI = 3.141592653589793238;
Console.WriteLine("Float PI is: {0}", floatPI);Console.WriteLine("Float PI is: {0}", floatPI);
Console.WriteLine("Double PI is: {0}", doublePI);Console.WriteLine("Double PI is: {0}", doublePI);
16
17. Abnormalities in theAbnormalities in the
Floating-Point CalculationsFloating-Point Calculations
Sometimes abnormalities can be observedSometimes abnormalities can be observed
when using floating-point numberswhen using floating-point numbers
Comparing floating-point numbers can not beComparing floating-point numbers can not be
performed directly with theperformed directly with the ==== operatoroperator
Example:Example:
double a = 1.0f;double a = 1.0f;
double b = 0.33f;double b = 0.33f;
double sum = 1.33f;double sum = 1.33f;
bool equal = (a+b == sum); // False!!!bool equal = (a+b == sum); // False!!!
Console.WriteLine("a+b={0} sum={1} equal={2}",Console.WriteLine("a+b={0} sum={1} equal={2}",
a+b, sum, equal);a+b, sum, equal);
17
18. Decimal Floating-Point TypesDecimal Floating-Point Types
There is a special decimal floating-pointThere is a special decimal floating-point
real number type in C#:real number type in C#:
decimaldecimal (±1,0 × 10(±1,0 × 10-28-28
to ±7,9 × 10to ±7,9 × 102828
): 128-bits,): 128-bits,
precision of 28-29 digitsprecision of 28-29 digits
Used for financial calculationsUsed for financial calculations
No round-off errorsNo round-off errors
Almost no loss of precisionAlmost no loss of precision
The default value ofThe default value of decimaldecimal type is:type is:
0.00.0MM ((MM is the suffix for decimal numbers)is the suffix for decimal numbers)
18
21. The Boolean Data TypeThe Boolean Data Type
TheThe Boolean data typeBoolean data type::
Is declared by theIs declared by the boolbool keywordkeyword
Has two possible values:Has two possible values: truetrue andand falsefalse
Is useful in logical expressionsIs useful in logical expressions
The default value isThe default value is falsefalse
21
22. Boolean Values – ExampleBoolean Values – Example
Example of boolean variables taking values ofExample of boolean variables taking values of
truetrue oror falsefalse::
int a = 1;int a = 1;
int b = 2;int b = 2;
bool greaterAB = (a > b);bool greaterAB = (a > b);
Console.WriteLine(greaterAB); // FalseConsole.WriteLine(greaterAB); // False
bool equalA1 = (a == 1);bool equalA1 = (a == 1);
Console.WriteLine(equalA1); // TrueConsole.WriteLine(equalA1); // True
22
25. The Character Data TypeThe Character Data Type
TheThe character data typecharacter data type::
Represents symbolic informationRepresents symbolic information
Is declared by theIs declared by the charchar keywordkeyword
Gives each symbol a corresponding integer codeGives each symbol a corresponding integer code
Has aHas a '0''0' default valuedefault value
Takes 16 bits of memory (fromTakes 16 bits of memory (from U+0000U+0000 toto
U+FFFFU+FFFF))
25
26. Characters and CodesCharacters and Codes
The example below shows that every symbolThe example below shows that every symbol
has an its unique Unicode code:has an its unique Unicode code:
char symbol = 'a';char symbol = 'a';
Console.WriteLine("The code of '{0}' is: {1}",Console.WriteLine("The code of '{0}' is: {1}",
symbol, (int) symbol);symbol, (int) symbol);
symbol = 'b';symbol = 'b';
Console.WriteLine("The code of '{0}' is: {1}",Console.WriteLine("The code of '{0}' is: {1}",
symbol, (int) symbol);symbol, (int) symbol);
symbol = 'A';symbol = 'A';
Console.WriteLine("The code of '{0}' is: {1}",Console.WriteLine("The code of '{0}' is: {1}",
symbol, (int) symbol);symbol, (int) symbol);
26
29. The String Data TypeThe String Data Type
TheThe string data typestring data type::
Represents a sequence of charactersRepresents a sequence of characters
Is declared by theIs declared by the stringstring keywordkeyword
Has a default valueHas a default value nullnull (no value)(no value)
Strings are enclosed in quotes:Strings are enclosed in quotes:
Strings can be concatenatedStrings can be concatenated
Using theUsing the ++ operatoroperator
string s = "Microsoft .NET Framework";string s = "Microsoft .NET Framework";
29
30. Saying Hello – ExampleSaying Hello – Example
Concatenating the two names of a person toConcatenating the two names of a person to
obtain his full name:obtain his full name:
NOTE: a space is missing between the twoNOTE: a space is missing between the two
names! We have to add it manuallynames! We have to add it manually
string firstName = "Ivan";string firstName = "Ivan";
string lastName = "Ivanov";string lastName = "Ivanov";
Console.WriteLine("Hello, {0}!n", firstName);Console.WriteLine("Hello, {0}!n", firstName);
string fullName = firstName + " " + lastName;string fullName = firstName + " " + lastName;
Console.WriteLine("Your full name is {0}.",Console.WriteLine("Your full name is {0}.",
fullName);fullName);
30
33. The Object TypeThe Object Type
The object type:The object type:
Is declared by theIs declared by the objectobject keywordkeyword
Is the base type of all other typesIs the base type of all other types
Can hold values of any typeCan hold values of any type
33
34. Using ObjectsUsing Objects
Example of an object variable taking differentExample of an object variable taking different
types of data:types of data:
object dataContainer = 5;object dataContainer = 5;
Console.Write("The value of dataContainer is: ");Console.Write("The value of dataContainer is: ");
Console.WriteLine(dataContainer);Console.WriteLine(dataContainer);
dataContainer = "Five";dataContainer = "Five";
Console.Write("The value of dataContainer is: ");Console.Write("The value of dataContainer is: ");
Console.WriteLine(dataContainer);Console.WriteLine(dataContainer);
34
37. What Is a Variable?What Is a Variable?
A variable is a:A variable is a:
Placeholder of information that can usually bePlaceholder of information that can usually be
changed at run-timechanged at run-time
Variables allow you to:Variables allow you to:
Store informationStore information
Retrieve the stored informationRetrieve the stored information
Manipulate the stored informationManipulate the stored information
37
40. Declaring VariablesDeclaring Variables
When declaring a variable we:When declaring a variable we:
Specify its typeSpecify its type
Specify its name (called identifier)Specify its name (called identifier)
May give it an initial valueMay give it an initial value
The syntax is the following:The syntax is the following:
Example:Example:
<data_type> <identifier> [= <initialization>];<data_type> <identifier> [= <initialization>];
int height = 200;int height = 200;
40
41. IdentifiersIdentifiers
Identifiers may consist of:Identifiers may consist of:
Letters (Unicode)Letters (Unicode)
Digits [0-9]Digits [0-9]
Underscore "_"Underscore "_"
IdentifiersIdentifiers
Can begin only with a letter or an underscoreCan begin only with a letter or an underscore
Cannot be a C# keywordCannot be a C# keyword
41
42. Identifiers (2)Identifiers (2)
IdentifiersIdentifiers
Should have a descriptive nameShould have a descriptive name
It is recommended to use only Latin lettersIt is recommended to use only Latin letters
Should be neither too long nor too shortShould be neither too long nor too short
Note:Note:
In C# small letters are considered different thanIn C# small letters are considered different than
the capital letters (case sensitivity)the capital letters (case sensitivity)
42
43. Identifiers – ExamplesIdentifiers – Examples
Examples of correct identifiers:Examples of correct identifiers:
Examples of incorrect identifiers:Examples of incorrect identifiers:
int new;int new; // new is a keyword// new is a keyword
int 2Pac;int 2Pac; // Cannot begin with a digit// Cannot begin with a digit
int New = 2; // Here N is capitalint New = 2; // Here N is capital
int _2Pac; // This identifiers begins with _int _2Pac; // This identifiers begins with _
string поздрав = "Hello"; // Unicode symbols usedstring поздрав = "Hello"; // Unicode symbols used
// The following is more appropriate:// The following is more appropriate:
string greeting = "Hello";string greeting = "Hello";
int n = 100; // Undescriptiveint n = 100; // Undescriptive
int numberOfClients = 100; // Descriptiveint numberOfClients = 100; // Descriptive
// Overdescriptive identifier:// Overdescriptive identifier:
int numberOfPrivateClientOfTheFirm = 100;int numberOfPrivateClientOfTheFirm = 100;
43
45. Assigning ValuesAssigning Values
Assigning of values to variablesAssigning of values to variables
Is achieved by theIs achieved by the == operatoroperator
TheThe == operator hasoperator has
Variable identifier on the leftVariable identifier on the left
Value of the corresponding data type on theValue of the corresponding data type on the
rightright
Could be used in a cascade calling, whereCould be used in a cascade calling, where
assigning is done from right to leftassigning is done from right to left
45
46. Assigning Values – ExamplesAssigning Values – Examples
Assigning values example:Assigning values example:
int firstValue = 5;int firstValue = 5;
int secondValue;int secondValue;
int thirdValue;int thirdValue;
// Using an already declared variable:// Using an already declared variable:
secondValue = firstValue;secondValue = firstValue;
// The following cascade calling assigns// The following cascade calling assigns
// 3 to firstValue and then firstValue// 3 to firstValue and then firstValue
// to thirdValue, so both variables have// to thirdValue, so both variables have
// the value 3 as a result:// the value 3 as a result:
thirdValue = firstValue = 3; // Avoid this!thirdValue = firstValue = 3; // Avoid this!
46
47. Initializing VariablesInitializing Variables
InitializingInitializing
Is assigning of initial valueIs assigning of initial value
Must be done before the variable is used!Must be done before the variable is used!
Several ways of initializing:Several ways of initializing:
By using theBy using the newnew keywordkeyword
By using a literal expressionBy using a literal expression
By referring to an already initialized variableBy referring to an already initialized variable
47
48. Initialization – ExamplesInitialization – Examples
Example of some initializations:Example of some initializations:
// The following would assign the default// The following would assign the default
// value of the int type to num:// value of the int type to num:
int num = new int(); // num = 0int num = new int(); // num = 0
// This is how we use a literal expression:// This is how we use a literal expression:
float heightInMeters = 1.74f;float heightInMeters = 1.74f;
// Here we use an already initialized variable:// Here we use an already initialized variable:
string greeting = "Hello World!";string greeting = "Hello World!";
string message = greeting;string message = greeting;
48
51. What are Literals?What are Literals?
Literals are:Literals are:
Representations of values in the source codeRepresentations of values in the source code
There are six types of literalsThere are six types of literals
BooleanBoolean
IntegerInteger
RealReal
CharacterCharacter
StringString
TheThe nullnull literalliteral
51
52. Boolean and Integer LiteralsBoolean and Integer Literals
The boolean literals are:The boolean literals are:
truetrue
falsefalse
The integer literals:The integer literals:
Are used for variables of typeAre used for variables of type intint,, uintuint,, longlong,,
andand ulongulong
Consist of digitsConsist of digits
May have a sign (May have a sign (++,,--))
May be in a hexadecimal formatMay be in a hexadecimal format
52
53. Integer LiteralsInteger Literals
Examples of integer literalsExamples of integer literals
TheThe ''0x0x'' andand ''0X0X'' prefixes mean aprefixes mean a
hexadecimal value, e.g.hexadecimal value, e.g. 0xA8F10xA8F1
TheThe ''uu'' andand ''UU'' suffixes mean asuffixes mean a ulongulong oror uintuint
type, e.g.type, e.g. 12345678U12345678U
TheThe ''ll'' andand ''LL'' suffixes mean asuffixes mean a longlong oror ulongulong
type, e.g.type, e.g. 9876543L9876543L
53
54. Integer Literals – ExampleInteger Literals – Example
Note: the letter ‘Note: the letter ‘ll’ is easily confused with the’ is easily confused with the
digit ‘digit ‘11’ so it’s better to use ‘’ so it’s better to use ‘LL’!!!’!!!
// The following variables are// The following variables are
// initialized with the same value:// initialized with the same value:
int numberInHex = -0x10;int numberInHex = -0x10;
int numberInDec = -16;int numberInDec = -16;
// The following causes an error,// The following causes an error,
because 234u is of type uintbecause 234u is of type uint
int unsignedInt = 234u;int unsignedInt = 234u;
// The following causes an error,// The following causes an error,
because 234L is of type longbecause 234L is of type long
int longInt = 234L;int longInt = 234L;
54
55. Real LiteralsReal Literals
The real literals:The real literals:
Are used for values of typeAre used for values of type floatfloat,, doubledouble andand
decimaldecimal
May consist of digits, a sign and “May consist of digits, a sign and “..””
May be in exponential notation:May be in exponential notation: 6.02e+236.02e+23
The “The “ff” and “” and “FF” suffixes mean” suffixes mean floatfloat
The “The “dd” and “” and “DD” suffixes mean” suffixes mean doubledouble
The “The “mm” and “” and “MM” suffixes mean” suffixes mean decimaldecimal
The default interpretation isThe default interpretation is doubledouble
55
56. Real Literals – ExampleReal Literals – Example
Example of incorrectExample of incorrect floatfloat literal:literal:
A correct way to assign floating-point valueA correct way to assign floating-point value
(using also the exponential format):(using also the exponential format):
56
// The following causes an error// The following causes an error
// because 12.5 is double by default// because 12.5 is double by default
float realNumber = 12.5;float realNumber = 12.5;
// The following is the correct// The following is the correct
// way of assigning the value:// way of assigning the value:
float realNumber = 12.5f;float realNumber = 12.5f;
// This is the same value in exponential format:// This is the same value in exponential format:
realNumber = 1.25e+7f;realNumber = 1.25e+7f;
57. Character LiteralsCharacter Literals
The character literals:The character literals:
Are used for values of theAre used for values of the charchar typetype
Consist of two single quotes surrounding theConsist of two single quotes surrounding the
character value:character value: ''<value><value>''
The value may be:The value may be:
SymbolSymbol
The code of the symbolThe code of the symbol
Escaping sequenceEscaping sequence
57
58. Escaping SequencesEscaping Sequences
Escaping sequences are:Escaping sequences are:
Means of presenting a symbol that is usuallyMeans of presenting a symbol that is usually
interpreted otherwise (likeinterpreted otherwise (like ''))
Means of presenting system symbols (like theMeans of presenting system symbols (like the
new line symbol)new line symbol)
Common escaping sequences are:Common escaping sequences are:
'' for single quotefor single quote "" for double quotefor double quote
for backslashfor backslash nn for new linefor new line
uXXXXuXXXX for denoting any other Unicode symbolfor denoting any other Unicode symbol
58
59. Character Literals – ExampleCharacter Literals – Example
Examples of different character literals:Examples of different character literals:
char symbol = 'a'; // An ordinary symbolchar symbol = 'a'; // An ordinary symbol
symbol = 'u006F'; // Unicode symbol code insymbol = 'u006F'; // Unicode symbol code in
// a hexadecimal format// a hexadecimal format
symbol = 'u8449'; //symbol = 'u8449'; // 葉葉 ((Leaf in Traditional Chinese)Leaf in Traditional Chinese)
symbol = '''; // Assigning the single quote symbolsymbol = '''; // Assigning the single quote symbol
symbol = ''; // Assigning the backslash symbolsymbol = ''; // Assigning the backslash symbol
symbol = 'n'; // Assigning new line symbolsymbol = 'n'; // Assigning new line symbol
symbol = 't'; // Assigning TAB symbolsymbol = 't'; // Assigning TAB symbol
symbol = "a"; // Incorrect: use single quotessymbol = "a"; // Incorrect: use single quotes
59
60. String LiteralsString Literals
String literals:String literals:
Are used for values of the string typeAre used for values of the string type
Consist of two double quotes surrounding theConsist of two double quotes surrounding the
value:value: ""<value><value>""
May have aMay have a @@ prefix which ignores the usedprefix which ignores the used
escaping sequences:escaping sequences: @@"<value>""<value>"
The value is a sequence of character literalsThe value is a sequence of character literals
string s = "I am a sting literal";string s = "I am a sting literal";
60
61. String Literals – ExampleString Literals – Example
Benefits of quoted strings (theBenefits of quoted strings (the @@ prefix):prefix):
In quoted stringsIn quoted strings "" is used instead ofis used instead of """"!!
// Here is a string literal using escape sequences// Here is a string literal using escape sequences
string quotation = ""Hello, Jude", he said.";string quotation = ""Hello, Jude", he said.";
string path = "C:WINNTDartsDarts.exe";string path = "C:WINNTDartsDarts.exe";
// Here is an example of the usage of @// Here is an example of the usage of @
quotation = @"""Hello, Jimmy!"", she answered.";quotation = @"""Hello, Jimmy!"", she answered.";
path = @"C:WINNTDartsDarts.exe";path = @"C:WINNTDartsDarts.exe";
string str = @"somestring str = @"some
text";text";
61
64. Nullable TypesNullable Types
NullableNullable types are instances of thetypes are instances of the
System.NullableSystem.Nullable structstruct
Wrapper over theWrapper over the primitiveprimitive typestypes
E.g.E.g. int?int?,, double?double?, etc., etc.
NullabeNullabe type can represent the normal rangetype can represent the normal range
of values for its underlying value type, plus anof values for its underlying value type, plus an
additionaladditional nullnull valuevalue
Useful when dealing withUseful when dealing with DatabasesDatabases or otheror other
structures that have default valuestructures that have default value nullnull
65. Nullable Types – ExampleNullable Types – Example
int? someInteger = null;int? someInteger = null;
Console.WriteLine(Console.WriteLine(
"This is the integer with Null value -> " + someInteger);"This is the integer with Null value -> " + someInteger);
someInteger = 5;someInteger = 5;
Console.WriteLine(Console.WriteLine(
"This is the integer with value 5 -> " + someInteger);"This is the integer with value 5 -> " + someInteger);
double? someDouble = null;double? someDouble = null;
Console.WriteLine(Console.WriteLine(
"This is the real number with Null value -> ""This is the real number with Null value -> "
+ someDouble);+ someDouble);
someDouble = 2.5;someDouble = 2.5;
Console.WriteLine(Console.WriteLine(
"This is the real number with value 5 -> " +"This is the real number with value 5 -> " +
someDouble);someDouble);
Example withExample with IntegerInteger::
Example withExample with DoubleDouble::
68. ExercisesExercises
1.1. Declare five variables choosing for each of them theDeclare five variables choosing for each of them the
most appropriate of the typesmost appropriate of the types bytebyte,, sbytesbyte,, shortshort,,
ushortushort,, intint,, uintuint,, longlong,, ulongulong to represent theto represent the
following values: 52130, -115, 4825932, 97, -10000.following values: 52130, -115, 4825932, 97, -10000.
2.2. Which of the following values can be assigned to aWhich of the following values can be assigned to a
variable of typevariable of type floatfloat and which to a variable ofand which to a variable of
typetype doubledouble: 34.567839023, 12.345, 8923.1234857,: 34.567839023, 12.345, 8923.1234857,
3456.091?3456.091?
3.3. Write a program that safely compares floating-pointWrite a program that safely compares floating-point
numbers with precision ofnumbers with precision of 0.0000010.000001..
68
69. Exercises (2)Exercises (2)
4.4. Declare an integer variable and assign it with theDeclare an integer variable and assign it with the
value 254 in hexadecimal format. Use Windowsvalue 254 in hexadecimal format. Use Windows
Calculator to find its hexadecimal representation.Calculator to find its hexadecimal representation.
5.5. Declare a character variable and assign it with theDeclare a character variable and assign it with the
symbol that has Unicode code 72. Hint: first use thesymbol that has Unicode code 72. Hint: first use the
Windows Calculator to find the hexadecimalWindows Calculator to find the hexadecimal
representation of 72.representation of 72.
6.6. Declare a boolean variable calledDeclare a boolean variable called isFemaleisFemale andand
assign an appropriate value corresponding to yourassign an appropriate value corresponding to your
gender.gender.
69
70. Exercises (3)Exercises (3)
7.7. Declare twoDeclare two stringstring variables and assign them withvariables and assign them with
“Hello” and “World”. Declare an“Hello” and “World”. Declare an objectobject variable andvariable and
assign it with the concatenation of the first twoassign it with the concatenation of the first two
variables (mind adding an interval). Declare a thirdvariables (mind adding an interval). Declare a third
stringstring variable and initialize it with the value of thevariable and initialize it with the value of the
object variable (you should perform type casting).object variable (you should perform type casting).
8.8. Declare twoDeclare two stringstring variables and assign them withvariables and assign them with
following value:following value:
Do the above in two different ways: with and withoutDo the above in two different ways: with and without
using quoted strings.using quoted strings.
The "use" of quotations causes difficulties.The "use" of quotations causes difficulties.
70