This document provides an overview of programming in C++ using Turbo C++. It covers topics such as the structure of a C++ program, control structures, functions, classes, and problem solving techniques. Modular programming using functions is discussed, including passing parameters by value and by reference. Various programming problems are presented as examples, such as calculating mathematical values and converting between different units and scales. The use of functions, parameters, and modular programming design are emphasized throughout.
This document provides an overview of programming in C++ using Turbo C++. It covers the Turbo C++ integrated development environment, basic C++ program structure, modular programming using functions, control structures like if/else statements, and problem solving approaches. Examples are provided for calculating areas and volumes, temperature conversions, and other mathematical problems. Function prototypes, call by value vs reference, and selection structures like switch statements are also discussed. The document aims to teach basic C++ concepts and skills like breaking problems into modular functions.
C++ functions presentation by DHEERAJ KATARIADheeraj Kataria
The document discusses C++ functions. It defines what a function is and describes the different types of C++ functions including standard and user-defined functions. It explains the structure of C++ functions including the function header, signature, and body. It provides examples of defining, declaring, implementing and calling functions. It also discusses topics like function parameters, scope of variables, inline functions, and building libraries.
The document discusses functions in C programming. It covers defining and calling functions, passing arguments to functions, return statements, and different types of functions. Some key points include:
- Functions make code modular and reusable. Arguments can be passed by value or reference.
- A function is defined with a return type, name, and parameters. It is called by name with arguments. Return passes data back to the calling function.
- Functions can take arguments and return values, take arguments but not return, return values without arguments, or do neither.
- Arguments are passed right to left in C. Functions can be nested by calling one function from another.
The document provides an overview of code level optimizations that can be performed by a compiler, including common subexpression elimination, copy propagation, dead code elimination, peephole optimization, and loop optimizations. It then gives examples of applying these optimizations to intermediate three address code to reduce computations and improve efficiency. Specific optimizations demonstrated include common subexpression elimination, copy propagation, dead code elimination, and identifying induction variables within loops. The overall goal of these optimizations is to reduce both the time and space requirements of the generated code.
1. Introduction to MATLAB and programming
2. Workspace, variables and arrays
3. Using operators, expressions and statements
4. Repeating and decision-making
5. Different methods for input and output
6. Common functions
7. Logical vectors
8. Matrices and string arrays
9. Introduction to graphics
10. Loops
11. Custom functions and M-files
The document discusses various code optimization techniques that can be used to improve the efficiency of a program without changing its functionality. It covers techniques like using appropriate data types, avoiding global variables, using arrays instead of switch-case statements, combining loops, putting loops inside functions, and early termination of loops. Optimizing variables, control structures, functions and loops can help reduce memory usage and improve execution speed of a program.
Types of C++ functions:
Standard functions
User-defined functions
C++ function structure
Function signature
Function body
Declaring and Implementing C++ functions
This document provides an overview of programming in C++ using Turbo C++. It covers the Turbo C++ integrated development environment, basic C++ program structure, modular programming using functions, control structures like if/else statements, and problem solving approaches. Examples are provided for calculating areas and volumes, temperature conversions, and other mathematical problems. Function prototypes, call by value vs reference, and selection structures like switch statements are also discussed. The document aims to teach basic C++ concepts and skills like breaking problems into modular functions.
C++ functions presentation by DHEERAJ KATARIADheeraj Kataria
The document discusses C++ functions. It defines what a function is and describes the different types of C++ functions including standard and user-defined functions. It explains the structure of C++ functions including the function header, signature, and body. It provides examples of defining, declaring, implementing and calling functions. It also discusses topics like function parameters, scope of variables, inline functions, and building libraries.
The document discusses functions in C programming. It covers defining and calling functions, passing arguments to functions, return statements, and different types of functions. Some key points include:
- Functions make code modular and reusable. Arguments can be passed by value or reference.
- A function is defined with a return type, name, and parameters. It is called by name with arguments. Return passes data back to the calling function.
- Functions can take arguments and return values, take arguments but not return, return values without arguments, or do neither.
- Arguments are passed right to left in C. Functions can be nested by calling one function from another.
The document provides an overview of code level optimizations that can be performed by a compiler, including common subexpression elimination, copy propagation, dead code elimination, peephole optimization, and loop optimizations. It then gives examples of applying these optimizations to intermediate three address code to reduce computations and improve efficiency. Specific optimizations demonstrated include common subexpression elimination, copy propagation, dead code elimination, and identifying induction variables within loops. The overall goal of these optimizations is to reduce both the time and space requirements of the generated code.
1. Introduction to MATLAB and programming
2. Workspace, variables and arrays
3. Using operators, expressions and statements
4. Repeating and decision-making
5. Different methods for input and output
6. Common functions
7. Logical vectors
8. Matrices and string arrays
9. Introduction to graphics
10. Loops
11. Custom functions and M-files
The document discusses various code optimization techniques that can be used to improve the efficiency of a program without changing its functionality. It covers techniques like using appropriate data types, avoiding global variables, using arrays instead of switch-case statements, combining loops, putting loops inside functions, and early termination of loops. Optimizing variables, control structures, functions and loops can help reduce memory usage and improve execution speed of a program.
Types of C++ functions:
Standard functions
User-defined functions
C++ function structure
Function signature
Function body
Declaring and Implementing C++ functions
This document provides an introduction and overview of MPI (Message Passing Interface). It discusses:
- MPI is a standard for message passing parallel programming that allows processes to communicate in distributed memory systems.
- MPI programs use function calls to perform all operations. Basic definitions are included in mpi.h header file.
- The basic model in MPI includes communicators, groups, and ranks to identify processes. MPI_COMM_WORLD identifies all processes.
- Sample MPI programs are provided to demonstrate point-to-point communication, collective communication, and matrix multiplication using multiple processes.
- Classification of common MPI functions like initialization, communication, and information queries are discussed.
The document discusses functions and static variables in C++. It covers topics like:
- Creating functions, invoking functions, and passing arguments to functions.
- Determining the scope of local and global variables.
- Understanding the differences between pass-by-value and pass-by-reference.
- Using function overloading and dealing with ambiguous overloading.
- Using function prototypes for declaring function headers.
- Knowing how to use default arguments.
- Static variables.
The document discusses arrays in C++ programming, including how to declare and initialize arrays, access array elements using indexes, and provides examples of programs that read user input into arrays, calculate sums of array elements, and print arrays in reverse order. It also explains common array sorting algorithms like selection and bubble sort and provides examples of their implementation.
This document provides an outline and overview of functions in C++. It discusses:
- The definition of a function as a block of code that performs a specific task and can be called from other parts of the program.
- The standard library that is included in C++ and provides useful tools like containers, iterators, algorithms and more.
- The parts of a function definition including the return type, name, parameters, and body.
- How to declare functions, call functions by passing arguments, and how arguments are handled.
- Scope rules for local and global variables as they relate to functions.
This document provides an overview of C++ including:
1. What a computer and computer program are, with hardware and software components.
2. The typical development process in C++ including editing, compiling, linking, loading and executing programs.
3. Examples of simple C++ programs that print text, get user input, perform calculations and make decisions.
This document provides an overview of programming in C and functions. It discusses implementing modular approaches using functions, parameters and return values of functions, passing arrays and command line arguments to functions, and using library functions for string manipulation and converting data types. Examples and practice problems are provided relating to defining and calling functions, passing arguments by value and reference, and using standard string and numeric conversion functions. The overall aim is to teach how to work with functions and data types in C programming.
This document provides information on functions in C and C++. It discusses the main components of functions including definition, declaration, prototypes, arguments, return values, scope, and recursion. It also covers function categories, nested functions, default arguments, inline functions, function overloading, and differences between calling functions by value versus reference in C++. Overall, the document serves as a tutorial on functions and their usage in C and C++ programming.
Dead code elimination is a compiler optimization technique that removes code that can never be executed, such as unreachable code, or code with outputs that are never used. Removing dead code shrinks program size and reduces runtime. It works by analyzing the control flow and data dependencies of a program to identify code that is deemed dead. Both static and dynamic dead code elimination techniques exist.
This document discusses C++ functions. It defines standard functions that come with C++ and user-defined functions. It explains the structure of a C++ function including the function header and body. It discusses declaring function signatures separately from implementations. Parameters and scopes are also covered. Examples are provided of standard math and character functions as well as user-defined functions. Header files for organizing function declarations and implementation files are demonstrated.
The document discusses dataflow analysis and liveness analysis. It defines liveness analysis as determining which variables are "live" or may be needed in the future at different points in a program. This allows optimizations like register allocation by mapping live variables that do not overlap in time to the same register. The document outlines the formal definition of liveness, including live-in and live-out variables at each node, and provides an algorithm to compute liveness information through a fixed point iteration on the control flow graph.
Functions allow programmers to organize code into reusable blocks. There are three main types of functions: library functions, user-defined functions, and main(). Functions can return values and take parameters. Parameters can be passed by value, reference using an alias, or reference using pointers. Passing by value copies the values, while passing by reference or pointer passes the actual arguments so any changes made in the function also change the original variables. Well-defined functions promote code reuse and modular programming.
Operator overloading allows giving special meanings to operators when used with user-defined types. It is implemented using special member functions called operator functions. Common operators that can be overloaded include arithmetic, relational, and function call operators. Operator overloading enhances the functionality of operators but does not change their syntax, precedence, or associativity. It allows applying operators to user-defined types in a similar way as they are used for built-in types.
The document is a report on the topic of computer programming and utilization prepared by group C. It discusses functions, including the definition of a function, function examples, benefits of functions, function prototypes, function arguments, and recursion. It provides examples of math library functions, global and local variables, and external variables. It also includes examples of recursive functions to calculate factorials and the Fibonacci series recursively.
This document discusses C++ functions. It begins by defining what a function is and describing standard and user-defined functions. It then covers the structure of C++ functions including the function signature, parameters, return values, and body. Examples are provided of defining, declaring, calling and overloading functions. The document also discusses scope of variables, passing data between functions, and inline functions.
The document discusses dataflow modeling in Verilog. It covers continuous assignments, delays, expressions using operators and operands, different types of operators like arithmetic, logical, relational, and examples of designing basic components like a 4-to-1 multiplexer and 4-bit full adder using these concepts. It also provides examples of modeling sequential logic like a 4-bit ripple carry counter and flip-flops.
Loop optimization is a technique to improve the performance of programs by optimizing the inner loops which take a large amount of time. Some common loop optimization methods include code motion, induction variable and strength reduction, loop invariant code motion, loop unrolling, and loop fusion. Code motion moves loop-invariant code outside the loop to avoid unnecessary computations. Induction variable and strength reduction techniques optimize computations involving induction variables. Loop invariant code motion avoids repeating computations inside loops. Loop unrolling replicates loop bodies to reduce loop control overhead. Loop fusion combines multiple nested loops to reduce the total number of iterations.
MATLAB is a programming tool that simplifies programming compared to languages like C and C#. The document introduces basic MATLAB functions like help, inputting matrices and vectors, matrix operations, loops, conditional statements, and graphs. It also covers symbolic math, Laplace transforms, Fourier transforms, and other domains and transforms. The overall document serves as an introduction to essential MATLAB programming concepts and capabilities.
C++ is an object-oriented programming language that was created as an extension of C by Bjarne Stroustrup in 1979 at Bell Labs. It supports concepts like inheritance, polymorphism, and encapsulation. C++ is a systems programming language that is commonly used to develop applications that require high performance or require low-level access to hardware. Some key features of C++ include object-oriented programming, functions, arrays, pointers, strings, file handling, and inheritance. C++ allows programmers to write code that is very close to the underlying hardware and has performance advantages over other languages.
40+ examples of user defined methods in java with explanationHarish Gyanani
The document discusses user defined methods in Java and provides examples of simple programs that utilize methods. Some key points covered include:
- Advantages of using methods to organize and reuse code.
- Examples of methods that perform basic operations like addition, average calculation, data type conversions, etc.
- Passing arrays to methods and returning arrays from methods.
- Differences between functions and methods in Java.
- Overloading methods by changing the number and type of arguments.
- Implementing methods to calculate operations like LCM, HCF, prime number checks, etc.
Turbo C++ was a C++ compiler and IDE originally created by Borland and later distributed by Embarcadero Technologies after they acquired Borland's compiler division in 2008. It was an introductory-level IDE based on their C++Builder product. While the free Explorer edition could be downloaded, both it and the commercial Professional edition were discontinued by Embarcadero in 2009. Turbo C++ is now succeeded by C++Builder.
Bjarne Stroustrup first invented C++ in 1980 at Bell Laboratories as an expanded version of C called "C with Classes". C++ added object-oriented programming features like data abstraction, encapsulation, inheritance, and polymorphism to C. Some common applications of C++ include real-time systems, simulation/modeling, databases, AI/expert systems, and CAD/CAM systems. A basic C++ program structure includes include files, class declarations, member function definitions, and a main function.
This document provides an overview and introduction to the Turbo C integrated development environment. It describes what is included in the Turbo C package, the system requirements, and new features of version 2.0. It also summarizes the contents and purpose of the two manuals included: Volume I covers using Turbo C for beginners, while Volume II is a reference guide for experienced C programmers.
This document provides an introduction and overview of MPI (Message Passing Interface). It discusses:
- MPI is a standard for message passing parallel programming that allows processes to communicate in distributed memory systems.
- MPI programs use function calls to perform all operations. Basic definitions are included in mpi.h header file.
- The basic model in MPI includes communicators, groups, and ranks to identify processes. MPI_COMM_WORLD identifies all processes.
- Sample MPI programs are provided to demonstrate point-to-point communication, collective communication, and matrix multiplication using multiple processes.
- Classification of common MPI functions like initialization, communication, and information queries are discussed.
The document discusses functions and static variables in C++. It covers topics like:
- Creating functions, invoking functions, and passing arguments to functions.
- Determining the scope of local and global variables.
- Understanding the differences between pass-by-value and pass-by-reference.
- Using function overloading and dealing with ambiguous overloading.
- Using function prototypes for declaring function headers.
- Knowing how to use default arguments.
- Static variables.
The document discusses arrays in C++ programming, including how to declare and initialize arrays, access array elements using indexes, and provides examples of programs that read user input into arrays, calculate sums of array elements, and print arrays in reverse order. It also explains common array sorting algorithms like selection and bubble sort and provides examples of their implementation.
This document provides an outline and overview of functions in C++. It discusses:
- The definition of a function as a block of code that performs a specific task and can be called from other parts of the program.
- The standard library that is included in C++ and provides useful tools like containers, iterators, algorithms and more.
- The parts of a function definition including the return type, name, parameters, and body.
- How to declare functions, call functions by passing arguments, and how arguments are handled.
- Scope rules for local and global variables as they relate to functions.
This document provides an overview of C++ including:
1. What a computer and computer program are, with hardware and software components.
2. The typical development process in C++ including editing, compiling, linking, loading and executing programs.
3. Examples of simple C++ programs that print text, get user input, perform calculations and make decisions.
This document provides an overview of programming in C and functions. It discusses implementing modular approaches using functions, parameters and return values of functions, passing arrays and command line arguments to functions, and using library functions for string manipulation and converting data types. Examples and practice problems are provided relating to defining and calling functions, passing arguments by value and reference, and using standard string and numeric conversion functions. The overall aim is to teach how to work with functions and data types in C programming.
This document provides information on functions in C and C++. It discusses the main components of functions including definition, declaration, prototypes, arguments, return values, scope, and recursion. It also covers function categories, nested functions, default arguments, inline functions, function overloading, and differences between calling functions by value versus reference in C++. Overall, the document serves as a tutorial on functions and their usage in C and C++ programming.
Dead code elimination is a compiler optimization technique that removes code that can never be executed, such as unreachable code, or code with outputs that are never used. Removing dead code shrinks program size and reduces runtime. It works by analyzing the control flow and data dependencies of a program to identify code that is deemed dead. Both static and dynamic dead code elimination techniques exist.
This document discusses C++ functions. It defines standard functions that come with C++ and user-defined functions. It explains the structure of a C++ function including the function header and body. It discusses declaring function signatures separately from implementations. Parameters and scopes are also covered. Examples are provided of standard math and character functions as well as user-defined functions. Header files for organizing function declarations and implementation files are demonstrated.
The document discusses dataflow analysis and liveness analysis. It defines liveness analysis as determining which variables are "live" or may be needed in the future at different points in a program. This allows optimizations like register allocation by mapping live variables that do not overlap in time to the same register. The document outlines the formal definition of liveness, including live-in and live-out variables at each node, and provides an algorithm to compute liveness information through a fixed point iteration on the control flow graph.
Functions allow programmers to organize code into reusable blocks. There are three main types of functions: library functions, user-defined functions, and main(). Functions can return values and take parameters. Parameters can be passed by value, reference using an alias, or reference using pointers. Passing by value copies the values, while passing by reference or pointer passes the actual arguments so any changes made in the function also change the original variables. Well-defined functions promote code reuse and modular programming.
Operator overloading allows giving special meanings to operators when used with user-defined types. It is implemented using special member functions called operator functions. Common operators that can be overloaded include arithmetic, relational, and function call operators. Operator overloading enhances the functionality of operators but does not change their syntax, precedence, or associativity. It allows applying operators to user-defined types in a similar way as they are used for built-in types.
The document is a report on the topic of computer programming and utilization prepared by group C. It discusses functions, including the definition of a function, function examples, benefits of functions, function prototypes, function arguments, and recursion. It provides examples of math library functions, global and local variables, and external variables. It also includes examples of recursive functions to calculate factorials and the Fibonacci series recursively.
This document discusses C++ functions. It begins by defining what a function is and describing standard and user-defined functions. It then covers the structure of C++ functions including the function signature, parameters, return values, and body. Examples are provided of defining, declaring, calling and overloading functions. The document also discusses scope of variables, passing data between functions, and inline functions.
The document discusses dataflow modeling in Verilog. It covers continuous assignments, delays, expressions using operators and operands, different types of operators like arithmetic, logical, relational, and examples of designing basic components like a 4-to-1 multiplexer and 4-bit full adder using these concepts. It also provides examples of modeling sequential logic like a 4-bit ripple carry counter and flip-flops.
Loop optimization is a technique to improve the performance of programs by optimizing the inner loops which take a large amount of time. Some common loop optimization methods include code motion, induction variable and strength reduction, loop invariant code motion, loop unrolling, and loop fusion. Code motion moves loop-invariant code outside the loop to avoid unnecessary computations. Induction variable and strength reduction techniques optimize computations involving induction variables. Loop invariant code motion avoids repeating computations inside loops. Loop unrolling replicates loop bodies to reduce loop control overhead. Loop fusion combines multiple nested loops to reduce the total number of iterations.
MATLAB is a programming tool that simplifies programming compared to languages like C and C#. The document introduces basic MATLAB functions like help, inputting matrices and vectors, matrix operations, loops, conditional statements, and graphs. It also covers symbolic math, Laplace transforms, Fourier transforms, and other domains and transforms. The overall document serves as an introduction to essential MATLAB programming concepts and capabilities.
C++ is an object-oriented programming language that was created as an extension of C by Bjarne Stroustrup in 1979 at Bell Labs. It supports concepts like inheritance, polymorphism, and encapsulation. C++ is a systems programming language that is commonly used to develop applications that require high performance or require low-level access to hardware. Some key features of C++ include object-oriented programming, functions, arrays, pointers, strings, file handling, and inheritance. C++ allows programmers to write code that is very close to the underlying hardware and has performance advantages over other languages.
40+ examples of user defined methods in java with explanationHarish Gyanani
The document discusses user defined methods in Java and provides examples of simple programs that utilize methods. Some key points covered include:
- Advantages of using methods to organize and reuse code.
- Examples of methods that perform basic operations like addition, average calculation, data type conversions, etc.
- Passing arrays to methods and returning arrays from methods.
- Differences between functions and methods in Java.
- Overloading methods by changing the number and type of arguments.
- Implementing methods to calculate operations like LCM, HCF, prime number checks, etc.
Turbo C++ was a C++ compiler and IDE originally created by Borland and later distributed by Embarcadero Technologies after they acquired Borland's compiler division in 2008. It was an introductory-level IDE based on their C++Builder product. While the free Explorer edition could be downloaded, both it and the commercial Professional edition were discontinued by Embarcadero in 2009. Turbo C++ is now succeeded by C++Builder.
Bjarne Stroustrup first invented C++ in 1980 at Bell Laboratories as an expanded version of C called "C with Classes". C++ added object-oriented programming features like data abstraction, encapsulation, inheritance, and polymorphism to C. Some common applications of C++ include real-time systems, simulation/modeling, databases, AI/expert systems, and CAD/CAM systems. A basic C++ program structure includes include files, class declarations, member function definitions, and a main function.
This document provides an overview and introduction to the Turbo C integrated development environment. It describes what is included in the Turbo C package, the system requirements, and new features of version 2.0. It also summarizes the contents and purpose of the two manuals included: Volume I covers using Turbo C for beginners, while Volume II is a reference guide for experienced C programmers.
This document provides an overview of introductory C++ concepts for a course on C++ programming. It covers basic C++ syntax like #include, using namespace, main(), and cout, as well as variables, data types, functions, classes, and strings. The document is presented as slides with explanations of C++ code examples to illustrate core C++ programming concepts for beginners.
This chapter discusses inheritance and polymorphism in object-oriented programming. Key points include:
1. Defining classes in an inheritance hierarchy allows sharing of common properties and behaviors while also allowing specialization.
2. Abstract classes cannot be instantiated but serve as base classes that concrete subclasses extend.
3. Polymorphism allows a variable to refer to objects of different subclasses, enabling flexible code.
4. The example problem involves reading student data from a file and calculating grades polymorphically based on undergraduate or graduate status.
This document discusses the components of a C++ program structure and the process of using a compiler. It identifies that a C++ program consists of comments, preprocessor directives, functions, bodies, and return statements. It then explains each of these components and provides examples. The document also outlines the steps to build a C++ program using a compiler which are editing source code, compiling to object code, linking to an executable, and executing the program.
The document discusses different types of selection and looping constructs in imperative programming languages. It describes if-else statements, switch-case statements, and how they allow a program to select different courses of action based on conditions. It also covers while, for, and do-while loops and how they repeatedly execute blocks of code while or until certain conditions are met. Examples are provided for each type of construct to illustrate their syntax and usage.
This document discusses C programming loops and provides examples of programs using for, while, do-while, and nested loops. It includes the theory, syntax, flowcharts, algorithms, and programs for each type of loop. Several programs are provided as examples, such as one to display characters and their ASCII values using a for loop, one to calculate the factorial of a number using a while loop, one to find the Fibonacci series using a do-while loop, and one to find prime numbers using a nested loop. Students are provided learning objectives for each example to learn how to write the loop syntax, draw flowcharts, write algorithms, and implement the programs using the specified loop type.
This document contains a list of Java programming lab assignments with questions ranging from basic programming concepts like variables, conditionals, loops, methods and classes to more advanced topics like inheritance, abstraction, polymorphism and exceptions. Some questions involve writing simple programs to calculate things like pay, time conversions or name formatting while others require designing classes and relationships between them. The assignments cover core Java programming techniques and principles.
Pointers provide an alternate way to access memory locations in C++. A pointer variable holds the address of another variable. Pointer variables must be declared with a data type followed by an asterisk, such as int* p. The address operator & returns the address of its operand, and the dereference operator * accesses the value at the address a pointer points to. Arrays can also be accessed using pointers since array names represent the base address of the array. Pointers allow values to be passed by reference to functions and returned from functions. Pointer arithmetic allows pointers to be incremented or decremented to access successive elements of an array.
This document provides an overview of the components of a simple "Hello World" C++ program, including comments, header files, namespaces, functions, output statements, and escape sequences. It explains that main is the first function executed, iostream is included for input/output, namespace std contains standard library elements, cout with << prints output, and return 0 indicates successful completion. It also demonstrates using escape sequences like \n to print multiple lines with a single statement.
This chapter discusses various methods of file input and output in Java, including low-level file I/O using FileInputStream and FileOutputStream, high-level file I/O using DataInputStream and DataOutputStream to read and write primitive data types, reading and writing text files using PrintWriter, BufferedReader, and Scanner, and object file I/O using ObjectInputStream and ObjectOutputStream to save and load objects. It also covers using JFileChooser to allow users to select files and applying file filters.
Arrays allow us to store multiple values of the same data type in memory. We can declare an array by specifying the data type, name, and number of elements. Individual elements can then be accessed using the name and index. Multidimensional arrays store arrays of arrays, representing tables of data. Arrays can also be passed as parameters to functions to operate on the array values. Strings are arrays of characters that end with a null terminator and can be initialized using character literals or double quotes.
Loops allow sections of code to repeat a certain number of times. There are three main types of loops in C++:
1. The for loop repeats until a test condition is false, and includes initialization, condition, and increment expressions.
2. The while loop repeats until a condition is false, without a fixed number of iterations.
3. The do-while loop guarantees running the loop body at least once before checking the condition, unlike the while loop which may not run if the condition is false.
C++ arrays allow storing a fixed number of elements of the same type sequentially in memory. Arrays are declared by specifying the element type and number, such as int numbers[100]. Individual elements can then be accessed via their index like numbers[0]. Arrays can be initialized with a list of values or left uninitialized. Elements are accessed using their index and the array name, like n[5] to get the 6th element.
C++ is an object-oriented programming language that is based on C and adds object-oriented programming features like classes, inheritance, and polymorphism. It was created by Bjarne Stroustrup at Bell Labs in the early 1980s. The document provides an introduction to C++ including its history, differences from C, program structure, data types, variables, input/output, and integrated development environments.
This document discusses user-defined functions in C programming. It explains that user-defined functions must be developed by the programmer, unlike library functions. It covers the need for user-defined functions to organize code into logical, reusable units. The key elements of functions - definition, call, and declaration - are described. Functions can return values and take parameters to perform tasks. Well-defined functions make code more modular, readable, and maintainable.
- An array is a collection of consecutive memory locations that all have the same name and type. An array allows storing multiple values of the same type using a single name.
- Arrays in C++ must be declared before use, specifying the type, name, and number of elements. Elements are accessed using an index.
- The main advantages of arrays are that they allow storing and processing large numbers of values efficiently using a single name. Arrays also make sorting and searching values easier.
The document contains C++ code examples for performing common matrix operations using 2D arrays, including summing and subtracting matrices, finding the transpose of a matrix, multiplying 2x2 matrices, and calculating the inverse of a 2x2 matrix. It prompts the user for matrix inputs, performs the selected operation on the matrices, and outputs the results.
This document provides an overview of programming in C++ using Turbo C++. It covers the structure of C++ programs, the Turbo C++ integrated development environment, control structures, functions, classes and object-oriented programming. It also provides examples of problem solving approaches and pseudocode for several problems involving calculations for shapes like circles and trapezoids. Modular programming using functions is discussed along with passing parameters by value and reference.
This is continuation of the slide Advanced C part 1. In part 1 you learnt about fundamentals of C - How to build an algorithm, operators. In this module - Advanced C part 2 you will be learning about functions, pointers and standard Input Output functions. This slide will help you to move a further ahead in Advanced C and gain deeper knowledge on it.
02 functions, variables, basic input and output of c++Manzoor ALam
This document discusses computer programming functions, variables, and basic input/output in C and C++. It covers:
- Defining and calling functions, function parameters and return values.
- Declaring and assigning values to variables of different data types like int, float, and double.
- Using basic input/output functions like cout and cin to display output and get user input.
- The scope of variables and how they work within and outside of functions.
This document provides an introduction to C++ programming. It discusses key differences between C and C++, shows simple C++ examples, and covers important C++ concepts like input/output streams, header files, inline functions, references, and reference parameters. The document is intended to teach basic C++ syntax and features to someone new to the language.
The document discusses C functions. Some key points:
1. Functions allow breaking code into reusable chunks that perform specific tasks. The main() function is required in every C program.
2. Functions are declared with a return type, name, and parameters. Definitions include the function body.
3. Standard library functions like strcat() and memcpy() are pre-defined for common tasks.
4. Functions are called by name and pass arguments by value or reference. Parameters allow customizing a function's behavior.
5. Recursion allows a function to call itself, enabling solutions to problems like factorials and Fibonacci sequences.
Programming Fundamentals Functions in C and typesimtiazalijoono
Programming Fundamentals
Functions in C
Lecture Outline
• Functions
• Function declaration
• Function call
• Function definition
– Passing arguments to function
1) Passing constants
2) Passing variables
– Pass by value
– Returning values from functions
• Preprocessor directives
• Local and external variables
This document discusses functions in C++. It covers:
- The definition of a function as a subprogram that can act on data and return a value.
- Functions come in two varieties: user-defined and built-in.
- Functions must be declared before use with a prototype specifying the return type and parameters.
- A function is defined by providing the body of code that performs the task.
- Functions can interact through calls where parameters are passed by value or by reference.
The document discusses functions in C++. It defines functions as modular pieces that divide programs into more manageable components. It describes function components like modules, functions, classes, and function calls. It provides examples of math library functions and how to define, call, and prototype functions. It also covers function parameters, return types, and scope rules for local variables and storage classes.
Lecture#2 Computer languages computer system and Programming EC-105NUST Stuff
The document discusses three types of computer languages: machine language, assembly language, and high-level languages. Machine language is directly understood by computers using binary, while assembly language uses abbreviations and high-level languages resemble English. It also introduces C++ programming concepts like variables, data types, input/output streams, arithmetic operators, and conditional statements. Sample programs are provided to demonstrate printing text, getting user input, performing calculations, and making decisions.
Programming For Engineers Functions - Part #1.pptxNoorAntakia
This document discusses functions in C++ programming. It begins by explaining the objectives of learning about standard predefined functions, user-defined functions, value-returning functions, and constructing user-defined functions. It then provides examples of user-defined functions for finding the maximum of two numbers, checking if a number is prime, calculating the nth Fibonacci number, and calculating binomial coefficients. It also discusses concepts like function prototypes, parameters, return types, and using functions to break programs into manageable pieces.
1. The document discusses object oriented programming concepts like classes, objects, inheritance, and polymorphism in C++.
2. It begins with an introduction to procedural programming and its limitations. Object oriented programming aims to overcome these limitations by emphasizing data over procedures and allowing for inheritance, polymorphism, and encapsulation.
3. The document then covers key OOP concepts like classes, objects, constructors, and static class members in C++. It provides examples of creating classes and objects.
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
The document discusses functional programming concepts like higher-order functions, function composition, currying, and lazy evaluation. It provides examples of implementing strategies like converting between units using functions and creating streams of prime numbers lazily to avoid stack overflows. Tail call optimization is mentioned as a way to avoid stack overflows with recursive functions.
This document provides a lab manual for the course GE3171 - Problem Solving and Python Programming Laboratory (REG-2021). It contains details of various programming exercises to be completed as part of the course curriculum. The exercises cover topics like:
1. Developing flow charts and Python programs for real-life problems like electricity billing, retail shop billing, etc.
2. Python programming using simple statements, expressions, and calculations.
3. Scientific problems using conditionals and iterative loops to generate number series and patterns.
4. Implementing applications using lists, tuples to represent library items, car components, construction materials.
5. Implementing applications using sets and dictionaries for language analysis and car
Complete Course Available at: https://github.com/Ebad8931/PythonWorkshop
Python Functions are discussed in this Presentation. The concept of Functional Programming is explained through a Time Conversion from AM to PM Example. Special functions like Lambdas, map and filter etc are also introduced here.
Create the equivalent of a four function calculator. The program should request the user to enter a number, an operator, and another number. carry out the specified arithmetical operation: adding, subtracting, multiplying, or dividing the two numbers. (Using switch statement ).ThesisScientist.com
The document discusses functions in C++. It provides examples of functions without parameters or return values, functions with return values but no parameters, functions with both parameters and return values, and functions that return references. It also discusses passing arguments to functions by reference, const reference, and using inline functions to avoid function call overhead.
This document provides an introduction to basic elements of C++ programming, including:
- The structure of a basic C++ program with an example main function.
- Common data types like integers, floating point numbers, characters, and strings.
- Arithmetic operators and precedence.
- Expressions, input/output, and type casting.
- Variables, memory allocation, and initializing variables.
- Control structures like increment/decrement operators.
- Program style guidelines including comments and formatting.
1. 1
Programming in C++
The Turbo C++ Environment
C++ Program Structure
Modular Programming with Functions
C++ Control Structures
Advanced Data Types
Classes
2. 2
Turbo C++ Environment
Windows based product
Integrated Development Environment (IDE)
– editor
– compiler
– linker
– debugger
3. 3
Structure of a C++ Program
preprocessor directives
main function header
{
declare statements
statements
}
4. 4
Using the Turbo C++ IDE
tool bars
menu
editor
5. 5
Using the Turbo C++ IDE (2)
compiling
linking
executing
6. 6
Developing Programs
Understand the problem
Design a solution to the problem
– including test cases and the solutions to the test
cases
Implement and document
– Translate the solution to a programming
language
7. 7
Developing Programs (2)
Verify
– Test and debug the solution
» using test cases from design phase
Maintain
8. 8
Problem Solving (1)
consider a trapezoid -- 4 sided figure in which
two sides are ||, the area is 1/2 the product
of the height and the sum of the lengths of
the two bases.
b1
h
b2
Area = (b1 + b2)h/2
9. 9
Problem Solving -- Trapezoid
Pseudocode
input b1
input b2
input height
bases = b1 + b2
area = bases * h /2
output area
10. 10
Problem Solving (2)
consider finding the area and circumference
of a circle
pi = 3.14159
area = pi * radius2
circumference = 2 * pi * radius
11. 11
Problem Solving -- Circle
Functions Pseudocode
pi = 3.14159
input radius
circum = 2 * pi * radius
area = pi * radius * radius
output area
output circum
12. 12
Problem Solving (3)
consider converting temperatures from
Centigrade to Fahrenheit (or vice versa)
where
c = 5/9(f-32)
f = 9/5c + 32
14. 14
Problem Solving (4)
consider sales commissions based upon the
number of sales made during the time
period
$8 per sale for 15 sales
$12 per sale = 15 sales
$16 per sale 15
15. 15
Problem Solving -- Commission
Pseudocode
quota = 15
input number_sales
if number_sales quota
rate = 8
else if number_sales == quota
rate = 12
else rate = 16
com = rate * number_sales
output com
17. 17
Problem Solving -- Pseudocode
Multiple Salespeople (2)
loop number_salespeople times
input number_sales
if number_sales quota
rate = 8
else if number_sales == quota
rate = 12
else rate = 16
com = rate * number_sales
output com
18. 18
Exercise -- GO
Develop a series of problems for the students
to do using each of the statement types
19. 19
Introduction to the C++
Language
keywords
– C++ is case-sensitive
identifiers
– can not be keywords
comments
– enclosed in /* */ multi-line
– start with // single line
21. 21
Data Types and Declarations
declare statement
– allocates memory and assigns “name”
– data type name [= initial value];
int -- 2 bytes
float -- 4 bytes
double -- 8 bytes
char -- enclosed in ‘ ‘
22. 22
User Defined Data Types
class -- mechanism to establish new data
types
ap classes
– string
» apstring.h apstring.ccp
– bool
» bool.h
23. 23
Example Declare Statements
int a;
int a,b,c;
float x,
y;
double average = 0.0;
char answer = ‘Y’;
bool another;
bool more = false;
apstring name;
apstring
class = “C++”;
24. 24
Input and Output Statements
#include iostream.h
cout -- output
insertion character
cin -- input
extraction character
25. 25
Using APSTRING Class
#include “apstring.h”
– entire path
create project
– place apstring and program in project
– you will need a different project for each
program
26. 26
Input and Output Statements (2)
COUT -- control codes
– way of inserting placement control
– n -- new line
– t -- tab
iomanip.h
– contains more formatting methods
27. 27
Arithmetic in C++
operator precedence
( )
*, /, % (left to right)
+, - (left to right)
integer arithmetic
– operations involving integers yielding integer
results
– truncation on integer division
– % -- modulo operator
28. 28
Arithmetic in C++ (2)
mixed mode arithmetic
– operands of different data types
– hierarchy double/float/int
» highest mode is used
» determined on a operation by operation basis
30. 30
Increment and Decrement
Statements
special operators which add or subtract one
from a variable
– more efficient (generates inc, dec)
a++; == a = a+1;
a--; == a = a -1;
postfix (a++;) (a--;)
– done after the expression is evaluated
prefix (++a;) (--a;)
– done prior to evaluating the expression
31. 31
Type Casting
changes the evaluation data type of the
expression
– does not change the data type of the variable
(data type)
– (int)
– (float)
– (apstring)
32. 32
Programming Problems
convert distance in miles to distance in
kilometers and meters
– 1 mile = 1.61 km, 1 km = 1000 meter
convert a temperature in Celsius to Kelvin
– -273.15oC = 0oK
convert a temperature in Fahrenheit to
Kelvin
– -459.67oF = 0oK
34. 34
Programming Problems
determine the volume of a sphere with an
input radius
– volume = (4 * pi * radius3)/3
determine the area of a triangle when given
length of two sides and the included angle
in degrees
– degrees = 180 * radians / pi
– area = side1 * side2 * sin (radians) / 2
35. 35
Programming Problems (2)
determine the distance from a point on the
Cartesian plane to the origin
– distance = sqrt (x2 + y2)
36. 36
Exercise -- GO
Implement the sequential problems developed
in the first exercise
37. 37
Modular Programming with
Functions
designed in small segments
each segment implemented as a function
– sqrt, pow, sin
self contained
– requires input through parameters
– sends output through name
Abstraction
– know what the function does and what it needs
to do its task
– not how the function works
38. 38
Modular Programming with
Functions (2)
allows for reuse
eliminates redundancy
allows for team development
simplifies logic
39. 39
Form of a Function
[return data type] Function name (parameter list)
{
[declarations]
statements
[return ]
}
40. 40
Types of Functions
no input, no return value
– void
input but no return value
both input and output
no input but returns a value
41. 41
Example -- Circle Functions
calculate the area and circumference of a
circle of an input radius
– input radius
– calculate area
– calculate circumference
– output results
invoke the functions
– use name and parameters in an expression
functions must be defined before they can
be used
42. 42
Example -- Pythagorean Triples
Pythagorean Triple are the three sides of a
right triangle a,b,c
– a2 + b2 = c2
given m and n, such that mn we can
generate the triples
– a = m2 - n2
– b= 2mn
– c = m2 + n2
43. 43
Call by Value
on invocation the value of the actual
parameter is copied into the formal
parameter
when the function terminates the value IS
NOT copied back to the actual parameter
can not change the value of a parameter
within the function
44. 44
Example Call by Value
#include iostream.h
int test (int n)
{
int i = 5;
n +=i;
return (n);
}
void main (void)
{
int n=1, i;
i = test (n);
cout i “ = “
n endl;
}
46. 46
Functions -- Pass by Reference
returns 0 or 1 value through name
need to return more than 1
– swap the values of two variables
change the values of parameters
– bank deposit or check
pass the “name” of the parameter rather
than its value so that the function uses the
same memory location as the actual
parameter
47. 47
Reversing Order -- Swap
if (num1 num2)
{
temp = num1;
num1 = num2;
num2 = num1;
}
48. 48
Reference Parameters
Parameter which shares the memory of the
actual parameter rather than declare new
memory and copy the actual’s value into it
Parameter declaration
int x;
– x is an alias for the actual integer parameter
double y
– y is an alias for the actual double parameter
49. 49
Function Swap
void swap (int num1, int num2)
{ int temp;
temp = num1;
num1 = num2;
num2 = temp;
}
if a b
swap (a,b); to invoke the function
50. 50
Call by Value vs Reference
Use reference vs return type
– all input
– when need to return more than 1 value
– always have return type void
Use value
– all other cases
– no side effects
51. 51
Exercise
modify circle.cpp to use reference where
appropriate
modify pyth.cpp to have compute_sides
52. 52
Programming Problem --
Functions
program to convert Fahrenheit to Celsius,
Fahrenheit to Kelvin
– input the temperature in Fahrenheit
– use functions
» input Fahrenheit temperature
» convert to Celsius
» convert to Kelvin
» output the results
53. 53
Programming Problem --
Functions
Translate US prices from pennies per pound
to Canadian prices dollars per kilogram
– 1 pound = .4536 kilograms
– 1 dollar US = 1.26 dollars Canadian
Input 5 words, echoing each as it is input
and display the average length (number of
characters) per word
54. 54
Exercise -- GO
Implement all previous programs using
modular design and reference and value
parameters as appropriate
55. 55
Function Prototypes
a function must be declared before it can be
used
placed functions at top of program
create prototype (declaration of interface),
place it at the top and the functions’
implementation can be placed after the main
function
[return value] function name (parameter
list);
float get_radius ();
56. 56
Overloading
function names can be overloaded
– different interfaces
– compiler can determine which to execute
operators can be overloaded as well
57. 57
Selection Structures
execute a group of statements based upon a
condition being true or false
if (condition)
statement;
if (condition)
{ statement(s);
}
conditions -- relational operators
, , =, =, = =, !=
58. 58
Simple Selection Examples
if (hours 40)
cout “overtime!n”;
if (cost 30000)
{
tax = (cost - 30000) * tax_rate;
cout “n for a car costing “ cost
“a luxury tax of “ tax “ is due ”;
}
59. 59
Selection -- IF ELSE
if (condition)
statement;
else
statement;
if (condition)
{ statements;
}
else
{statements;
}
60. 60
If ELSE -- Examples
if (xy)
max = x;
else
max = y;
66. 66
Short Circuiting
efficient evaluation of Boolean expression
AND
– the first relational expression which evaluates
false terminates the evaluation-- result false
OR
– the first relational expression which evaluates
as true terminates the evaluation -- result true
67. 67
Short Circuiting (2)
determine if a number is divisible by
another number
if the second number is 0 -- error
termination
if (a != 0 b % a == 0)
if a = 0 the second expression is not
evaluated
68. 68
Programming Example
determining leap years
leap years occur every 4 years, if the year is
divisible by 4
– only valid for non-centennial years
centennial year (divisible by 100) which is
divisible by 400
69. 69
BREAK statement
allows program to leave a control structure
form -- break;
70. 70
Multiple Selection -- Switch
test the value of a single integer type and
perform different blocks of statements
based upon the value
71. 71
Multiple Selection -- Switch
Form
switch (expression)
{ case value 1:
statement(s);
break;
case value 2:
statement (s);
break; ....
[default:
statement(s);
break;]}
72. 72
Example Switch Statement
determine if a value is -1, 0, or 1-4
cin value;
switch (value)
{
case -1:
cout “value = -1n”;
break;
case 0:
cout “value = 0n”;
break;
73. 73
Example Switch Statement Con’t
case 1:
case 2:
case 3:
case 4:
cout “value in range 1-4n”;
break;
default:
cout “value is -1 or 4n”;
}
75. 75
Programming Problem
complete temperature conversion program
accepts as input a temperature and a type
and converts it to the other two temperature
types
prints an error message if unknown type
accepts both upper and lower case input
76. 76
Exercise -- GO
Implement the selection statement problem
solving problems
77. 77
Repetition Statements
ability to repeatedly execute blocks of
statements
two types of loops
– count controlled
» executed a set number of times
– event driven
» executed until a certain event occurs
» pre-test and post-test loops
78. 78
While Loop
form
while (condition)
{
statement(s);
}
event driven loop
79. 79
While Loop (2)
pre-test (0) loop
– test the condition
» if true execute the loop
» if false exit loop
» loop can be executed 0 times
81. 81
Programming Example
taking averages
enter values to be averaged until sentinel is
entered (0)
– event which terminates loop
ave.cpp
82. 82
Controlling Input
0 is in the set to be averaged
– must use some key defined value to signal end
of input
– CRTL Z
get()
– cin.get()
– accepts a single value as input
– prompt for CRTL (^) Z
83. 83
Do While Loop
event driven loop
always executes at least once (1 loop)
post test loop
form
do{
statement(s);
}while (condition);
84. 84
Do While Loop (2)
executes the loop
tests the condition
– if true executes the loop again
– if false exits the loop
85. 85
Do While Example
add the numbers from 1 to 5
sum = 0;
i = 1;
do{
sum += i;
i ++;
}while (i = 5);
86. 86
Programming Example
display square of input value
user prompt to continue
squares.cpp
87. 87
Programming Example -- Circle
Functions
robust programming
– user friendly/user forgiving
Area and Circumference of circle
– radius can not be =0
– present error message and re-prompt for input
until it is valid
– circleif.cpp
88. 88
Programming Exercise --
Pythagorean Triples
robust example
– m n and both 0
give meaningful error message
89. 89
For Loop
counted loop -- set number of times
iterates through a set of values
for (initial expression;
condition;
loop expression)
{ statement(s);
}
90. 90
For Loop (2)
initial expression -- starting point, executed
once before the loop begins
condition -- evaluated each time through the
loop (pre test)
– exit -- false
– execute -- true
loop expression -- statement(s) executed at
the bottom of the loop
91. 91
Example For Loop - I
Countdown
for (i = 1; i=5; ++i)
{
cout i endl;
}
92. 92
Example For Loop - II
sum numbers 1-5
for (sum = 0, i = 1; i = 5; ++i)
{
sum += i;
}
93. 93
Programming Examples
Factorials
– fact.cpp
– change fact to be integer (see what happens)
temperature conversions
– temps.cpp
generating random numbers
– random.cpp
94. 94
Boolean Variables
Turbo C++ does not have Boolean
– bool.h -- apclass
– 0 false, 1 true
bool flag
– if flag (if 0 false, non 0 true)
– while !flag
flags.cpp
95. 95
Programming Exercise
maintain check book balance
modular
$15 service fee for bad check
– display message
final balance on exit
96. 96
Nesting Control Structures
both selection and repetition statements can
be nested for complex execution
if else if
– else matches closest un-elsed if
all looping structures can be nested
regardless of type
97. 97
Example If else if -- Sales
Quotas
if (num_sales quota)
rate = low_rate;
else if (num_sales = quota)
rate= ave_rate;
else rate = high_rate;
98. 98
Example Nested Loops
cout “enter the number to sum to, 0 to
end”;
cin num;
while (num != 0)
{ for (sum=0, i=1; i=num;++i)
sum += num;
cout “the sum of the numbers 1 - ....
cout “enter the number to sum to ...
cin num);} /*end while*/
99. 99
Nesting Control Structures
Programming Examples
counting number of letter grades
– aven.cpp
printing multiplication tables
– table.cpp
circle functions
– circleof.cpp
100. 100
Programming Exercise
Modify the average program so that more
than 1 set of averages can be determined
Modify the Pythagorean triples so that an
unlimited number of triples can be
generated
Modify finding roots of a quadratic
equation so that all root types are
determined
101. 101
Enumeration Types
user defined data type
– enum statement
– define the domain
enum bool {false, true};
– bool -- name of data type
– false, true -- domain
integers
– false = 0, true =1
102. 102
Lines in Cartesian Plane
perpendicular, parallel or intersecting
slope
enumeration type can be used
– parameters
– return types
lines.cpp
103. 103
Exercise -- GO
Implement any remaining problem solving
programs.
Be sure have a complete set identifying all
structures including enumeration types.
104. 104
Composite Data Structures
construct that can access more than one data
item through a single name
Array -- homogenous data type
Structure -- heterogeneous data type
105. 105
ArraysVectors
collection of data components
all of same data type
are contiguous
accessed
– entire array (name)
– individual component (subscript)
106. 106
Declaring Arrays
int x[5]
– declares a 5 element array of integers
» x[0], x[1], x[2], x[3], x[4]
int x[2][5] -- two dimensional array
int x [2] [5] [5] -- three dimensional array
size must be declared at compile time
– can not int size, int x[size]
– can
» #define max_size 100
» int x[max_size]
107. 107
Referencing Arrays
elements
– float ave_temp [12]
» ave_temp [0] -- Jan
» ave_temp [11] -- Dec
» ave_temp [i+2]
no arrays bounds checking
– “fast” code
108. 108
Initializing Arrays
int x[5] = {12,-2,33,21,31};
int height [10] = {60,70,68,72,68};
– rest 0
float g[] = {3.2,5.7};
– size is set to 2
a 250 element array all to 1
int x[250];
for (i =0; i=249; i++)
x[i] = 1;
109. 109
Using Arrays
data must be passed more than once
– array1.cpp
implement vectors or matrices
– array2.cpp
data comes in haphazard order
– string example
110. 110
Passing Arrays to Functions
pass an element
– treated as any single variable of that type
» pass by value
pass the entire array
– use the name without any subscripting
– pass by reference
» pass the address and the actual memory locations of
the actual array are used by the function
» any change made to the elements of the array by the
function WILL be noted in the main program
111. 111
Programming Problem
Input a set of exam scores for a class
– calculate and display
» average
» high grade
» low grade
» those grades which were above the average
– have number of grades entered determined by
the # of values input rather than prompt for
class size
112. 112
Programming Problem
Using an enumeration type for months of
the year
– calculate the average rainfall
– display those months with average rainfall
amounts
113. 113
Structures
Heterogeneous data type
– logically related set of items which can be
accessed either on an individual item basis or
all at once through structure’s name
– fields can be of any data type (different ones),
user defined as well
114. 114
Example Structure
struct GRADES
{ apstring name;
int midterm;
int final;
float assigns;
float sem_ave;
char letter_grade;};
GRADES student1, student2;
115. 115
Operations on Structures
Assignment
– entire structures done by common elements, in
order
– single element -- data type
Initialization
– on declare
» FRACTION num1 = {1,2};
» GRADES student1 = {“john Doe”,90,80,70,80};
116. 116
Structures and Functions
An element is passed to a structure in the
same way any simple variable is passed
– by value (default) or by reference (forced)
– student.cpp
An entire structure is passed
– by value (default)
– by reference (force) employee.cpp
A function can return a structure variable
117. 117
“Arrays” and Structures
Structures can contain vectors, apstring
– apstring name
– apvectorint exams(3)
vectors of structures
– apvectorGRADES class(60);
» 60 students in class
» class[0].name class[0].final
» class[59].name class[59].final
118. 118
Hierarchical Structures
Structures can contain structures
typedef struct
{char last [15];
char first [15];
char middle;} NAME;
typedef struct
{NAME stu_name;
…} STUDENT;
119. 119
ArraysVectors
collection of data components
all of same data type
are contiguous
accessed
– entire array (name)
– individual component (subscript)
120. 120
Declaring Vectors
#include “a:apvector.h”
apvectorint v1(10);
– declares a 10 element integer vector
– v1[0], v1[1], v1[2]….v1[9]
apvectorint v2(10,0);
– declares a 10 element integer vector
– all elements are initialized to 0
– v2[0]=0, v2[1]=0…..v2[9]=0
121. 121
Declaring Vectors (2)
apvectorapstring (25);
– declares a vector of 25 strings
– each is “empty” string
can be user defined data types
122. 122
Accessing Elements
v1[1]
– second element of the vector
v1[9]
– last element of the vector
v1[1] += 2;
high = v1[3];
123. 123
Assignment -- APVECTOR
Apvectorint v1(10), v2(20);
v1 = v2;
– v1 will be “reallocated” at a size of 20
– v1[0] = v2[0]
– ….
– v1[19] = v2[19]
corresponding elements will be assigned
124. 124
Member Functions -APVECTOR
User defined data type -- class
length() -- capacity of vector
– size changes as needed
– returns current size as an integer
– object.length()
» v1.length() = 20
» v1 still ranges from 0-19
for (i=0;iv1.length();i++)
cout v1[i] endl;
125. 125
Vectors as Parameters
elements are considered same as any single
variable
entire vector
– pass by value or by reference
– more efficient to pass by reference
– avoid side effects
» const reference parameter
126. 126
Using Vectors
data must be passed more than once
– vect1.cpp
implement vectors or matrices
– vect2a.cpp
data comes in haphazard order
– string example
enumeration types and vectors
– rainenum.cpp
127. 127
Matrices
two dimensional array
problems with C++ arrays are doubled in
two dimensions
APMATRIX
– #include “a:apmatrix.h”
– can automatically be “resized”
– subscript checking
128. 128
Declaring Matrices
apmatrixint imat (3,3)
– imat[0][0] ....imat [2][2]
apmatrixint imat2(3,3,0)
– all elements are initialized to 0
can be any system or user defined data type
129. 129
Referencing Elements
imat[1][2] = 7;
score = imat [i][j];
if subscript is out of bounds (either of them)
program error terminates
131. 131
APMATRIX--Member Functions
numrows() -- returns the number of rows
– imat.numrows() == 10
numcols() -- returns the number of columns
– imat.numcols() == 10
for (r=0;rimat.numrows();r++)
for (c=0;cimat.numcols();c++)
cout imat[r][c];
132. 132
Programming Problem
Create “resuable” functions for matrix
addition and multiplication
– matrix.h
– matrix.cpp
– use_matrix.cpp
133. 133
ADT -- complex numbers
struct COMPLEX
{ double real;
double imag;};
operations -- input, output, add, subtract,
mult, divide, absolute value
package together in include file
134. 134
Class -- User Defined Data Type
encapsulate data and functions
information hiding
– public vs private
can be inherited
– structures can not
135. 135
Public VS. Private
client programs can use the member
functions which “come with” a class
through the public interface
client program CAN NOT access any
function or data member declared private
– information hiding
– if can’t access it, can’t modify it
– more maintainable -- fewer side effects
136. 136
Class Definition
class class_name
{public:
member functions
private:
data members
};
137. 137
Data Members
Pieces of information which the class
maintains
– states
» date -- month, day, year
» complex number --- real, imaginary
» fraction -- numerator, denominator
» student -- name, ssn, address, etc
Private-- only the functions of the class
have access to them
138. 138
Member Functions
Services provided by the class to
manipulate the data members
Public -- can be used by any “client”
program
Have access to the data members
Constructors, Accessors, Mutators, and
Operations
139. 139
Constructors
Automatically invoked by the system when
an object of the class is declared
specify the initial values to be given to the
data members
function with the same name as the class
itself with no return type of any kind
can be overloaded
140. 140
Accessors
Return the value of a data member
Const functions as they do not change the
value of any data member
Necessary since no “outside” function can
access the data members
141. 141
Mutators
Modify one or more of the data members
used by client programs to modify the data
members, since client programs can not
access the data members directly
142. 142
Operations
Provide services of the class
perform calculations, etc using data
members
necessary since the data members are not
accessible to the client programs
143. 143
Date Class
Data members
– int day, int month, int year
Constuctor
– allow date to be set when the object is declared
– or to use default values
small implementation of the class
– demonstration purposes only
144. 144
Interface of the Date class
Definition of the class
available to client programs/ers
.h file
declaration of the data members
interfaces of the member functions
the object receiving the message to invoke
the member function is the one that the
function operates upon
145. 145
Date Class Implementation
.cpp file
the implementation of all member functions
scope resolution operator ::
– since the function implementations are in a
separate file need to tie them back to the class
or they will not have access to the data
members
146. 146
Client Program
Declares an object of the data type
– Date today;
Invoke a member function
– object.function_name();
– object which receives the message is the one on
which the function the function operators
» v1.resize();
» v1.length();
147. 147
Constructor
Default initial values for parameters
– if the parameters are omitted the initial value of
the fraction on declaration is 1/1
initialization list
– special form of the constructor which allows
the data members to be set within the interface
(.h file)
148. 148
Fraction Class
Represents rational
numbers
constructor
– initializes object to 1/1
accessors
– reduce
– print_fraction
Mutators
– input_fraction
operations
– add, subtract, multiply,
divide
gcd
– needed by class to do
its work
149. 149
Member vs Friend functions
Member function must be invoked with
object receiving message
friend function stands separate
– it still has access to the data members
– does not need an object to be invoked
– used for binary operators which do not modify
their parameters (overloading)
defined in interface as friend
150. 150
Complex Number Class
class COMPLEX
{public:
COMPLEX(int r=0,int i=0);
int real() const;
int imaginary() const;
COMPLEX add_complex
(const COMPLEX l, const COMPLEX r);
152. 152
Complex Number Class -- Con’t
void set_real (double);
void set_imag(double);
private:
double real;
double imag;
};
153. 153
Member vs Friend functions
Member function must be invoked with
object receiving message
friend function stands separate
– it still has access to the data members
– does not need an object to be invoked
– used for binary operators which do not modify
their parameters (overloading)
defined in interface as friend
154. 154
Inlining
Used to provide an implementation within
the interface
Only use on “small simple functions” which
either simply set data members or simple
calculations which return values
155. 155
This pointer
Refers to the object receiving the message
*this == value
– used in functions which modify the object
receiving the message +=,-=,*=,/=
156. 156
File I/O
Input and output are done through streams:
istream and ostream (fstream.h)
– cin -- istream -- iostream.h
– cout -- ostream -- iostream.h
4 steps to using files
– declare an object of the appropriate stream
open the stream
– connects the external file with the stream
(buffer)
– stream.open(filename);
157. 157
File I/O(2)
Input but from the stream declared
rather than from cin
output but from the stream declared
rather than cout
close file
– stream.close();
Editor's Notes
Turbo C++ environment
IDE, structure of a C program, process of developing executables (C, L, R) c errors, link errors , run errors
Intro. to C++
elementary data types, ap classes string, bool
declare statement, include, i/o, arithmetic operators,
assignment statement, increment/decrement
Modular
top down problem solving, functions, parameter passing
C control structures
relational and logical operators, short circuiting, break,
if the else, switch, do, while, for, compound logical, nesting
Advanced data types
one dimensional arrays -- vector class, sorting
multi-dimensional arrays -- matrix class
Structures
Classes -- public/private data members/member functions/ constructors
windows -- cut/paste/etc
IDE -- allows for integrated development in a windows environment
different features modify the speedbar
C++ programs are a series of functions to be performed which together perform a specific task... at minimum it must contain a main ()
preprocessor directives -- start with # as first non-blank character
give instructions to the C preprocessor which based on these
instructions modifies your program BEFORE it is compiled
main function header -- a program is written in a modular format where it is simply a series of functions which must be performed Main is the starting point
{} begin/end of a block of code
form of sample programs -- line 1 comment containing file name on the disk
load and look at first.cpp -- load turbo c++, click on disk -&gt; on toolbar, set drive to a: then *.cpp, list of files appear in window, double click on first
/* */ -- multi-line comment // - single line comment
Tool Bars
help opensaveview includessearchreplacecutcopypasteundocompilerebuild (compile/link)
Menu
file -- print
run -- run, debugger
window -- switch between windows
Editor
auto indent
comments/literals are different shades of blue
code is black
preprocessor commands are green
Compileopens message window
automatically positions on error in editing window
click on next error/warning message and you are automatically positioned at next error in the editor window
compile first.cpp (no errors), link first (no errors, 1 warning),
run first
load cent.cpp -- attempt to compile, fix all errors
Linkopens message window
lists errors but does not position in the editor window
there might be errors finding an element
Run must choose from the menu-- no power button, will rebuild if needed
opens execution window, which stays in front until you close it
must close the window explicitly
run cent, load and run zero to show execution errors -- opens execute
window and new window with error message... dead until click OK
run zero2.cpp input denominator
5 -&gt; 203 -&gt;33 not 33.33333
understand the problem
algorithm -- general solution to a problem
“a step by step procedure for solving a problem in a finite amount of time”
determine -- use decomposition technique
divide & conquer -- break the problem into smaller more manageable pieces which together solve the problem
implement these pieces with functions
design the solution -- work in Pseudocode
determine test cases and their correct solution
desk check Pseudocode with test cases
find all solutions can be expressed as a combination of statement types
sequential -- in order
selection -- alternative execution
repetition -- iteration of block of code
modular -- segments of code treated as one
debugging is WORK!
maintenance -- longest and most costly phase
decompose into subfunctions
input the bases, height
calculate area
output results
sequence is necessary
notice b1+b2 is done first, is there another way??
commands and variables -- define identifiers and self-documenting names
variable and only contain one value at any one time
only uses sequential statements
trap.cpp -- uses a=(b1 + b2)*h/2
constant -- pi is an identifier whose value will not change so that we can declare it a constant and then it’s value can not be changed
also only needs sequential statements
selection statements allow for alternate execution based on the value of a decision or logical expression for example this solution makes NO SENSE for radius values &lt;= 0, we would need selection statements to only do the calculations if the radius input &gt; 0 , try values &lt;=0... what happens??
first.cpp
requires selection statements as we need to know in which direction we are going
decomposition --
input temperature
input scale
use scale to determine direction
convert appropriately to new temperature
output new temperature
test cases ===&gt; 0 centigrade = 32 Fahrenheit
100 centigrade = 212 Fahrenheit
notice = =
if true do first statement
if false do second
never do both
selection statements allow for alternate execution based on the value of a decision or logical expression
notice indenting -- style -- work for readability
readability, modifiability (maintainable) and correctness
three keys to successful programming
cent2.cpp -- use test cases.. how many times will you need to run it?
remember both ways must be tested
requires multiple selection
multiple selection -- last else catches all
only one of the branches will be taken as choosing one path excludes all others
test cases -- be sure all paths are done -- three sets &lt;15, =15, &gt;15
again question of BAD data -- user friendly/forgiving ROBUST
not real useful -- only does one person need repetition
need to know how many sales people working with
input is now number of people
then for each person their number of sales
commis.cpp
quota constant -- easy changes
input number of salespeople-- determine how many times we repeat the section of code
test cases -- be sure all paths are done -- three sets &lt;15, =15, &gt;15
and be sure that the loop is tested at the boundaries and within
again question of BAD data -- user friendly/forgiving ROBUST
there are other more flexible types of looping -- sentinel till something happens to make us stop
this is a counted loop -- know the number of times to repeat
comm2.cpp
sequential -- i/o assignment (possibly inc, dec)
selection -- both if , if else, nested if else
iteration -- counted loop
sentinel loop
include all data types stings, char, int, float, double, bools
Grade Option -- TURN IN -- for each problem describe the construct, data type being exemplified
BREAK INTO GROUPS of 3-4 each (not whole class) this will give us lots
of examples to share
keywords are explicitly reserved words that have special/strict meaning in C++
the can not be used in other contexts or redefined
case sensitive -- C++ is
A is different from a
Pay from pay from pAy from paY etc.
keywords are all lower case -- you should use all lower case!
identifiers -- any name used in a program
rules -- must start with a letter
contain letters, digits, and underscore
no blanks or special characters
&lt;= 31 characters long
can not be keywords // case sensitive
comments -- literals to document the program
enclosed in /* */ set or begin with //
not compiled, etc include name, date on every program
library files --allow access to already built reusable functions and definitions
header file -- library file which contains definitions of constants and functions. We group constants and functions into header files based upon
similar purpose (unit conversions)
iostream.h -- contains definitions of C++’s i/o functions
math.h contains the mathematical functions (pow, sin, cos, etc)
apstring.h -- ap class for strings
bool.h -- boolean data types
the actual functions are in the run-time library or within your directory and the link process includes them with your program
to include a header file with your program use
#include &lt;header file name&gt; (look in the standard library)
#include “header file name” (look in personal library)
constants -- programmer defined data and its associated name
specified at the beginning of program
look at first.cpp (comments, #include)
declare statement -- informative message to the compiler non-executable
allocates memory and assigns a “name” to that memory location
form-- data type name [initial value]; (all c statements end in a ;)
data type -- set of values (domain) and the set of operations that can be performed on those values
4 predefined data types in C int, float, double, char (only those of interest are
MANY others)
int -- represents integers both positive and negative
simply digits-- no commas, decimal points, $ etc
allocated 2 bytes -- 16 bits values can range between
-32,768 -- 32,767
float -- floating point numbers both signed and unsigned
must include decimal point (or the program blows)
no commas, $ but can use scientific notation (e)
allocated 4 bytes
double -- same as float but allocated 8 bytes
char -- non-numeric character data/any ASCII character enclosed in single ‘‘
overflow and underflow
modify apstring.h and .cpp to correct path
bool -- true or false
other compilers provide bool -- look at bool later
string class is a first class data type-- apstring
array of chars [] for substring only
string name;
automatically variable length
using functions object.function
length(), find(), substr -- member functions
&lt;&lt;,&gt;&gt;, getline
+ -- concatenate
notice = instead of == of the if statement
use string class naturally -- see previous slide
i/o is performed by the object iostream -- two instances cout, cin
the compiler interprets the data (translates from text to data type)
first.cpp look at it -- interactive input
load sum.cpp -- example of inputting two in a row with different couts
load sum2.cpp -- in one cout
endl -- new line -- flush the buffer
names.cpp ==&gt; string i/o
whole path even if in same directory
will have to do this for any “home grown” class
project necessary so that linkage editor can find the object module for the class which is not in the system supplied library
control codes --
-- newline, -- tab
without formatting 6 to the right just right on the left
round or truncation, loss of significant digits??
load rndtrun to determine
load cent, first, zero, sum, sum2 look at the output
setiosflags ios::fixed setprecision setw
if too small just makes it right
what is the value of 5+3*2+12/16 13 or 4.6666 (13)
operator Precedence:
( )
*, /, % -- left to right
+, - -- left to right
can not imply multiplication must use *
int arithmetic
operations involving integers yielding integer results
7/2 = 2 not 2.3333
999/1000 = 0
modulo operator -- %
7 % 3 = 1
if x&lt;y =&gt; x % y = x
can be used to determine parity (odd or even) by %2
only valid for ints
data type hierarchy is double/float/int
highest mode determines the resulting mode and how arithmetic is done
examples
999/1000 -- both int so int =&gt; 0
999.9/1000 -- float =&gt; .999
999/1000.0 -- float =&gt; .999
20.0/3*20/3==&gt;
(20.0/3) * 20 /3 ==&gt; 6.6666 *20 /3 ==&gt; 133.333 /3 =&gt; 44.444443
20/3*20.0/3 ==&gt;
(20/3) *20.0/3 ==&gt; 6 *20.0 /3 ==&gt; 120.0/3 ==&gt; 40.0
20.0/3 + 20/3 ==&gt; 6.666 + 6 =&gt; 12.666
7.0/3.0*3.0 -- should result in 7.0 but doesn’t always
7.0/3.0 =&gt; 2.333333
and on some systems loose precision (turbo c does not -- feel free to run it)
= assignment operator
variable = expression;
illegal -- x+2 = y+2;
float x;
x = 7/2; x=&gt; 3.0
float y;
int x;
y= 19/4;
x= y*4;x=16 y=4.0;
x = x+1; ==&gt; x+=1;
x = x*15 ==&gt; x*=15;
x *=15+y ==&gt; x= x*(15+y);
a =5, b=6, c=10, d=4
a = b++; ===&gt; a=6 b=7
a =b, b++
a = ++b; ===&gt; a=7 b=7
b++, a=b
a = b++ * --c / d++ + ++d;
--c
++d
b+c/d+d ====&gt; a =15, b=7, c=9, d=6
d++
b++
AP exam == frowns on this usage DO NOT DO!!
changes the evaluation of a given variable or expression to a different data type
can be user defined types as well
float f;
f = (int) (2.5 *4.3) ==&gt; f= 10.0
type casting applies to the expression only it does not alter the data type of the variable
int x,y;
y=10;
x = (float) (y)/4*10;
x ==&gt; 10.0/4*10==&gt; 2.5*10 ==&gt; 25
without the type cast 20
x = (float) (y/4) *10 ==&gt; get 20 again
freezing in Kelvin is 273.15
boiling in Kelvin is 373.15
solutions are miles.cpp and ckelvin.cpp fkelvin.cpp
don’t forget int division when doing fkelvin
libraries of functions exist that are pre-written and WORK...they can simply be reused by including them with a #include statement -- all classes can be used!!
standard math functions not provided by C’s operators (no exponentiation)
sqrt (double x)
pow (double x, double exponent)
abs (int x)
fabs (double x)
ceil (double x) smallest whole number not &lt; x ceil (45.23) =&gt; 46
exp (double x) ex
floor (double x) largest whole number not &gt; x floor (45.23) =&gt; 45
example roots of quadratic equation (quad.cpp) -- demonstrate blow up
data will make this fail -- can’t take a negative square root
discriminant (b2 - 4ac) must be positive or roots are not defined
requires if (do know that if =0 single double root
requires nested if’s)
Domain error -- out of range of legal values
areat.cpp
vols.cpp
notice 6 decimal places
dist.cpp
still 6 places
how to include files -- whole path
must set up project to include home grown classes
functions can stand alone
gets its input through parameters, returns output through function name
know how to invoke the above
pow (x,y) ==&gt; x,y are parameters, order, returns its value through the name pow
main () ==&gt; no parameters, we can send them into main but beyond the scope here, from warning message know main is supposed to return something, namely an integer
abstraction
the process of separating out the details of how something is implemented from what it does... allows for modular design, allows us to concentrate on each section
know what pow does not how it does it
understand the purpose of function
the arguments the function must receive
the data it returns
logic -- incremental development
reuse -- component assembly
team -- each person develops a function (speed up work)
redundancy -- performed many times
if with different data just send it in as parameters
optional return data type -- default is int is left out, can be void ,
how the function returns its value (singular!)
function name -- any valid identifier
parameter list -- those pieces of information the function needs to do its work
can declare local variables
set of statements to do work of the function
optional return-- if it returns a value then the statement is mandatory
form: return (value);
if its return is void (does not return a value) the return statement is not needed
{} are the begin/end of the function
functs.cpp -- (find_max, larger-- local variables) how to invoke
A function may have 0 or more parameters, and return 0 or 1 values
if it has no parameters we say void
main () -- no parameters
main (void)
a function need not return anything
void main ()
give instructions, messages
input but no results --
void name (parameters)
output information -- print_formatted
input and output -- computes something -- find_max
no input but returns something -- get values from the user
get_radius, zero
load circle.cpp
look at form of functions calc_area, calc_circum
comments
parameters, return values
pi -- ap frowns on define discuss its advantages
invoking the function
use name in the expression
placement of the functions in the program -- must be defined before they can be used -- prototypes/interfaces later
local variables -- discuss them compare it to first.cpp
load pyth.cpp
instructions -- no i/o
results -- i but no o
generate -- both i/o
could write get_m and get_n
int get_m (void)
{
int m;
cout &lt;&lt; “enter the larger of the two numbers:”;
cin &gt;&gt; m;
return (m);
}
etc.
what happens if m, n or if either =0?
actual is those in function invocation statement
formal is those in the function interface
memory is allocated for test when the function is invoked...
the value of n is copied in (1)
i gets memory which is initialized to 5
n becomes 6
the function returns n through its name --
value gets copied into i
the memory for test is deallocated
in the main procedure n retains its original value -- it is not changed
i gets the value of 6
need to change the value or return more than 1 value
deposit, check -- updating balance
the actual memory location is used so that the actual memory is modified by the function
so common write a function if call by value won’t see the change
exercise -- write this -- solution is swap1.cpp
only the parameter is declared as a reference not the actual!
if is in the main
num1, num2 are formal parameters
a,b are actual
solution swap.cpp
in circle.cpp get_radius should be by reference
side effects -- changes made “accidentally”
solution is circle2.cpp, pyth2.cpp
notice different invocations
use the editor effectively so that you are not retyping
use reference and value appropriately
solution f_to_ck.c
canusf.cpp
words.cppinclude format
project setup
the same as the function header except it ends in a semi colon
also know as the interface
the actual code is know as the implementation
interface -- different parameters either in type or number
dist2.cpp -- notice enter_point is a function to avoid duplication of code
if then -- but no keyword then
if the condition is true we execute the statements if false we skip the statements
notice = = --- common C programming error, while turbo c gives warning
VAX C and UNIX C DO NOT!
3&lt;4 == T
x&lt;4 True sometimes false others
notice placement of {}
notice indentation
else part is executed when false
notice the ;
notice all the ;’s
notice the use of {} even though its only one statement -- allows for easy modification
robust -- will handle the unexpected input of 0
solution is quad2.cpp
only send error message not single double root, imaginary roots
truth tables for and, or, not
always use () anyway
not all languages short circuit
in ADA and then or then
allows for more efficient code
leap.cpp
not the most elegant solution -- purpose is to demonstrate complex expressions
notice leap_year()
used in complex if then else statements to leave rather than continue evaluating
used in next statement switch statement
evaluates the expression which must produce an discrete type ...ordered
int, char, bool, enum
compares the value to each of the cases upon equality it executes the statements and IF there is a break statement it leaves the structure
no break it continues down the list of values
default is optional if left out it simply goes on to the next statement
can use or case 1:
case 2:
but not and
temp_con.cpp
solution -- very modular (possibly library creation!!!)
if worthwhile do it!!
notice no ; at end of while statement
prints 5 4 3 2 1
if we could control the screen ... window (which C++ can, uses header file conio.h) we could have a blast off display!
notice the robustness check to be sure values have been entered
aveof.cpp
EOF defined in iostream.h
cin.get (object.function)
^c -- interrupt endless loops
notice the ; on the while statement (end of the structure)
thus the loop is always executed at least once
could also be done in a count controlled loop or a while loop
notice must enter one value!!
what does it take to make it terminate?
still needs work -- nested loops
modify pyth.cpp to be robust etc
discuss flags!!!
pythif.cpp -- notice for formatting
i=1
i&lt;=5
cout
i++
comma operator (sum =0, i=1)
with fact as integer -- other systems blow up with overflow error at 32
turbo just gives garbage results
notice reusables in temps (if library has been created use it!)
random -- in stdlib.h srand() rand()
exercise -- modify words.ccp to use for loop solution wordsl.cpp
look also at pythif -- uses flag can change code to be if flag rather than if flag == 1
could declare an enumeration type for booleans
do not need to setup a project (no object module to be linked in) but need the entire path
bank.cpp
difference with define/const
quota question from problem solving commis.cpp
leap.cpp uses nested ifs
else matches closet un-elsed if
circle functions-- so far have not been very useful only do 1 circle at a time
to do more than one need nesting loops
what makes it terminate??
originals to be modified--
aven.cpp
pythif.cpp
quad2.cpp
solutions--
pythifn.cpp
avenp.cpp
quad3.cpp
two enums -- bool and line type
discuss difference between bool.h and enum -- ap wants use bool.h and know about enums.
reuse of get_point!!!!
Also unions -- not covered here
Arrays -- standard C++ method is trouble some-- no range checking
pointer likeness (dynamic allocated)
AP people have built a user defined type APVECTOR
Conceptualization is the same -- syntax and usage that is different
vectors -- ap class APVECTOR -- .h and .cpp change files on disk
why they created apvector
c++ doesn’t check array bounds so you can go out of bounds and modify memory locations without any error or warning
can’t say a=b if a,b are arrays
won’t adjust array size dynamically
arrays are passed by reference so & is confusing
apvector
checks array bounds
a=b is allowed -- dynamic array size adjustment
normal usage of pass by reference
three dimensional is largest C can handle
rain1.cpp
starting address is passed
Grades.cpp
also discuss calculating the mode
Rainenum.cpp
array -- homogenous -- all same data type, select element through its position
structure -- heterogeneous -- different data types, access through its name
ADA -- record
What we have declared (student1, student2) are contiguous memory areas
to refer to an individual item -- qualify it -- selector operator .
student1.name studnet1.exam1 student2.name
or can refer to entire structure:
student1 = student2;
struct PARTS struct FRACTION
{ int number;{int numerator;
char name[25]; int denominator;};
int on_hand;};
PARTS part1, part2;FRACTION num1, num2;
student1.name = ”cindy”;
student1.midterm = 100;
part1.on_hand++;
order of declared items
CAN NOT USE IN CONDITION
no -- (student1 = = student2)
student.cpp
Pass entire structure
void print_stu (GRADES stu)
{….
return a structure:
GRADES get_stu ()
{GRADES in_stu;
printf (“students name: “);gets (in_stu.name);
printf (“exam1: “);scanf (“%d”,&in_stu.exam1);
….
Return in_stu;
}
pass by reference: when structure is large -- not to waste memory and machine time use const where appropriate
Remember passed normally by value ==&gt; const reference
strucarray.c -- example of using inventory application
Conceptualization is the same -- syntax and usage that is different
vectors -- ap class APVECTOR -- .h and .cpp change files on disk
why they created apvector
c++ doesn’t check array bounds so you can go out of bounds and modify memory locations without any error or warning
can’t say a=b if a,b are arrays
won’t adjust array size dynamically
arrays are passed by reference so & is confusing
apvector
checks array bounds
a=b is allowed -- dynamic array size adjustment
normal usage of pass by reference
Apvector is a generic class (template)
apvector&lt;dt&gt; variable name(#values,[initial value]);
can we write add, sub functions and place them in library -- vector.h .cpp
Strings -- in C++ are simply arrays of characters (can not grow)
APSTRINGS -- can grow dynamically (one of the reason ap people created them) so it doesn’t matter that they are empty on declare
Access a single element
can be on left or right side
if subscript is out of bounds error terminates
uses [] instead of ()
other member functions
resize -- used in passing vectors
vector.cpp
only operator =
vector.cpp and vect2a.cpp
resize in passing
or can use the class construct!
interfaces of member functions only NOT the implelementation
stored in .h file
implementation is in .cpp file
data members are standalone contents of structure
class itself ties it into one unit just as the structure
did
Can be of any data type (even user defined)
can be accessed individually or as a unit
when you declare an object of the class you get all data members
Class must supply everything since the data members are private
Can have default initial values for the parameters
Use of const is desirable so no side effects can occur
Class must provide everything!
Including I/O etc
Look at date.h
look at interfaces---- no parameters so what is it doing the work on???
Look at date.cpp
look at the implementations --- what are they doing their work on??
Rational.h
Gcd could be a private function since it is only used by the class to do its work but then no other class could use it
Add, etc are friends so we can call them naturally otherwise we would have to invoke it
left.add(right) when add is a friend we invoke it
add (left, right)
same in date class with equal==&gt; left.equal(right) verse equal(left,right)
rational.h, rational.cpp, & use-rat.cpp
read complex2.h
look at complex2.cc
notice no scope resolution operatoron the firend functions but there is one on +=
types of functions
constructors
accessors
mutators
operations
add,sub,mult,div could be written as overloaded operators
they could then be used naturally
Same slide now rewrite complex ops as friends rather than members
Add, etc are friends so we can call them naturally otherwise we would have to invoke it
left.add(right) when add is a friend we invoke it
add (left, right)
same in date class with equal==&gt; left.equal(right) verse equal(left,right)
rational.h, rational.cpp, & use-rat.cpp
read complex2.h
look at complex2.cc
notice no scope resolution operatoron the firend functions but there is one on +=
Look at complex2.h
inlined -- constructor
real(), imaginary()
conversion to double
abs
conj
Stands for input file stream
output file stream
filename must be in “”