The document discusses various computational concepts including expressions, selection, iteration, functions, and vectors. It explains that expressions are made up of operators and operands and discusses common operators. Selection uses if/else statements to choose between alternatives. Iteration is covered using a while loop example to calculate and print squares from 0 to 99. Functions allow naming and specifying sub-computations. Vectors are introduced to hold sequences of values for more realistic computations.
This document contains a C programming assignment submitted by Vijayananda D Mohire for their Post Graduate Diploma in Information Technology. The assignment contains 11 questions on basic C programming concepts like data types, variables, functions, structures, file handling etc. For each question, the code for the algorithm/program is provided as the answer. The questions cover topics like checking odd/even numbers, calculating sum of numbers, interest calculation, number divisibility, swapping values, month to word conversion using switch case, structure to store employee data, reading and writing to files.
The document discusses C programming concepts including operators, loops, functions, pointers, and file handling. It contains sample code to demonstrate:
1) Summing integers entered interactively using a while loop.
2) Calculating the average length of text lines using global variables and functions.
3) Adding and subtracting numbers using pointer variables and dereferencing operators.
4) Checking for a null pointer and using it as a placeholder.
5) Searching a specified file for a given character using command line arguments.
Object Orientation vs. Functional Programming in PythonPython Ireland
The document discusses object orientation and functional programming approaches in Python. It covers various object-oriented programming concepts like the template method pattern, abstract base classes, mixins, and composition. It also covers functional programming concepts like callbacks, higher-order functions, decorators, and partial function application. It concludes that Python supports both paradigms well and that depending on the situation, one approach may be more appropriate, but the tools can also complement each other.
This document provides an overview of the Lecture 2 on Declarative Syntax Definition for the CS4200 Compiler Construction course. The lecture covers the specification of syntax definition from which parsers can be derived, the perspective on declarative syntax definition using SDF, and reading material on the SDF3 syntax definition formalism and papers on testing syntax definitions and declarative syntax. It also discusses what syntax is, both in linguistics and programming languages, and how programs can be described in terms of syntactic categories and language constructs. An example Tiger program for solving the n-queens problem is presented to illustrate syntactic categories in Tiger.
This document discusses syntactic editor services including formatting, syntax coloring, and syntactic completion. It describes how syntactic completion can be provided generically based on a syntax definition. The document also discusses how context-free grammars can be extended with templates to specify formatting layout when pretty-printing abstract syntax trees to text. Templates are used to insert whitespace, line breaks, and indentation to produce readable output.
This document summarizes and discusses type checking algorithms for programming languages. It introduces constraint-based type checking, which separates type checking into constraint generation and constraint solving. This provides a more declarative way to specify type checkers. The document discusses using variables and constraints to represent types during type checking. It introduces NaBL2, a domain-specific language for writing constraint generators to specify name and type constraints for programming language static semantics. NaBL2 uses scope graphs to represent name binding structures and supports features like type equality, subtyping, and type-dependent name resolution through constraint rules. An example scope graph and constraint rule for let-bindings is provided.
This document discusses functional programming (FP) and its benefits compared to object-oriented programming (OOP). It defines FP as programming with pure functions that have no side effects. The document explores eliminating side effects through techniques like separating function concerns and returning descriptions of side effects rather than executing them. It also covers FP concepts like higher order functions, recursion, and data types like Option for handling errors/exceptions. The goal is to introduce FP techniques and when each paradigm (FP vs OOP) is best suited.
Declare Your Language: Name ResolutionEelco Visser
Scope graphs are used to represent the binding information in programs. They provide a language-independent representation of name resolution that can be used to conduct and represent the results of name resolution. Separating the representation of resolved programs from the declarative rules that define name binding allows language-independent tooling to be developed for name resolution and other tasks.
This document contains a C programming assignment submitted by Vijayananda D Mohire for their Post Graduate Diploma in Information Technology. The assignment contains 11 questions on basic C programming concepts like data types, variables, functions, structures, file handling etc. For each question, the code for the algorithm/program is provided as the answer. The questions cover topics like checking odd/even numbers, calculating sum of numbers, interest calculation, number divisibility, swapping values, month to word conversion using switch case, structure to store employee data, reading and writing to files.
The document discusses C programming concepts including operators, loops, functions, pointers, and file handling. It contains sample code to demonstrate:
1) Summing integers entered interactively using a while loop.
2) Calculating the average length of text lines using global variables and functions.
3) Adding and subtracting numbers using pointer variables and dereferencing operators.
4) Checking for a null pointer and using it as a placeholder.
5) Searching a specified file for a given character using command line arguments.
Object Orientation vs. Functional Programming in PythonPython Ireland
The document discusses object orientation and functional programming approaches in Python. It covers various object-oriented programming concepts like the template method pattern, abstract base classes, mixins, and composition. It also covers functional programming concepts like callbacks, higher-order functions, decorators, and partial function application. It concludes that Python supports both paradigms well and that depending on the situation, one approach may be more appropriate, but the tools can also complement each other.
This document provides an overview of the Lecture 2 on Declarative Syntax Definition for the CS4200 Compiler Construction course. The lecture covers the specification of syntax definition from which parsers can be derived, the perspective on declarative syntax definition using SDF, and reading material on the SDF3 syntax definition formalism and papers on testing syntax definitions and declarative syntax. It also discusses what syntax is, both in linguistics and programming languages, and how programs can be described in terms of syntactic categories and language constructs. An example Tiger program for solving the n-queens problem is presented to illustrate syntactic categories in Tiger.
This document discusses syntactic editor services including formatting, syntax coloring, and syntactic completion. It describes how syntactic completion can be provided generically based on a syntax definition. The document also discusses how context-free grammars can be extended with templates to specify formatting layout when pretty-printing abstract syntax trees to text. Templates are used to insert whitespace, line breaks, and indentation to produce readable output.
This document summarizes and discusses type checking algorithms for programming languages. It introduces constraint-based type checking, which separates type checking into constraint generation and constraint solving. This provides a more declarative way to specify type checkers. The document discusses using variables and constraints to represent types during type checking. It introduces NaBL2, a domain-specific language for writing constraint generators to specify name and type constraints for programming language static semantics. NaBL2 uses scope graphs to represent name binding structures and supports features like type equality, subtyping, and type-dependent name resolution through constraint rules. An example scope graph and constraint rule for let-bindings is provided.
This document discusses functional programming (FP) and its benefits compared to object-oriented programming (OOP). It defines FP as programming with pure functions that have no side effects. The document explores eliminating side effects through techniques like separating function concerns and returning descriptions of side effects rather than executing them. It also covers FP concepts like higher order functions, recursion, and data types like Option for handling errors/exceptions. The goal is to introduce FP techniques and when each paradigm (FP vs OOP) is best suited.
Declare Your Language: Name ResolutionEelco Visser
Scope graphs are used to represent the binding information in programs. They provide a language-independent representation of name resolution that can be used to conduct and represent the results of name resolution. Separating the representation of resolved programs from the declarative rules that define name binding allows language-independent tooling to be developed for name resolution and other tasks.
The document discusses functional programming and pattern matching. It provides examples of using pattern matching in functional programming to:
1. Match on algebraic data types like lists to traverse and operate on data in a recursive manner. Pattern matching allows adding new operations easily by adding new patterns.
2. Use pattern matching in variable declarations to destructure data like tuples and case class objects.
3. Perform pattern matching on function parameters to selectively apply different logic based on the patterns, like filtering even numbers from a list. Everything can be treated as values and expressions in functional programming.
Compiler Construction | Lecture 9 | Constraint ResolutionEelco Visser
This document provides an overview of constraint resolution in the context of a compiler construction lecture. It discusses unification, which is the basis for many type inference and constraint solving approaches. It also describes separating type checking into constraint generation and constraint solving, and introduces a constraint language that integrates name resolution into constraint resolution through scope graph constraints. Finally, it discusses papers on further developments with this approach, including addressing expressiveness and staging issues in type systems through the Statix DSL for defining type systems.
Compiler Construction | Lecture 8 | Type ConstraintsEelco Visser
This lecture covers type checking with constraints. It introduces the NaBL2 meta-language for writing type specifications as constraint generators that map a program to constraints. The constraints are then solved to determine if a program is well-typed. NaBL2 supports defining name binding and type structures through scope graphs and constraints over names, types, and scopes. Examples show type checking patterns in NaBL2 including variables, functions, records, and name spaces.
Python is an interpreted, general-purpose, high-level programming language. It allows programmers to define functions for reusing code and scoping variables within functions. Key concepts covered include objects, expressions, conditionals, loops, modules, files, and recursion. Functions can call other functions, allowing for modular and reusable code.
This document provides an introduction to programming in the C language. It discusses various data types in C including predefined and user-defined types. It also covers control structures like conditional statements, loops, functions and block statements. Examples are provided to illustrate definitions of structures like records and unions, as well as pointers, arrays and file I/O operations.
This document provides an overview of parsing in compiler construction. It discusses context-free grammars and how they are used to generate sentences and parse trees through derivations. It also covers ambiguity that can arise from grammars and various grammar transformations used to eliminate ambiguity, including defining associativity and priority. The dangling else problem is presented as an example of an ambiguous grammar.
Functions: Function Definition, prototyping, types of functions, passing arguments to functions, Nested Functions, Recursive functions.
Strings: Declaring and Initializing strings, Operations on strings, Arrays of strings, passing strings to functions. Storage Classes: Automatic, External, Static and Register Variables.
Hooking signals and dumping the callstackThierry Gayet
The document provides information on programmatically obtaining backtraces in C using functions from the execinfo.h header file. It describes the backtrace(), backtrace_symbols(), and backtrace_symbols_fd() functions for getting and translating a backtrace. It also gives examples of using these functions to print a backtrace after a crash.
Variables, constants, I/O functions & Header Files document discusses:
1. Variables in C - Variables store data in memory locations and can change value. They are declared with a data type and name.
2. Constants in C - Constants cannot change value once declared. They include integer, floating point, character, and string literals.
3. Input/output functions in C - These allow programs to accept input and display output. Formatted functions like printf() and scanf() control formatting while unformatted functions like getch() and putch() do not.
4. Header files in C - Header files contain predefined library functions and are included using #include to access standard functions.
Compiler Construction | Lecture 4 | Parsing Eelco Visser
This lecture covers parsing and turning syntax definitions into parsers. It discusses context-free grammars and derivations. Grammars can be ambiguous, allowing multiple parse trees for a sentence. Grammar transformations like disambiguation, eliminating left recursion, and left factoring can address issues while preserving the language. Associativity and priority can be defined through transformations. The reading material covers parsing schemata, classical compiler textbooks, and papers on disambiguation filters and parsing algorithms.
● Concept of Structure and Union
● Declaration and Initialization of structure and union
● Nested structures
● Array of Structures
● Passing structure to functions
C is a low-level programming language suitable for systems programming. It is small but powerful, with a large collection of data types and operators. It assumes the programmer knows what they are doing and does not mandate extensive error checking. The document discusses the basics of C including data types, operators, input/output, expressions, selection statements, loops, functions, and pointers. It provides examples of basic C programs and comparisons between C and Java.
This document provides an overview of fundamental concepts in C programming such as keywords, identifiers, data types, constants, variables, and operators. Key points include:
- Keywords are reserved words in C that have special meaning, while identifiers are names given to variables, functions, etc. Identifiers cannot be the same as keywords.
- There are different data types in C like int, char, float, etc. that determine the type of data a variable can hold.
- Constants cannot change value once defined, while the value of variables can change during program execution.
- Operators like unary, binary, and ternary are used to perform operations on operands. Unary operators require a single
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
The document provides an overview of the C programming language. It begins by explaining that Objective-C extends standard ANSI C with object-oriented capabilities. It then discusses why C remains important today due to its use in libraries, operating systems, and as the base for many other popular languages. The document proceeds to cover basic C concepts like variables, data types, functions, flow control, pointers, memory allocation, and I/O parameters. It emphasizes that C provides high performance with a minimal footprint while abstracting away the CPU and memory.
ANTLR v3 is an improved version of ANTLR that provides more robust grammars, error recovery, attributes, tree construction and code generation capabilities compared to version 2. Some key features include single element EBNF grammar syntax, support for parameters and return values in rules, dynamic scoping of attributes, automatic and rewrite-based tree construction, tree grammars, and internationalization through string templates. The runtime is also better organized and separated into modules for parsing, trees, and debugging.
1. Pointers are variables that store memory addresses and can be used to manipulate other variables and arrays. Pointer variables must be declared with a data type and can be initialized using the address-of operator.
2. Arithmetic operations can be performed on pointers to change what they point to, with the amount of change depending on the data type. Pointers can iterate through arrays and strings.
3. Two-dimensional arrays can be viewed as arrays of pointers, allowing strings to be manipulated. Pointers simplify string handling functions like calculating length and checking for palindromes.
The document provides an overview of a C programming course, including:
1) The course will teach programming C elegantly and writing good algorithms, without fancy graphics.
2) Programming is useful for applying math concepts to the real world through simulation.
3) C was chosen as it is small, common, stable, and quick-running, forming the basis for many languages.
4) The document defines some programming terminology and covers basic C programming concepts like variables, functions, and debugging techniques.
Python is a general purpose programming language that can be used for both programming and scripting. It is an interpreted language, meaning code is executed line by line by the Python interpreter. Python code is written in plain text files with a .py extension. Key features of Python include being object-oriented, using indentation for code blocks rather than brackets, and having a large standard library. Python code can be used for tasks like system scripting, web development, data analysis, and more.
The document discusses functional programming and pattern matching. It provides examples of using pattern matching in functional programming to:
1. Match on algebraic data types like lists to traverse and operate on data in a recursive manner. Pattern matching allows adding new operations easily by adding new patterns.
2. Use pattern matching in variable declarations to destructure data like tuples and case class objects.
3. Perform pattern matching on function parameters to selectively apply different logic based on the patterns, like filtering even numbers from a list. Everything can be treated as values and expressions in functional programming.
Compiler Construction | Lecture 9 | Constraint ResolutionEelco Visser
This document provides an overview of constraint resolution in the context of a compiler construction lecture. It discusses unification, which is the basis for many type inference and constraint solving approaches. It also describes separating type checking into constraint generation and constraint solving, and introduces a constraint language that integrates name resolution into constraint resolution through scope graph constraints. Finally, it discusses papers on further developments with this approach, including addressing expressiveness and staging issues in type systems through the Statix DSL for defining type systems.
Compiler Construction | Lecture 8 | Type ConstraintsEelco Visser
This lecture covers type checking with constraints. It introduces the NaBL2 meta-language for writing type specifications as constraint generators that map a program to constraints. The constraints are then solved to determine if a program is well-typed. NaBL2 supports defining name binding and type structures through scope graphs and constraints over names, types, and scopes. Examples show type checking patterns in NaBL2 including variables, functions, records, and name spaces.
Python is an interpreted, general-purpose, high-level programming language. It allows programmers to define functions for reusing code and scoping variables within functions. Key concepts covered include objects, expressions, conditionals, loops, modules, files, and recursion. Functions can call other functions, allowing for modular and reusable code.
This document provides an introduction to programming in the C language. It discusses various data types in C including predefined and user-defined types. It also covers control structures like conditional statements, loops, functions and block statements. Examples are provided to illustrate definitions of structures like records and unions, as well as pointers, arrays and file I/O operations.
This document provides an overview of parsing in compiler construction. It discusses context-free grammars and how they are used to generate sentences and parse trees through derivations. It also covers ambiguity that can arise from grammars and various grammar transformations used to eliminate ambiguity, including defining associativity and priority. The dangling else problem is presented as an example of an ambiguous grammar.
Functions: Function Definition, prototyping, types of functions, passing arguments to functions, Nested Functions, Recursive functions.
Strings: Declaring and Initializing strings, Operations on strings, Arrays of strings, passing strings to functions. Storage Classes: Automatic, External, Static and Register Variables.
Hooking signals and dumping the callstackThierry Gayet
The document provides information on programmatically obtaining backtraces in C using functions from the execinfo.h header file. It describes the backtrace(), backtrace_symbols(), and backtrace_symbols_fd() functions for getting and translating a backtrace. It also gives examples of using these functions to print a backtrace after a crash.
Variables, constants, I/O functions & Header Files document discusses:
1. Variables in C - Variables store data in memory locations and can change value. They are declared with a data type and name.
2. Constants in C - Constants cannot change value once declared. They include integer, floating point, character, and string literals.
3. Input/output functions in C - These allow programs to accept input and display output. Formatted functions like printf() and scanf() control formatting while unformatted functions like getch() and putch() do not.
4. Header files in C - Header files contain predefined library functions and are included using #include to access standard functions.
Compiler Construction | Lecture 4 | Parsing Eelco Visser
This lecture covers parsing and turning syntax definitions into parsers. It discusses context-free grammars and derivations. Grammars can be ambiguous, allowing multiple parse trees for a sentence. Grammar transformations like disambiguation, eliminating left recursion, and left factoring can address issues while preserving the language. Associativity and priority can be defined through transformations. The reading material covers parsing schemata, classical compiler textbooks, and papers on disambiguation filters and parsing algorithms.
● Concept of Structure and Union
● Declaration and Initialization of structure and union
● Nested structures
● Array of Structures
● Passing structure to functions
C is a low-level programming language suitable for systems programming. It is small but powerful, with a large collection of data types and operators. It assumes the programmer knows what they are doing and does not mandate extensive error checking. The document discusses the basics of C including data types, operators, input/output, expressions, selection statements, loops, functions, and pointers. It provides examples of basic C programs and comparisons between C and Java.
This document provides an overview of fundamental concepts in C programming such as keywords, identifiers, data types, constants, variables, and operators. Key points include:
- Keywords are reserved words in C that have special meaning, while identifiers are names given to variables, functions, etc. Identifiers cannot be the same as keywords.
- There are different data types in C like int, char, float, etc. that determine the type of data a variable can hold.
- Constants cannot change value once defined, while the value of variables can change during program execution.
- Operators like unary, binary, and ternary are used to perform operations on operands. Unary operators require a single
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
The document provides an overview of the C programming language. It begins by explaining that Objective-C extends standard ANSI C with object-oriented capabilities. It then discusses why C remains important today due to its use in libraries, operating systems, and as the base for many other popular languages. The document proceeds to cover basic C concepts like variables, data types, functions, flow control, pointers, memory allocation, and I/O parameters. It emphasizes that C provides high performance with a minimal footprint while abstracting away the CPU and memory.
ANTLR v3 is an improved version of ANTLR that provides more robust grammars, error recovery, attributes, tree construction and code generation capabilities compared to version 2. Some key features include single element EBNF grammar syntax, support for parameters and return values in rules, dynamic scoping of attributes, automatic and rewrite-based tree construction, tree grammars, and internationalization through string templates. The runtime is also better organized and separated into modules for parsing, trees, and debugging.
1. Pointers are variables that store memory addresses and can be used to manipulate other variables and arrays. Pointer variables must be declared with a data type and can be initialized using the address-of operator.
2. Arithmetic operations can be performed on pointers to change what they point to, with the amount of change depending on the data type. Pointers can iterate through arrays and strings.
3. Two-dimensional arrays can be viewed as arrays of pointers, allowing strings to be manipulated. Pointers simplify string handling functions like calculating length and checking for palindromes.
The document provides an overview of a C programming course, including:
1) The course will teach programming C elegantly and writing good algorithms, without fancy graphics.
2) Programming is useful for applying math concepts to the real world through simulation.
3) C was chosen as it is small, common, stable, and quick-running, forming the basis for many languages.
4) The document defines some programming terminology and covers basic C programming concepts like variables, functions, and debugging techniques.
Python is a general purpose programming language that can be used for both programming and scripting. It is an interpreted language, meaning code is executed line by line by the Python interpreter. Python code is written in plain text files with a .py extension. Key features of Python include being object-oriented, using indentation for code blocks rather than brackets, and having a large standard library. Python code can be used for tasks like system scripting, web development, data analysis, and more.
This document provides a quick introduction to the C programming language. It discusses basic C syntax like main functions, header files, comments, and variables. It also covers data types, memory, functions, scopes, expressions, control flow statements like if/else and loops. Functions can access arguments and global variables from their own scope but not variables from outer scopes unless passing their addresses.
The document provides a quick introduction to C programming, covering topics like functions, variables, memory, expressions, and recursion. It uses a recursive pow() function to demonstrate recursion and the call stack. Each function call gets its own copy of arguments and local variables, stored on the call stack.
The document provides a quick introduction to C programming. It discusses some key concepts in C including functions, variables, memory, data types, expressions and evaluation, and recursion. It provides an example of a recursive pow() function to calculate powers and discusses how function calls are handled through the stack.
PHP is a server-side scripting language that can be embedded into web pages. It uses HTML-like syntax for embedding code tags and has variables, operators, and control structures similar to C. PHP code is processed on the server and outputs dynamic content to the browser. It supports common data types like strings, integers, floats, arrays, and objects. Variables do not need to be declared, have dynamic types, and can be manipulated using operators. PHP provides control structures like if/else statements and loops to control program flow. Data can be included and required from other files.
The document provides an overview of the history and basics of C++ programming. It discusses:
- Bjarne Stroustrup created C++ in the early 1980s as an extension of C to support object-oriented programming.
- A typical C++ environment includes a program development environment, the C++ language itself, and the C++ Standard Library.
- A C++ program goes through several phases: edit, preprocess, compile, link, load, and execute.
- Basic C++ concepts covered include variables, data types, operators, and common errors.
The document discusses the evolution of programming languages from machine language to high-level languages like C++ and Java. It provides an example of a simple "Hello World" program in C++ and explains what each part of the code is doing. It also discusses some basic concepts in programming like data types, variables, operators, and control flow statements.
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Python
Language
is uesd in engineeringStory adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they s
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.
This document provides an introduction to the C programming language. It discusses key concepts like functions, variables, data types, memory, scopes, expressions, operators, control flow with if/else statements and loops. It also explains how passing arguments by value means functions cannot directly modify their parameters, but passing addresses allows modifying variables in the calling scope. Overall it serves as a helpful primer on basic C syntax and programming concepts for newcomers to the language.
This document discusses various concepts related to C programming including data types, operators, decision making statements, and loops. It begins with an example "Hello World" C program and explains each part. It then covers various data types in C like integer, float, char, etc. along with their sizes and ranges. Different types of operators like arithmetic, logical, assignment, increment/decrement are described. Decision making statements like if, if-else, if-else ladder, nested if, switch case are explained with examples. Finally, it briefly introduces the three types of loops in C - while, do-while, and for loops.
This document discusses using Python for scientific computing. It begins by listing popular programming languages for scientific purposes, including Fortran, MATLAB, Scilab, GNU Octave, Mathematica, and Python. While MATLAB is currently the most popular, it is proprietary software. Python is introduced as a free and open source alternative with many scientific libraries like NumPy, SciPy, scikit-learn, and Matplotlib. These libraries allow Python to perform similarly to MATLAB. Instructions are provided for installing the necessary Python packages on Linux, Unix, and Windows systems. Examples demonstrate basic Python syntax and how to perform tasks like importing data, visualization, and machine learning classification.
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.
Program 1 – CS 344This assignment asks you to write a bash.docxwkyra78
Program 1 – CS 344
This assignment asks you to write a bash shell script to compute statistics. The purpose
is to get you familiar with the Unix shell, shell programming, Unix utilities, standard
input, output, and error, pipelines, process ids, exit values, and signals.
What you’re going to submit is your script, called stats.
Overview
NOTE: For this assignment, make sure that you are using Bash as your shell (on Linux,
/bin/sh is Bash, but on other Unix O/S, it is not). This is because the Solaris version of
Bourne shell has some annoying bugs that are really brought out by this script. Bash can
execute any /bin/sh script.
In this assignment you will write a Bourne shell script to calculate averages and medians
from an input file of numbers. This is the sort of calculation I might do when figuring
out the grades for this course. The input file will have whole number values separated by
tabs, and each line of this file will have the same number of values. (For example, each
row might be the scores of a student on assignments.) Your script should be able to
calculate the average and median across the rows (like I might do to calculate an
individual student's course grade) or down the columns (like I might do to find the
average score on an assignment).
You will probably need commands like these, so please read up on them: sh, read, expr,
cut, head, tail, wc, and sort.
Your script will be called stats. The general format of the stats command is
stats {-rows|-cols} [input_file]
Note that when things are in curly braces separated by a vertical bar, it means you should
choose one of the things; here for example, you must choose either -rows or -cols. The
option -rows calculates the average and median across the rows; the option -cols
calculates the average and median down the columns. When things are in square braces
it means they are optional; you can include them or not, as you choose. If you specify an
input_file the data is read from that file; otherwise, it is read from standard input.
Here is a sample run of what your script might return, using an input file called test_file
(this particular one can be downloaded here , note that in Windows, the newline
characters may not display as newlines. Move this to your UNIX account, without
opening and saving it in Windows, and then cat it out: you'll see the newlines there):
% cat test_file
1 1 1 1 1
9 3 4 5 5
6 7 8 9 7
3 6 8 9 1
3 4 2 1 4
6 4 4 7 7
% stats -rows test_file
Average Median
1 1
5 5
7 7
5 6
3 3
6 6
% cat test_file | stats –c
Averages:
5 4 5 5 4
Medians:
6 4 4 7 5
% echo $?
0
% stats
Usage: stats {-rows|-cols} [file]
% stats -r test_file nya-nya-nya
Usage: stats {-rows|-cols} [file]
% stats -both test_file
Usage: stats {-rows|-cols} [file]
% chmod -r test_file
% stats -columns test_file
stats: cannot read test_file
% stats -columns no_such_file
stats: cannot read no_such_file
% echo $?
1
Specifications
You must ch ...
An Overview Of Python With Functional ProgrammingAdam Getchell
This document provides an overview of the Python programming language and its capabilities for functional programming. It describes Python's attributes such as being portable, object-oriented, and supporting procedural, object-oriented, and functional programming. It also lists several popular Python modules that provide additional functionality and examples of code written in both a procedural and object-oriented style in Python. Finally, it provides examples of functional programming concepts like map, filter and reduce implemented in Python along with references for further information.
The document provides examples of programming exercises of increasing complexity that require mastery of specific programming concepts. It includes exercises to practice variables, input/output, conditional statements, loops, arrays, functions, strings, object-oriented programming concepts like classes and inheritance, file input/output, pointers, sorting, linked lists, and recursion. Many exercises ask the programmer to modify an initial program by adding additional requirements or complexity. The last exercise provided asks the programmer to create a linked list of bunny objects with various attributes and behaviors to simulate bunny aging, breeding, and the introduction of radioactive mutant vampire bunnies.
The C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system.
The C is the most widely used computer language, it keeps fluctuating at number one scale of popularity along with Java programming language, which is also equally popular and most widely used among modern software programmers.
Shift-reduce parsing is a bottom-up parsing technique that uses two steps: the shift step pushes the next input symbol onto the stack, and the reduce step replaces grammar rule right-hand sides on the stack with their left-hand non-terminals. The LR parser is a widely used, efficient bottom-up parsing algorithm that uses shift-reduce actions and looks ahead k symbols to make parsing decisions. There are three main LR parsing algorithms: SLR(1) works on the smallest grammars but has few states; LR(1) works on all LR(1) grammars but has more states; and LALR(1) works on an intermediate size of grammars with the same number of states as S
This document discusses different types of spread spectrum techniques used in wireless communications. It begins by explaining spread spectrum and its advantages such as security, resistance to jamming and interference, and allowing multiple signals to coexist. It then describes three spread spectrum methods: frequency hopping spread spectrum (FHSS), direct sequence spread spectrum (DSSS), and time hopping spread spectrum (THSS). FHSS and DSSS are discussed in further detail, including how they work, their uses, advantages, and disadvantages. The document also briefly covers infrared wireless networks and orthogonal frequency-division multiplexing (OFDM).
This document provides an overview of infrared radiation and wireless protocols. It begins with definitions of infrared radiation, its history and characteristics. It then discusses infrared technology used in mobiles for wireless connectivity. The document outlines different infrared data transmission techniques and classification schemes. It also covers wireless networks and common network protocols like TCP, IP, HTTP and their standards. The key points covered are the use of infrared for mobile communication, protocols for network communication and wireless network standards.
This document provides information about Orthogonal Frequency Division Multiplexing (OFDM) including:
- OFDM was first proposed in 1966 and has developed over the years as a popular scheme for wideband digital communication.
- OFDM works by dividing the available spectrum into multiple orthogonal subcarriers that are modulated with low-rate data streams, maintaining total data rates similar to conventional single-carrier modulation schemes.
- OFDM has advantages over other modulation techniques in that it can easily adapt to severe channel conditions and is robust against interference and fading.
Frequency hopping spread spectrum (FHSS) is a method of wireless communication where the frequency of the transmitted signal is rapidly switched, or hopped, among many distinct frequencies within a wide band of frequencies. This hopping occurs according to a pseudorandom sequence that is known to both the transmitter and receiver. By hopping between many frequencies, FHSS improves interference rejection, provides security against eavesdropping, and allows multiple transmitters to operate in the same space without interference. Some advantages of FHSS include improved interference rejection, secure communication, increased capacity and spectral efficiency, and lower implementation costs. FHSS is commonly used in military communications systems and satellite communications.
Wireless networks use radio waves to connect devices without cables. They integrate with wired networks through access points and allow mobility as users move between coverage areas. The 802.11 standards define the physical and data link layers for wireless LANs and include specifications like 802.11a, b, g which provide different speeds and frequencies. Security is important for wireless networks and features like WEP have known vulnerabilities. Careful planning of access point placement and antennas is needed for effective coverage.
This document summarizes the evolution of wireless technologies from 1G to 5G. It discusses the key features and limitations of each generation including 1G, 2G, 2.5G, 3G, 4G, and the emerging 5G technology. The document compares the data speeds and capabilities of 3G and 4G networks. It also outlines some of the countries that have implemented 4G networks and discusses potential applications and services of wireless technologies.
Direct sequence spread spectrum is a technique that spreads signals across a wider bandwidth through the use of pseudorandom number sequences. This decreases interference and allows multiple access and functions. In direct sequence spread spectrum, each bit is represented by multiple bits using a spreading code, spreading the signal across a wider frequency band proportional to the number of bits. It is used in applications like GPS, wireless networks, and communications to increase resistance to interference and jamming while allowing sharing of channels.
This document contains a multiple choice quiz on topics related to mobile and wireless communication systems. It covers various modulation techniques, technologies and standards used over time for mobile communication including frequency modulation, DECT, GSM, 2G, 3G. Concepts discussed include cellular network components, frequency reuse, channel assignment strategies, handoff processes, interference management techniques, and trunking.
This document outlines topics related to mobile and wireless networks for a final term project, including random access techniques, GSM network architecture, mobile ad-hoc networks, multiplexing techniques, wireless local area networks, infrared and radio frequency comparison, GSM cell structure, handoff types, comparisons of 2G, 3G, 4G networks, the roaming process, short notes on wireless standards and technologies, operating system comparisons, CDMA and GSM comparisons, and details about the ZigBee wireless protocol. The project will involve reviewing chapters 1-3 of the provided textbook on mobile communication.
This document is a preface and table of contents for a set of lecture notes on mobile communication. The author has been teaching a course on mobile communication for many years at IIT Guwahati in India. The lecture notes are intended to supplement that course and provide students access to the material anytime. The notes cover introductory concepts in mobile communication as well as the evolution of mobile systems, cellular engineering fundamentals, radio wave propagation, multipath fading, and multiple access techniques. The author acknowledges the help received from students and colleagues in developing the lecture notes.
The document discusses the topics covered in modules about Global System for Mobile Communications (GSM). It provides an overview of GSM architecture and components like the mobile station, base station subsystem, network switching subsystem and their interfaces. It describes the different generations of cellular networks and GSM channels. It also covers concepts like cell planning, hardware for different network nodes, call paths for various call types, data services, mobile packet backbone network and the evolution of GSM.
This document summarizes the evolution of mobile communications technology from 1G to 4G networks. It describes the basic structure of mobile networks and then details the major standards and generations including: AMPS, GSM, CDMA, UMTS, HSPA, LTE, and LTE-Advanced. It provides information on key aspects of each such as supported data rates, deployment dates, and technological enhancements compared to previous standards.
Flow and error control are important functions of the data link layer. Flow control coordinates the amount of data sent before receiving acknowledgement to prevent buffers from overflowing. Error control detects and corrects damaged frames using automatic repeat request (ARQ) protocols. Three common ARQ protocols are described: stop-and-wait, go-back-N, and selective repeat. Stop-and-wait sends one frame at a time while the others use sliding windows to allow multiple outstanding frames. Go-back-N resends frames from the last acknowledged in order, while selective repeat resends only damaged frames.
This document provides an overview and summary of Chapter 10 from the textbook "Principles of Managerial Finance" by Lawrence J. Gitman. Chapter 10 expands on capital budgeting techniques by considering risk factors such as sensitivity analysis, scenario analysis, and simulation. It also examines evaluating international projects and risk adjustment methods like certainty equivalents and risk-adjusted discount rates. The document provides learning resources for students on these topics, including a problem solver, study guide examples, and answers to chapter review questions to help students understand the concepts covered in the chapter.
This document provides an overview and instructor resources for a chapter on capital budgeting techniques from the textbook "Principles of Managerial Finance" by Lawrence J. Gitman. The chapter covers net present value, internal rate of return, payback period, and risk-adjusted discount rates. It includes sample problems, spreadsheet templates, and a study guide for classroom use. The document lists learning goals, solutions to review questions, and solutions to sample problems calculating various capital budgeting metrics for multiple projects.
This document summarizes key concepts from Chapter 5 of the textbook "Principles of Managerial Finance" by Lawrence J. Gitman. The chapter focuses on risk and return fundamentals including measuring risk of single and multiple assets, the benefits of diversification, and the Capital Asset Pricing Model (CAPM). It provides an overview of the chapter topics, study guide examples, answers to review questions, and solutions to problems to help instructors teach the concepts.
The document discusses key concepts related to classes and objects in object-oriented programming. It defines class, object, class variables, object variables, class methods, and object methods. It explains that a class is a blueprint or template for creating objects, and that every object is built from a class. It also provides examples of how to write a class in different programming languages like ActionScript 3 and Visual Basic. The document then discusses other important OOP concepts like inheritance, polymorphism, exception handling, and common programming structures like arrays, foreach loops, and GUI components.
This document discusses email security concepts and PGP. It defines email security as securing email accounts and content. Techniques mentioned include strong passwords, spam filters, and encryption. Threats to email security are loss of confidentiality, integrity, and authentication. The document also discusses specific email security threats like snowshoe spamming, hacktivism, and data breaches. It defines concepts related to PGP like public/private key encryption and how PGP can be used to encrypt emails and files.
This document discusses top-down design and functions in C programming. It explains that programmers often build on existing functions to reuse code and meet deadlines. Some key points:
- Top-down design breaks problems into subproblems that are solved with functions. Structure charts show the relationships between subproblems.
- C provides standard library functions through header files that can be reused. Programmers can also define their own functions.
- Functions are declared with prototypes specifying their return type and arguments. Control passes between the main function and subprograms when functions are called.
- The document provides examples of functions without arguments, and functions that take input arguments or return values. Homework involves creating functions to convert between Celsius
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...NelTorrente
In this research, it concludes that while the readiness of teachers in Caloocan City to implement the MATATAG Curriculum is generally positive, targeted efforts in professional development, resource distribution, support networks, and comprehensive preparation can address the existing gaps and ensure successful curriculum implementation.
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Dr. Vinod Kumar Kanvaria
Exploiting Artificial Intelligence for Empowering Researchers and Faculty,
International FDP on Fundamentals of Research in Social Sciences
at Integral University, Lucknow, 06.06.2024
By Dr. Vinod Kumar Kanvaria
How to Build a Module in Odoo 17 Using the Scaffold MethodCeline George
Odoo provides an option for creating a module by using a single line command. By using this command the user can make a whole structure of a module. It is very easy for a beginner to make a module. There is no need to make each file manually. This slide will show how to create a module using the scaffold method.
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
বাংলাদেশের অর্থনৈতিক সমীক্ষা ২০২৪ [Bangladesh Economic Review 2024 Bangla.pdf] কম্পিউটার , ট্যাব ও স্মার্ট ফোন ভার্সন সহ সম্পূর্ণ বাংলা ই-বুক বা pdf বই " সুচিপত্র ...বুকমার্ক মেনু 🔖 ও হাইপার লিংক মেনু 📝👆 যুক্ত ..
আমাদের সবার জন্য খুব খুব গুরুত্বপূর্ণ একটি বই ..বিসিএস, ব্যাংক, ইউনিভার্সিটি ভর্তি ও যে কোন প্রতিযোগিতা মূলক পরীক্ষার জন্য এর খুব ইম্পরট্যান্ট একটি বিষয় ...তাছাড়া বাংলাদেশের সাম্প্রতিক যে কোন ডাটা বা তথ্য এই বইতে পাবেন ...
তাই একজন নাগরিক হিসাবে এই তথ্য গুলো আপনার জানা প্রয়োজন ...।
বিসিএস ও ব্যাংক এর লিখিত পরীক্ষা ...+এছাড়া মাধ্যমিক ও উচ্চমাধ্যমিকের স্টুডেন্টদের জন্য অনেক কাজে আসবে ...
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
How to Fix the Import Error in the Odoo 17Celine George
An import error occurs when a program fails to import a module or library, disrupting its execution. In languages like Python, this issue arises when the specified module cannot be found or accessed, hindering the program's functionality. Resolving import errors is crucial for maintaining smooth software operation and uninterrupted development processes.
2. 22
AbstractAbstract
Today, I’ll present the basics of computation. InToday, I’ll present the basics of computation. In
particular, we’ll discuss expressions, how toparticular, we’ll discuss expressions, how to
iterate over a series of values (“iteration”), anditerate over a series of values (“iteration”), and
select between two alternative actionsselect between two alternative actions
(“selection”). I’ll also show how a particular sub-(“selection”). I’ll also show how a particular sub-
computation can be named and specifiedcomputation can be named and specified
separately as a function. To be able to performseparately as a function. To be able to perform
more realistic computations, I will introduce themore realistic computations, I will introduce the
vectorvector type to hold sequences of values.type to hold sequences of values.
Selection, Iteration, Function, VectorSelection, Iteration, Function, Vector
Stroustrup/Programming/2015Stroustrup/Programming/2015
3. 33
OverviewOverview
ComputationComputation
What is computable? How best to compute it?What is computable? How best to compute it?
Abstractions, algorithms, heuristics, data structuresAbstractions, algorithms, heuristics, data structures
Language constructs and ideasLanguage constructs and ideas
Sequential order of executionSequential order of execution
Expressions and StatementsExpressions and Statements
SelectionSelection
IterationIteration
FunctionsFunctions
VectorsVectors
Stroustrup/Programming/2015Stroustrup/Programming/2015
4. 44
You already know most of thisYou already know most of this
Note:Note:
You know how to do arithmeticYou know how to do arithmetic
d = a+b*cd = a+b*c
You know how to selectYou know how to select
““if this is true, do that; otherwise do something else ”if this is true, do that; otherwise do something else ”
You know how to “iterate”You know how to “iterate”
““do this until you are finished”do this until you are finished”
““do that 100 times”do that 100 times”
You know how to do functionsYou know how to do functions
““go ask Joe and bring back the answer”go ask Joe and bring back the answer”
““hey Joe, calculate this for me and send me the answer”hey Joe, calculate this for me and send me the answer”
What I will show you today is mostly just vocabulary andWhat I will show you today is mostly just vocabulary and
syntax for what you already knowsyntax for what you already know
Stroustrup/Programming/2015Stroustrup/Programming/2015
5. 55
ComputationComputation
Input: from keyboard, files, other input devices, other programs, otherInput: from keyboard, files, other input devices, other programs, other
parts of a programparts of a program
Computation – what our program will do with the input to produce theComputation – what our program will do with the input to produce the
output.output.
Output: to screen, files, other output devices, other programs, other partsOutput: to screen, files, other output devices, other programs, other parts
of a programof a program
(input) data (output) data
data
Code, often messy,
often a lot of code
Stroustrup/Programming/2015Stroustrup/Programming/2015
6. 66
ComputationComputation
Our job is to express computationsOur job is to express computations
CorrectlyCorrectly
SimplySimply
EfficientlyEfficiently
One tool is called Divide and ConquerOne tool is called Divide and Conquer
to break up big computations into many little onesto break up big computations into many little ones
Another tool is AbstractionAnother tool is Abstraction
Provide a higher-level concept that hides detailProvide a higher-level concept that hides detail
Organization of data is often the key to good codeOrganization of data is often the key to good code
Input/output formatsInput/output formats
ProtocolsProtocols
Data structuresData structures
Note the emphasis on structure and organizationNote the emphasis on structure and organization
You don’t get good code just by writing a lot of statementsYou don’t get good code just by writing a lot of statements
Stroustrup/Programming/2015Stroustrup/Programming/2015
7. 77
Language featuresLanguage features
Each programming language feature exists to expressEach programming language feature exists to express
a fundamental ideaa fundamental idea
For exampleFor example
++ : addition: addition
** : multiplication: multiplication
if (if (expressionexpression)) statementstatement elseelse statement ;statement ; selectionselection
while (while (expressionexpression)) statementstatement ;; iterationiteration
f(x);f(x); function/operationfunction/operation
……
We combine language features to create programsWe combine language features to create programs
Stroustrup/Programming/2015Stroustrup/Programming/2015
8. 88
ExpressionsExpressions
//// compute area:compute area:
int length = 20;int length = 20; //// the simplest expression: a literal (here, 20)the simplest expression: a literal (here, 20)
//// (here used to initialize a variable)(here used to initialize a variable)
int width = 40;int width = 40;
int area = length*width;int area = length*width; //// a multiplicationa multiplication
int average = (length+width)/2;int average = (length+width)/2; //// addition and divisionaddition and division
The usual rules of precedence apply:The usual rules of precedence apply:
a*b+c/da*b+c/d meansmeans (a*b)+(c/d)(a*b)+(c/d) and notand not a*(b+c)/da*(b+c)/d..
If in doubt, parenthesize. If complicated, parenthesize.If in doubt, parenthesize. If complicated, parenthesize.
Don’t write “absurdly complicated” expressions:Don’t write “absurdly complicated” expressions:
a*b+c/d*(e-f/g)/h+7a*b+c/d*(e-f/g)/h+7 //// too complicatedtoo complicated
Choose meaningful names.Choose meaningful names.
Stroustrup/Programming/2015Stroustrup/Programming/2015
9. 99
ExpressionsExpressions
Expressions are made out of operators and operandsExpressions are made out of operators and operands
Operators specify what is to be doneOperators specify what is to be done
Operands specify the data for the operators to work withOperands specify the data for the operators to work with
Boolean type:Boolean type: boolbool ((truetrue andand falsefalse))
Equality operators:Equality operators: = == = (equal),(equal), !=!= (not equal)(not equal)
Logical operators:Logical operators: &&&& (and),(and), |||| (or),(or), !! (not)(not)
Relational operators:Relational operators: << (less than),(less than), >> (greater than),(greater than), <=<=,, >=>=
Character type:Character type: charchar (e.g.,(e.g., 'a''a',, '7''7', and, and '@''@'))
Integer types:Integer types: short, int, longshort, int, long
arithmetic operators:arithmetic operators: +, -, *, /, %+, -, *, /, % (remainder)(remainder)
Floating-point types: e.g.,Floating-point types: e.g., float, doublefloat, double (e.g.,(e.g., 12.4512.45 andand 1.234e31.234e3))
arithmetic operators:arithmetic operators: +, -, *, /+, -, *, /
Stroustrup/Programming/2015Stroustrup/Programming/2015
10. 1010
Concise OperatorsConcise Operators
For many binary operators, there are (roughly) equivalentFor many binary operators, there are (roughly) equivalent
more concise operatorsmore concise operators
For exampleFor example
a += ca += c meansmeans a = a+ca = a+c
a *= scalea *= scale meansmeans a = a*scalea = a*scale
++a++a meansmeans a += 1a += 1
oror a = a+1a = a+1
““Concise operators” are generally better to useConcise operators” are generally better to use
(clearer, express an idea more directly)(clearer, express an idea more directly)
Stroustrup/Programming/2015Stroustrup/Programming/2015
11. 1111
StatementsStatements
A statement isA statement is
an expression followed by a semicolon, oran expression followed by a semicolon, or
a declaration, ora declaration, or
a “control statement” that determines the flow of controla “control statement” that determines the flow of control
For exampleFor example
a = b;a = b;
double d2 = 2.5;double d2 = 2.5;
if (x == 2) y = 4;if (x == 2) y = 4;
while (cin >> number) numbers.push_back(number);while (cin >> number) numbers.push_back(number);
int average = (length+width)/2;int average = (length+width)/2;
return x;return x;
You may not understand all of these just now, but you will …You may not understand all of these just now, but you will …
Stroustrup/Programming/2015Stroustrup/Programming/2015
12. 1212
SelectionSelection
Sometimes we must select between alternativesSometimes we must select between alternatives
For example, suppose we want to identify the larger of twoFor example, suppose we want to identify the larger of two
values. We can do this with anvalues. We can do this with an ifif statementstatement
if (a<b)if (a<b) //// Note: No semicolon hereNote: No semicolon here
max = b;max = b;
elseelse //// Note: No semicolon hereNote: No semicolon here
max = a;max = a;
The syntax isThe syntax is
if (condition)if (condition)
statement-1statement-1 //// if the condition is true, do statement-1if the condition is true, do statement-1
elseelse
statement-2statement-2 //// if not, do statement-2if not, do statement-2
Stroustrup/Programming/2015Stroustrup/Programming/2015
13. 1313
Iteration (while loop)Iteration (while loop)
The world’s first “real program” running on a stored-programThe world’s first “real program” running on a stored-program
computer (David Wheeler, Cambridge, May 6, 1949)computer (David Wheeler, Cambridge, May 6, 1949)
//// calculate and print a table of squares 0-99:calculate and print a table of squares 0-99:
int main()int main()
{{
int i = 0;int i = 0;
while (i<100) {while (i<100) {
cout << i <<cout << i << ''tt'' << square(i) <<<< square(i) << ''nn'';;
++i ;++i ; //// incrementincrement ii
}}
}}
//// (No, it wasn’t actually written in C++(No, it wasn’t actually written in C++ .).)
Stroustrup/Programming/2015Stroustrup/Programming/2015
14. 1414
Iteration (while loop)Iteration (while loop)
What it takesWhat it takes
A loop variable (control variable);A loop variable (control variable); here:here: ii
Initialize the control variable;Initialize the control variable; here:here: int i = 0int i = 0
AA termination criterion;termination criterion; here: ifhere: if i<100i<100 is false, terminateis false, terminate
Increment the control variable;Increment the control variable; here:here: ++i++i
Something to do for each iteration;Something to do for each iteration; here:here: cout << …cout << …
int i = 0;int i = 0;
while (i<100) {while (i<100) {
cout << i <<cout << i << ''tt'' << square(i) <<<< square(i) << ''nn'';;
++i ;++i ; //// incrementincrement ii
}}
Stroustrup/Programming/2015Stroustrup/Programming/2015
15. 1515
Iteration (for loop)Iteration (for loop)
Another iteration form: theAnother iteration form: the forfor looploop
You can collect all the control information in oneYou can collect all the control information in one
place, at the top, where it’s easy to seeplace, at the top, where it’s easy to see
for (int i = 0; i<100; ++i) {for (int i = 0; i<100; ++i) {
cout << i <<cout << i << ''tt'' << square(i) <<<< square(i) << ''nn'';;
}}
That is,That is,
for (for (initializeinitialize;; conditioncondition ;; incrementincrement ))
controlled statementcontrolled statement
Note: what isNote: what is square(i)square(i)??
Stroustrup/Programming/2015Stroustrup/Programming/2015
16. 1616
FunctionsFunctions
But what wasBut what was square(i)?square(i)?
A call of the functionA call of the function square()square()
int square(int x)int square(int x)
{{
return x*x;return x*x;
}}
We define a function when we want to separate aWe define a function when we want to separate a
computation because itcomputation because it
is logically separateis logically separate
makes the program text clearer (by naming the computation)makes the program text clearer (by naming the computation)
is useful in more than one place in our programis useful in more than one place in our program
eases testing, distribution of labor, and maintenanceeases testing, distribution of labor, and maintenance
Stroustrup/Programming/2015Stroustrup/Programming/2015
17. 1717
Control FlowControl Flow
int main()int main()
{{
i=0;i=0;
while (i<100)while (i<100)
{{
square(i);square(i);
}}
}}
int square(int x)int square(int x)
{{
//// compute square rootcompute square root
return x * x;return x * x;
}}i<100
i==100
Stroustrup/Programming/2015Stroustrup/Programming/2015
18. 1818
FunctionsFunctions
Our functionOur function
int square(int x)int square(int x)
{{
return x*x;return x*x;
}}
is an example ofis an example of
Return_type function_nameReturn_type function_name (( Parameter listParameter list ))
//// (type name, etc.)(type name, etc.)
{{
//// use each parameter in codeuse each parameter in code
returnreturn some_valuesome_value;; //// ofof Return_typeReturn_type
}}
Stroustrup/Programming/2015Stroustrup/Programming/2015
19. 1919
Another ExampleAnother Example
Earlier we looked at code to find the larger of two values.Earlier we looked at code to find the larger of two values.
Here is a function that compares the two values and returnsHere is a function that compares the two values and returns
the larger value.the larger value.
int max(int a, int b)int max(int a, int b) //// this function takes 2 parametersthis function takes 2 parameters
{{
if (a<b)if (a<b)
return b;return b;
elseelse
return a;return a;
}}
int x = max(7, 9);int x = max(7, 9); //// x becomes 9x becomes 9
int y = max(19, -27);int y = max(19, -27); //// y becomes 19y becomes 19
int z = max(20, 20);int z = max(20, 20); //// z becomes 20z becomes 20
Stroustrup/Programming/2015Stroustrup/Programming/2015
20. 2020
Data for Iteration - VectorData for Iteration - Vector
To do just about anything of interest, we need a collection ofTo do just about anything of interest, we need a collection of
data to work on. We can store this data in adata to work on. We can store this data in a vectorvector. For example:. For example:
//// read some temperatures into a vector:read some temperatures into a vector:
int main()int main()
{{
vector<double> temps;vector<double> temps; //// declare a vector of type double to storedeclare a vector of type double to store
//// temperatures – like 62.4temperatures – like 62.4
double temp;double temp; //// a variable for a single temperature valuea variable for a single temperature value
while (cin>>temp)while (cin>>temp) //// cin reads a value and stores it in tempcin reads a value and stores it in temp
temps.push_back(temp);temps.push_back(temp); //// store the value of temp in the vectorstore the value of temp in the vector
//// … do something …… do something …
}}
//// cin>>tempcin>>temp will return true until we reach the end of file or encounterwill return true until we reach the end of file or encounter
//// something that isn’t a double: like the word “end”something that isn’t a double: like the word “end”
Stroustrup/Programming/2015Stroustrup/Programming/2015
21. 2121
VectorVector
Vector is the most useful standard library data typeVector is the most useful standard library data type
aa vector<T>vector<T> holds an sequence of values of typeholds an sequence of values of type TT
Think of a vector this wayThink of a vector this way
A vector namedA vector named vv contains 5 elements: {1, 4, 2, 3, 5}:contains 5 elements: {1, 4, 2, 3, 5}:
1 4 2 3 5
5v:
v’s elements:
v[0] v[1] v[2] v[3] v[4]
size()
Stroustrup/Programming/2015Stroustrup/Programming/2015
22. 2222
VectorsVectors
vector<int> v;vector<int> v; //// start off emptystart off empty
v.push_back(1);v.push_back(1); //// add an element with the valueadd an element with the value 11
v.push_back(4);v.push_back(4); //// add an element with the valueadd an element with the value 44 at end (“the back”)at end (“the back”)
v.push_back(3);v.push_back(3); //// add an element with the valueadd an element with the value 33 at end (“the back”)at end (“the back”)
v[0]v[0] v[1] v[2]v[1] v[2]
0v:
3
2
1 1
41
341
v:
v:
v:
Stroustrup/Programming/2015Stroustrup/Programming/2015
23. 2323
VectorsVectors
Once you get your data into a vector you can easily manipulate itOnce you get your data into a vector you can easily manipulate it
//// compute mean (average) and median temperatures:compute mean (average) and median temperatures:
int main()int main()
{{
vector<double> temps;vector<double> temps; //// temperatures in Fahrenheit, e.g. 64.6temperatures in Fahrenheit, e.g. 64.6
double temp;double temp;
while (cin>>temp) temps.push_back(temp); //while (cin>>temp) temps.push_back(temp); // read and put into vectorread and put into vector
double sum = 0;double sum = 0;
for (int i = 0; i< temps.size(); ++i) sum += temps[i]; //for (int i = 0; i< temps.size(); ++i) sum += temps[i]; // sums temperaturessums temperatures
cout << "Mean temperature: " << sum/temps.size() << 'n';cout << "Mean temperature: " << sum/temps.size() << 'n';
sort(temps);sort(temps); //// from std_lib_facilities.hfrom std_lib_facilities.h
//// or sort(temps.begin(), temps.end();or sort(temps.begin(), temps.end();
cout << "Median temperature: " << temps[temps.size()/2] << 'n';cout << "Median temperature: " << temps[temps.size()/2] << 'n';
}}
Stroustrup/Programming/2015Stroustrup/Programming/2015
24. 2424
Traversing a vectorTraversing a vector
Once you get your data into a vector you can easily manipulate itOnce you get your data into a vector you can easily manipulate it
Initialize with a listInitialize with a list
vector<int> v = { 1, 2, 3, 5, 8, 13 }; //vector<int> v = { 1, 2, 3, 5, 8, 13 }; // initialize with a listinitialize with a list
often we want to look at each element of a vector in turn:often we want to look at each element of a vector in turn:
for (int i = 0; i< v.size(); ++i) cout << v[i] << 'n'; //for (int i = 0; i< v.size(); ++i) cout << v[i] << 'n'; // list all elementslist all elements
//// there is a simpler kind of loop for that (a range-for loop):there is a simpler kind of loop for that (a range-for loop):
for (int i : v) cout << x << 'n'; //for (int i : v) cout << x << 'n'; // list all elementslist all elements
//// for each x in v …for each x in v …
Stroustrup/Programming/2015Stroustrup/Programming/2015
25. 2525
Combining Language FeaturesCombining Language Features
You can write many new programs by combiningYou can write many new programs by combining
language features, built-in types, and user-definedlanguage features, built-in types, and user-defined
types in new and interesting ways.types in new and interesting ways.
So far, we haveSo far, we have
Variables and literals of typesVariables and literals of types bool, char, int, doublebool, char, int, double
vector, push_back(), [ ]vector, push_back(), [ ] (subscripting)(subscripting)
!=, ==, =, +, -, +=, <, &&, ||, !!=, ==, =, +, -, +=, <, &&, ||, !
max( ), sort( ), cin>>, cout<<max( ), sort( ), cin>>, cout<<
if, for, whileif, for, while
You can write a lot of different programs with theseYou can write a lot of different programs with these
language features! Let’s try to use them in a slightlylanguage features! Let’s try to use them in a slightly
different way…different way…
Stroustrup/Programming/2015Stroustrup/Programming/2015
26. 2626
Example – Word ListExample – Word List
//// “boilerplate” left out“boilerplate” left out
vector<string> words;vector<string> words;
for (string s; cin>>s && s != "quit“; )for (string s; cin>>s && s != "quit“; ) //// && means AND&& means AND
words.push_back(s);words.push_back(s);
sort(words);sort(words); //// sort the words we readsort the words we read
for (string s : words)for (string s : words)
cout << s << 'n';cout << s << 'n';
/*/*
read a bunch of strings into a vector of strings, sortread a bunch of strings into a vector of strings, sort
them into lexicographical order (alphabetical order),them into lexicographical order (alphabetical order),
and print the strings from the vector to see what we have.and print the strings from the vector to see what we have.
*/*/
Stroustrup/Programming/2015Stroustrup/Programming/2015
27. 2727
Word list – Eliminate DuplicatesWord list – Eliminate Duplicates
//// Note that duplicate words were printed multiple times. ForNote that duplicate words were printed multiple times. For
//// example “the the the”. That’s tedious, let’s eliminate duplicates:example “the the the”. That’s tedious, let’s eliminate duplicates:
vector<string> words;vector<string> words;
for (string s; cin>>s && s!= "quit"; )for (string s; cin>>s && s!= "quit"; )
words.push_back(s);words.push_back(s);
sort(words);sort(words);
for (int i=1; i<words.size(); ++i)for (int i=1; i<words.size(); ++i)
if(words[i-1]==words[i])if(words[i-1]==words[i])
““get rid of words[i]” // (pseudocode)get rid of words[i]” // (pseudocode)
for (string s : words)for (string s : words)
cout << s << 'n';cout << s << 'n';
//// there are many ways to “get rid of words[i]”; many of them are messythere are many ways to “get rid of words[i]”; many of them are messy
//// (that’s typical). Our job as programmers is to choose a simple clean(that’s typical). Our job as programmers is to choose a simple clean
//// solution – given constraints – time, run-time, memory.solution – given constraints – time, run-time, memory.
Stroustrup/Programming/2015Stroustrup/Programming/2015
28. 2828
Example (cont.) Eliminate Words!Example (cont.) Eliminate Words!
//// Eliminate the duplicate words by copying only unique words:Eliminate the duplicate words by copying only unique words:
vector<string> words;vector<string> words;
for (string s; cin>>s && s!= "quit"; )for (string s; cin>>s && s!= "quit"; )
words.push_back(s);words.push_back(s);
sort(words);sort(words);
vector<string>w2;vector<string>w2;
if (0<words.size()) {if (0<words.size()) { //// note style { }note style { }
w2.push_back(words[0]);w2.push_back(words[0]);
for (int i=1; i<words.size(); ++i) //for (int i=1; i<words.size(); ++i) // note: not a range-note: not a range-forfor
if(words[i-1]!=words[i])if(words[i-1]!=words[i])
w2.push_back(words[i]);w2.push_back(words[i]);
}}
cout<< "found " << words.size()-w2.size() << " duplicatesn";cout<< "found " << words.size()-w2.size() << " duplicatesn";
for (string s : w2)for (string s : w2)
cout << s << "n";cout << s << "n";
Stroustrup/Programming/2015Stroustrup/Programming/2015
29. 2929
AlgorithmAlgorithm
We just used a simple algorithmWe just used a simple algorithm
An algorithm is (from Google search)An algorithm is (from Google search)
““a logical arithmetical or computational procedure that, if correctlya logical arithmetical or computational procedure that, if correctly
applied, ensures the solution of a problem.” –applied, ensures the solution of a problem.” – Harper CollinsHarper Collins
““a set of rules for solving a problem in a finite number of steps, as fora set of rules for solving a problem in a finite number of steps, as for
finding the greatest common divisor.” –finding the greatest common divisor.” – Random HouseRandom House
““a detailed sequence of actions to perform or accomplish some task.a detailed sequence of actions to perform or accomplish some task.
Named after an Iranian mathematician, Al-Khawarizmi. Technically, anNamed after an Iranian mathematician, Al-Khawarizmi. Technically, an
algorithm must reach a result after a finite number of steps, …The term isalgorithm must reach a result after a finite number of steps, …The term is
also used loosely for any sequence of actions (which may or may notalso used loosely for any sequence of actions (which may or may not
terminate).” –terminate).” – Webster’sWebster’s
We eliminated the duplicates by first sorting the vectorWe eliminated the duplicates by first sorting the vector
(so that duplicates are adjacent), and then copying only(so that duplicates are adjacent), and then copying only
strings that differ from their predecessor into anotherstrings that differ from their predecessor into another
vector.vector.
Stroustrup/Programming/2015Stroustrup/Programming/2015
30. 3030
IdealIdeal
Basic language features and libraries should beBasic language features and libraries should be
usable in essentially arbitrary combinations.usable in essentially arbitrary combinations.
We are not too far from that ideal.We are not too far from that ideal.
If a combination of features and types make sense,If a combination of features and types make sense,
it will probably work.it will probably work.
The compiler helps by rejecting some absurdities.The compiler helps by rejecting some absurdities.
Stroustrup/Programming/2015Stroustrup/Programming/2015
31. 3131
The next lectureThe next lecture
How to deal with errorsHow to deal with errors
Stroustrup/Programming/2015Stroustrup/Programming/2015