C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements C Programming for Engineers A Review of C. Introducing iostream Nick Urbanik nicku@nicku.org This document Licensed under GPL—see slide 263 Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read 2006 February slide 1/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Welcome! C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Welcome to our class in Electrical Control, C Programming My name is Nick Urbanik Call me Nick C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers My email address is nicku@nicku.org The notes for this class are always available at http://nicku.org/c-for-engineers/ I taught in Hong Kong for ten years I taught in Macau one year before that Before that I wrote software in C++ to collect data for medical experiments Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 3/256 Welcome! C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Welcome to our class in Electrical Control, C Programming My name is Nick Urbanik Call me Nick C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers My email address is nicku@nicku.org The notes for this class are always available at http://nicku.org/c-for-engineers/ I taught in Hong Kong for ten years I taught in Macau one year before that Before that I wrote software in C++ to collect data for medical experiments Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 3/256 Welcome! C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Welcome to our class in Electrical Control, C Programming My name is Nick Urbanik Call me Nick C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers My email address is nicku@nicku.org The notes for this class are always available at http://nicku.org/c-for-engineers/ I taught in Hong Kong for ten years I taught in Macau one year before that Before that I wrote software in C++ to collect data for medical experiments Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 3/256 Welcome! C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Welcome to our class in Electrical Control, C Programming My name is Nick Urbanik Call me Nick C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers My email address is nicku@nicku.org The notes for this class are always available at http://nicku.org/c-for-engineers/ I taught in Hong Kong for ten years I taught in Macau one year before that Before that I wrote software in C++ to collect data for medical experiments Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 3/256 Welcome! C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Welcome to our class in Electrical Control, C Programming My name is Nick Urbanik Call me Nick C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers My email address is nicku@nicku.org The notes for this class are always available at http://nicku.org/c-for-engineers/ I taught in Hong Kong for ten years I taught in Macau one year before that Before that I wrote software in C++ to collect data for medical experiments Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 3/256 Welcome! C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Welcome to our class in Electrical Control, C Programming My name is Nick Urbanik Call me Nick C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers My email address is nicku@nicku.org The notes for this class are always available at http://nicku.org/c-for-engineers/ I taught in Hong Kong for ten years I taught in Macau one year before that Before that I wrote software in C++ to collect data for medical experiments Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 3/256 Welcome! C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Welcome to our class in Electrical Control, C Programming My name is Nick Urbanik Call me Nick C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers My email address is nicku@nicku.org The notes for this class are always available at http://nicku.org/c-for-engineers/ I taught in Hong Kong for ten years I taught in Macau one year before that Before that I wrote software in C++ to collect data for medical experiments Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 3/256 Welcome! C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Welcome to our class in Electrical Control, C Programming My name is Nick Urbanik Call me Nick C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers My email address is nicku@nicku.org The notes for this class are always available at http://nicku.org/c-for-engineers/ I taught in Hong Kong for ten years I taught in Macau one year before that Before that I wrote software in C++ to collect data for medical experiments Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 3/256 How we will work in these classes C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview We will learn by doing I will explain something for a short time you will then try it out for a short time C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Next week: I will print the notes out for you, now that I know what you need I will give you more information about this course This is always available from http://nicku.org/; click on the link on the left “C for Engineers”. I will publish all the teaching material also on http://gonzo.org.au/, and I’ll explain to you how to use it Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 4/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 5/256 C — Quick tour C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output C was originally designed as a low-level systems programming language for an early version of the UNIX operating system. Combine: efficiency and hardware access capability of assembler with high level language structures and portability Redirecting Output and Input C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read Most of the Linux and UNIX operating systems are written in C. slide 6/256 C is portable C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Although C matches the capabilities of many computers, it is independent of any particular machine architecture. it is not difficult to write portable programs that can be run without change on a variety of hardware the standard makes portability issues explicit, and prescribes a set of constants that characterize the machine on which the program is run. See limits.h Redirecting Output and Input C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 7/256 C — quick tour (continued) The standard library is a suite of ready-written commonly used functions header files declare the library functions, and any symbolic constants required. The (obsolete) header file for the iostream library is included into your program file with: #include C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library Continuing our tour Data Types Expressions Statements Header files tell the compiler about the library functions and about the type of the parameters and return types linker automatically links in the required functions at compile-time. C programs make use of functions from the standard library; e.g., all input and output operations are usually performed using standard library functions. Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 8/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 9/256 Standard Input, Output If you run a program in Windows or Linux, it usually has three files already open: Name Standard Input Standard output Standard error File Descriptor 0 1 2 normally connected to keyboard screen screen C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read These are normally connected to the keyboard and your command prompt window slide 10/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 11/256 Output Redirection We redirect output using ’>’ For example: C:\STUDENT> command > output Creates the file output (or overwrites it if it already exists) and places the standard output from command into it We can append to a file rather than overwriting it by using >> normally C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers command Arrays and Pointers > output (file) with redirection Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 12/256 Input Redirection < redirects standard input from a file, e.g., C:\STUDENT> analyse < numbers.txt analyse now take the contents of the file numbers.txt as its input numbers.txt (file) C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library Continuing our tour Data Types < analyse st Expressions Statements Functions Arrays n di stdo ut Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 13/256 C++ C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library An overview of the iostream library C++ is forwards compatible with C If a C++ compiler cannot compile a C program, the C program may be poorly written We will use some basic C++ features in this course, where they make things easier One of these ways is file input and output using the iostream standard library. Another is the standard string library, but I don’t think that Borland C++ 3.1 supports it. Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 14/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library An overview of the iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 15/256 Overview of iostream library To use iostream library in programs, we must include the header file like this: #include C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library An overview of the iostream library If you are using a very old C++ compiler, put this instead: #include The library defines three standard stream objects: std::cin pronounced see-in an istream class object representing standard input Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read std::cout pronounced see-out an ostream class object representing standard output std::cerr pronounced see-err an ostream class object representing standard error slide 16/256 Input and Output operators Output is done using the left shift operator < < Input is done using the right shift operator > > #include int main( void ) { char name[ 1000 ]; std::cout < "what is your name? "; < std::cin > name; > if ( name[ 0 ] == ’\0’ ) std::cerr < "error: name is empty!\n"; < else std::cout < "hello, " < name < "!\n"; < < < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library An overview of the iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 17/256 How do I remember? C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library A way of remembering which operator is which: each operator points in the direction the data moves, e.g., >x > An overview of the iostream library Continuing our tour Data Types Expressions Statements puts data into x, while int main( void ) { std::cout < "Hello World\n"; < } Data Types Output for Program hello.cpp: Hello World Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 21/256 Good programming practice C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Indentation can improves clarity and readability. It can be enhanced by placing braces or blank lines. Use variable and function names that explain themselves Functions should be shorter than one A4 page and should be simple to understand Every long or complicated function should be preceded by a comment describing the purpose of the function. Aim: make the program as easy for a human to understand as possible Saves money: less time to change/update program = less money. C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 22/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 23/256 Format of main() function without parameters C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax int main( void ) { declarations ; statements ; } Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 24/256 Variable declarations C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Variables are declared and defined with a data type and a name. The name is also called an identifier. First character of a variable must be letter or underscore (_). Special characters (e.g., $ and #) are illegal. Some people (including me!) recommend using lowercase letters and underscores only. Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 25/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 26/256 Input characters without skipping whitespace We can input and output characters one at a time: Program one-char-io.cpp: #include int main( void ) { char letter ; std::cin > letter ; > std::cout < letter ; < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Note that by default, std::cin > letter ; will skip over > whitespace, such as spaces, tabs and newlines You can use the iostream member function std::cin.get() to input characters one at a time, including whitespace: #include int main( void ) { char letter ; std::cin.get( letter ); std::cout < letter ; < } slide 27/256 Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Data Types Three of the most commonly used data types: int double integer floating point number C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading char character Program vars.cpp: #include int main( void ) { int num = 5; float cost = 9.5; std::cout < "Hello: num = " < num < < < " cost = " < cost < < < ’\n’; < } Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 28/256 The std::endl manipulator C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour The iostream libraries support manipulators A manipulator changes the state of a stream The std::endl manipulator: prints a newline ’\n’, and sends any remaining characters stored ready for output, to the output We say that this “flushes the buffer” hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 29/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 30/256 Input and output with iostream Simple input and output operations using iostream library objects std::cout and std::cin Program celcius.cpp: #include int main( void ) { double fahr = 212, cel; cel = ( 5.0 / 9.0 ) * ( fahr − 32 ); std::cout < fahr < " deg F => " < < < cel < " deg C\n"; < < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Output of program celcius.cpp: 212 deg F => 100 deg C Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 31/256 Using std::cin for input std::cin object performs the opposite operation. reads text from standard input and assigns to variables automatically converts the input text data to appropriate types Program cin-cout-2.cpp: #include int main( void ) { int num; float cost; std::cout < "Enter number: "; < std::cin > num; > std::cout < "Enter cost: "; < std::cin > cost; > std::cout < "Num = " < num < ", cost = " < < < < cost < ’\n’; < < } slide 32/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 33/256 Strings — array of characters A string is an array of characters, i.e., text. The length of the string can be defined with a number enclosed in brackets. e.g., array of 10 characters with name lname: char lname[ 10 ]; C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Program cin-cout-3.cpp: #include int main( void ) { int num; char lname[ 1000 ]; std::cout < "Enter class number: "; < std::cin > num; > std::cout < "Enter last name: "; < std::cin > lname; > std::cout < "class number is " < num < < < ", lastname is " < lname < < < ’\n’; < } slide 34/256 Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 35/256 Loops C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview A loop will cause statements to be executed repeatedly until a test condition proves false Program while-1.cpp: C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace #include I/O of other data to standard output and from standard int main( void ) input Reading into strings { Loops Reading till the end of file int j = 0; Infinite Loop while reading while ( j < 5 ) { Data Types std::cout < "j has the value " < j < ’\n’; < < < Expressions j = j + 1; Statements } Functions } Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 36/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 37/256 End of file C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library When there is no more input, a program has reached the end of file When reading standard input: that is redirected from a file (see section 11 on page 19), the program has reached end of file when, well, the last line is read. ¤ § from the keyboard, you can type ¦ Control-Z ¥ Windows, on reached the end of file Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading § ¤ or ¦ Control-d ¥ Linux to tell your program that it has on Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 38/256 Reading till the end of file If you execute the code std::cin > name; after reaching > end of file, the result is false. That means you can write code like this: if ( std::cin > name ) { > // do something with name } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading You can also write a loop that automatically terminates when there is no more to read: float num; while ( std::cin > num ) { > // Now we know that num is a valid float, // so do something with it } Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers After this loop is finished, either we have reached end of file, or the next input is not a valid float slide 39/256 Multidimensional Arrays and arrays of pointers Structures Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 40/256 Infinite Loop while reading C Programming for Engineers Nick Urbanik Who am I? Who are You? If you do something like this: float num = 1.0; std::cout < "enter positive floats: "; < while ( num > 0 ) { std::cin > num; > std::cout < "You gave me " < num < ’\n’; < < < } Overview C++ and iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file if you enter something that is not a valid float, you get an infinite loop. Use the method I described in the last slide. See http://www.parashift.com/c++-faq-lite/ input-output.html#faq-15.2 for more about this. Infinite Loop while reading Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures slide 41/256 Data Types C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Data is represented in memory by a sequence of bits, arranged into bytes, eight bits to a byte These bits could represent strings or characters integers floating point values memory addresses binary values representing music or video ... C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Each item of data has a data type The data type determines how the program will interpret the data slide 42/256 Guidelines Declaration & data types A variable declaration consists of a data type and an identifier, followed by a semicolon: Data Type Variable Name semicolon Example: int count; Basic data types character signed character unsigned character integer unsigned integer long integer unsigned long integer long long integer unsigned long long integer short integer floating point slide 43/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants char Enumerated Types: enum signed char Expressions unsigned char Statements int Functions int Arrays Pointers long Arrays and Pointers unsigned long Multidimensional long long Arrays and arrays of pointers unsigned long long Structures short Reading and Writing float or double or long double Files Keywords Guidelines Integer and floating point data types Types of integer data (each has an unsigned counterpart): character integer short integer long integer long long integer C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Types of floating point values: single precision (float) double precision (double) long double precision (long double) Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files The range of values that can be held are machine dependent. The ranges of integer types are in limits.h The ranges of floating types are in float.h slide 44/256 Guidelines Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 45/256 Guidelines Signed integers — 1 An unsigned integer has only positive values while a signed integer can have a positive or negative value. Signed Integers: int size: range: use: standard integer system dependent, usually size of a word. INT_MIN to INT_MAX, defined in limits.h. For 4 byte word, −231 − 1 to 231 , i.e., −2147483648 to 2147483647 int num; 1000 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 46/256 Guidelines example declaration: example constant: Signed integers — 2 long size: range: use: large numbers usually 4 bytes. LONG_MIN to LONG_MAX. For 4 bytes, −231 to 231 − 1, i.e., −2147483648 to 2147483647 long lnum; 5212000L C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum example declaration: example constant: short size: range: declaration: constants: slide 47/256 Expressions Statements use: smaller numbers 2 bytes or same size as integer SHRT_MIN to SHRT_MAX. For 2 bytes, −2 to 215 − 1, i.e., −32768 to 32767 short snum; 120 15 Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines long long long long size: range: use: very large numbers usually 8 bytes. for 8 bytes, −263 to 263 − 1, i.e., −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 long long lnum; 5212000LL use: very large positive numbers usually 8 bytes. for 8 bytes, 0 to 2 − 1, i.e., 0 to 18,446,744,073,709,551,615 unsigned long long lnum; 5212000LL 64 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum example declaration: example constant: unsigned long long size: range: example declaration: example constant: slide 48/256 Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Unsigned integers — 1 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour unsigned int size: range: declaration: constants: system dependent; always same size as int 0 to UINT_MAX. For 4 byte word, 0 to 232 − 1, i.e., 4294967295 unsigned int unum; or unsigned unum; 5530u Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 49/256 Guidelines Unsigned integers — 2 unsigned long size: range: example declaration: example constant: unsigned short size: range: example declaration: example constant: slide 50/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour usually 4 bytes; always same size as long 0 to UINT_MAX. For 4 byte, 0 to 232 − 1 = 4294967295 unsigned long ulnum; 76212000uL Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions usually 2 bytes; always same size as short int 0 to USHRT_MAX. For 2 bytes, 0 to 65536 unsigned short usnum; 34000u Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 51/256 Guidelines Characters When working with characters, use the type char. Note that the type char can be signed or unsigned, depending on the compiler. char size: range: usually 8 bits; CHAR_BIT in limits.h CHAR_MIN to CHAR_MAX. For 1 byte, could be −27 to 27 − 1, i.e., −127 to 128 or 0 to 255 char ch; ’a’ C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files example declaration: example constant: slide 52/256 Guidelines Characters: signed, unsigned specify the type as signed or unsigned only if you care. C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview signed char size: range: example declaration: example constant: unsigned char size: range: example declaration: slide 53/256 C++ and iostream library Continuing our tour usually 8 bits; CHAR_BIT in limits.h SCHAR_MIN to SCHAR_MAX. For 1 byte, −27 to 27 − 1, i.e., −127 to 128 signed char ch; ’a’ Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers usually 8 bits; CHAR_BIT in limits.h 0 to UCHAR_MAX. For 1 byte, 0 to 28 − 1 = 255 unsigned char ch; Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Character types C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Characters are represented in C with integer values. The correspondence between a given character and an integer value is determined by an agreed-upon character set, such as the ASCII character set. Examples of declarations: char letter ; signed char sletter ; unsigned char uletter ; Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 54/256 Guidelines Program princhar.cpp #include int main( void { char letter int num char ch1 char ch2 ) = ’A’; = letter ; = ’b’; = ’B’; // ’A’ is character constant // ASCII code = 98 // ASCII code = 66 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types std::cout < "letter = " < letter < < < ", num = " < num < ’\n’; < < < std::cout < "letter + 1 = " < letter + 1 < < < ", num = " < num < ’\n’; < < < std::cout < ch1 < " - " < ch2 < < < < " = " < ch1 − ch2 < std::endl; < < < } Output for Program princhar.cpp: letter = A, num = 65 letter + 1 = 66, num = 65 b - B = 32 slide 55/256 Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 56/256 Guidelines Integer constants: octal and hexadecimal An integer can be represented in an octal or a hexadecimal form. Octal integer constants are represented with a leading zero. Hexadecimal integer constant is represented with the leading characters 0x, or 0X. Integer 4 12 123 Octal 04 014 0173 Hexadecimal 0x4 0xc 0x7b C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays The long integer qualifier L can also used with the octal and hexadecimal Example of octal constant: 0553000L Example of hexadecimal constant: 0x2f6c7a333L slide 57/256 Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Program printvar.cpp #include #include int main( void ) { int num = 77; short int small = 0173; short little = 0x7b; long int big = 88000; long large = −43000L; unsigned int unum = 45000; unsigned long ubig = 330000000UL; std::cout std::cout < < < < std::cout < < std::cout < < std::cout < < std::cout < < } slide 58/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum < std::showbase; < < "num (dec) = " < num < < ", (oct) = " < std::oct < num < < ", (hex) = " < std::hex < num < ’\n’; < < < < "small (oct) = " < std::oct < small < < < ", little (hex) = " < std::hex < little < ’\n’; < < < < "big (dec) = " < std::dec < big < < < ", large (dec) = " < large < ’\n’; < < < "unum = " < unum < < ", ubig = " < ubig < ’\n’; < < < "small (dec) = " < small < < ", little (dec) = " < little < std::endl; < < Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Output for Program printvar.cpp num (dec) = 77, (oct) = 0115, (hex) = 0x4d small (oct) = 0173, little (hex) = 0x7b big (dec) = 88000, large (dec) = -43000 unum = 45000, ubig = 330000000 small (dec) = 123, little (dec) = 123 We need to include iomanip here for the manipulators: std::oct Changes the state of the ostream to displaying all integer type numbers in octal. All numbers printed while in this state are in octal. std::hex Changes the state of the ostream to displaying all integer type numbers in hexadecimal std::dec Changes the state of the ostream to displaying all integer type numbers in decimal std::showbase a state that displays octal with leading “0”, hexadecimal with leading “0x” slide 59/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 60/256 Guidelines Floating point data types — 1 The floating point data type is used to represent real numbers. Real numbers include the fractional number between integers. two components: an exponent and a fraction float size: range: example declaration: example constant: system dependent, usually four bytes. FLT MIN to FLT MAX defined in float.h float fnum; 3.456f C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 61/256 Guidelines Floating point data types — float C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library double size: range: example declaration: example constants: twice the size of float, usually eight bytes DBL MIN to DBL MAX defined in float.h double dnum; floating point notation: 3.4567 exponential notation: 4.788e+5, 3e1 Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 62/256 Guidelines Floating point data types — long double C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour long double size: range: example declaration: example constants: bigger than the size of double. LDBL MIN to LDBL MAX defined in float.h long double ldnum; 3.4567L exponential notation: 4.788e+5L Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 63/256 Guidelines Program float-io.cpp #include int main( void ) { float cost = 15.92; float total = 3.6e5; float value = 357e−1; // value is 35.7 double debt = 1.2e15; long double decrease = 5e−6; std::cout < "cost = " < < cost < < ", total = " < total < ’\n’; < < < std::cout < "value = " < value < ’\n’; < < < std::cout < "debt = " < < debt < ’\n’ < < < "decrease = " < decrease < ’\n’; < < < } Output for Program float-io.cpp cost = 15.92, total = 360000 value = 35.7 debt = 1.2e+15 decrease = 5e-06 slide 64/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Program float.cpp showing limits of floating values #include <float.h> #include int main() { std::cout < < std::cout < < std::cout < < std::cout < < std::cout < < std::cout < < std::cout < < std::cout < < std::cout < < std::cout < < return 0; } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters "float min: " < FLT MIN < ’\n’; < < Floating Point Types "float max: " < FLT MAX < ’\n’; < < Named Constants Enumerated Types: enum "double min: " < DBL MIN < ’\n’; < < Expressions "double max: " < DBL MAX < ’\n’; < < Statements "long double min: " < LDBL MIN < ’\n’; < < "long double max: " < LDBL MAX < ’\n’; < < Functions "float epsilon: " < FLT EPSILON < ’\n’; < < Arrays "double epsilon: " < DBL EPSILON < ’\n’; < < Pointers "long double epsilon: " < LDBL EPSILON < ’\n’; < < Arrays and Pointers "A long double constant: " < 4.788e+5L < ’\n’; < < Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Octal, Hexadecimal Output with ostream slide 65/256 Guidelines Output for Program float.cpp C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library float min: 1.17549e-38 float max: 3.40282e+38 double min: 2.22507e-308 double max: 1.79769e+308 long double min: 3.3621e-4932 long double max: 1.18973e+4932 float epsilon: 1.19209e-07 double epsilon: 2.22045e-16 long double epsilon: 1.0842e-19 A long double constant: 478800 Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 66/256 Guidelines Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 67/256 Guidelines Symbolic constants: #define, const, and enum #define can be thought of as a global substitution command. The #define directive consists of the #define keyword, a define symbol, and a replacement text. Program define.cpp: #include #define RATE 1.5 // Note: terminated by comment or newline int main( void ) { float cost = RATE * 8.0; std::cout < "Cost = " < cost < < < ", rate = " < RATE < ’\n’; < < < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 68/256 Guidelines Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files slide 69/256 Guidelines Kconst and enum Using const is better than #define. Program const.cpp: #include int main( void ) { const float rate = 1.5; float cost = rate * 8; C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library // with “;” Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum std::cout < "cost = " < cost < < < ", rate = " < rate < ’\n’; < < < } Program enum-2.cpp: #include enum weather { clouds, rain, sunny, storm }; int main( void ) { weather today = sunny ; std::cout < clouds < ’ ’ < rain < ’ ’ < < < < < sunny < ’ ’ < storm < ’\n’; < < < < std::cout < "today: " < today < ’\n’; < < < slide 70/256 } Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Enumerated types — 2 Program enum-3.cpp: #include enum weather { clouds = 30, rain = 5, sunny = 255, storm = 1 }; enum boolean { TRUE = 1, FALSE = 0 }; int main( void ) { weather today = rain; std::cout < clouds < ’ ’ < rain < ’ ’ < < < < < sunny < ’ ’ < storm < ’\n’; < < < < std::cout < "today: " < today < ’\n’; < < < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Output of program enum-3.cpp: 30 5 255 1 slide 71/256 Guidelines Expressions Expressions define the tasks to be performed in a program do calculations perform function calls and assignment operations Arithmetic expressions perform the standard arithmetic operations. Arithmetic operator — is a symbol or a binary operator, i.e. acts upon 1 or more operands or values. Operand —- may be constant, variable, or function. C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions operator 8+x operands Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 72/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 73/256 Arithmetic operators — unary C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Unary arithmetic operators: + plus, or positive − negative −6 −( −6 ) −( 3 − 7 ) −y negative 6 positive 6 positive 4 change the sign of operand y Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 74/256 Arithmetic operators — binary Additive operators: + addition − subtraction total = 8 + 5 − 2; sum = num − 3; C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Multiplicative operators: * multiplication / division % modulo or remainder int total; total = 8 * 5; total = 23 / 4; // now total has the value 5 total = 23 % 4; // now total has the value 3 Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 75/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 76/256 Arithmetic precedence and associativity One operator may take precedence over another. When an expression is evaluated, it is broken down into a series of subexpressions, one for each operator. The order in which these subexpressions are evaluated is determined by either parentheses or precedence. Example: (2+4)*(5−3) C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions evaluates to the same as 6*2 If there are no parentheses, precedence determines the order of evaluation All operators are ranked according to their precedence. Operators with greater precedence are evaluated first. Example: 2+4*5−3 Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers evaluates to the same as: 2 + 20 − 3 slide 77/256 Multidimensional Arrays and arrays of Arithmetic Precedence and Associativity (cont’) If the operators share the same operand, the priority of one operator over the other will be determined by its associativity. Associativity describes how an operator associates its operands. Arithmetic operators associate left to right, whereas assignment operators associate right to left. Example: 2 + 10 − 5 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator evaluates the same as 12 − 5 Arithmetic if Expressions Bitwise Operators Casts Statements Functions The following table lists the precedence and assciativity of operators. slide 78/256 Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 79/256 All Operators and their Precedence I C Programming for Engineers Nick Urbanik Who am I? Who are You? Level 15L Operator −>, . [] () sizeof ++, −− ∼ ! +, − *, & () *, /, % +, − Function structure member selectors array index function call size in bytes increment, decrement bitwise NOT logical NOT unary plus, minus dereference, address-of type conversion (cast) multiply, divide, modulus arithmetic operators Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts 14R 13L 12L Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 80/256 All Operators and their Precedence II Level 11L 10L 9L 8L 7L 6L 5L 4L 3L 2R Operator <> <, > <, <=, >, >= ==, != & ^ | && || ?: = *=, /=, %= +=, −=, < <= > >=, &=, |=, ^= , Function bitwise shift relational operators equality, inequality bitwise AND bitwise XOR bitwise OR logical AND logical OR arithmetic if assignment operator compound assignment operators C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions 1L comma operator Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 81/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 82/256 Comparison Expressions Relational, equality, and logical expressions compare their operands. the result of the comparison is the integer value of either one or zero. If an operation compares successfully, the result of the expression is an integer value of 1. If an operation compares fails, the result of the expression is an integer value of 0. A relational operator compares two operands and determines whether one is greater or less than the other. < > <= >= less than greater than less than or equal greater than or equal C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 83/256 Relational expressions — 1 C Programming for Engineers Nick Urbanik Who am I? Who are You? Relational expressions can be combined with other expressions. Example: num = 3; abc = ( num < 5 ); Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence As 3 < 5, the resulting value of abc is 1. Example: num = 8; abc = 5 + ( num < 5 ); Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts As 8 > 5, the value of abc is 5 + 0 = 5. Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 84/256 Relational expressions — 2 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts The equality operators test a relationship between two operands result is 1 or 0. == equal, != not equal equality operator is a double equal sign == assignment operation is a single equals sign = e.g while ( test == 1 ) // comparison operation for equality test = 1; // assignment operation Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 85/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 86/256 Logical expressions — 1 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview The logical operators compare the truth or false of their operands. determined by whether or not it has a zero value If an expression evaluates to zero, the expression is false If an expression evaluates to a non-zero, it is true. C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts The operands of a logical operation are often relational expressions. && || ! logical AND logical OR logical NOT Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 87/256 Logical expressions — 2 Here is the truth table for the logical AND operation: expr1 T T F F non-zero non-zero 0 0 T F T F expr2 non-zero 0 non-zero 0-zero (expr1) && (expr2) T F F F 1 0 0 0 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Truth table for the logical OR operation: expr1 T T F F non-zero non-zero 0 0 T F T F expr2 non-zero 0 non-zero 0-zero (expr1) || (expr2) T T T F 1 1 1 0 Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Truth table for the logical NOT operation: expr T F non-zero 0 !(expr) F T 0 1 Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 88/256 Program countdig.cpp C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview /* Counts only the numeric characters ’0’ - ’9’ read from standard input */ #include int main( void ) { int n = 0; char c; while ( std::cin > c ) { > if ( c >= ’0’ && c <= ’9’ ) n = n + 1; } std::cout < "Count of digits = " < n < ’\n’; < < < } C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 89/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 90/256 Assignment expressions assignment operation is an expression. resulting value of the assignment expression is the value assigned to the variable in the assignment operation. assignment operation can be combined with other operators to form a complex expression: total = ( num = ( 4 + 2 ) ); C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Parentheses can be left out since assignment evaluate from right to left. total = num = 4 + 2; Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators which is identical to total = 4 + 2; num = 4 + 2; Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 91/256 Arithmetic assignment operators C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview provide a shorthand applying an arithmetic operation to a variable j += 3; is equivalent to j = j + 3; j *= 3; is equivalent to j = j * 3; C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions List of arithmetic assignment operators: += −= *= /= %= add and then assign subtract and then assign multiply and then assign divide and then assign modulo; assign remainder Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 92/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 93/256 Increment and decrement assignment operators an assignment operation in which 1 is added/subtracted to a variable and the result assigned to that variable. The increment or decrement operator can operate in two ways: Prefix places the increment or decrement operator before its operand. Postfix places the increment or decrement operator after its operand. Example: x = 32; y = ++x; C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator imply x = 32 + 1 = 33 and y = x = 33 But x = 32; y = x++; Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers imply y = x = 32 and x = 32 + 1 = 33 slide 94/256 Arrays and Pointers Multidimensional Arrays and arrays of Program plusequl.cpp C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview #include int main( void ) { int n, j, k ; k = j = n = 4; std::cout < "n = " < n < ", j = " < j < < < < < ", k = " < k < ’\n’; < < < n += j = 3; std::cout < "n = " < n < ", j = " < j < < < < < ’\n’; < } C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Output for Program plusequl.cpp: n = 4, j = 4, k = 4 n = 7, j = 3 Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 95/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 96/256 Comma operator expressions The comma operator expression is an expression that consists of a list of other expressions. The comma does not perform any operation on these expressions. they are simply evaluated sequentially as if they were a series of statements. C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Example: r = ( 3 * 5, 8.00 + 2.5, num = 5 ); Relational Expressions Logical Expressions Assignment Expressions The result is the value of the last expression in its list i.e., r = num = 5 Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts The main use of comma is in the headers of for loops: for ( i = 0, j = n; i < n; ++i, −−j ) Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 97/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 98/256 Arithmetic if Expressions C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts A conditional expression implements an if-else decision format. The conditional expression consists of three subexpressions: test expression and two alternative result expressions expression1 ? expression2 : expression3 If the test is true, the result will be the value of the second expression. If the test is false, the result will be the value of the third expression. Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 99/256 Arithmetic if expressions — 2 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence When used in an assignment operation, the arithmetic if expression works like an if-else statement. max = ( a > b ) ? a : b; equivalent to if ( a > b ) max = a; else max = b; All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 100/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 101/256 Bitwise operators — 1 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library The bitwise operations allow the programmer to manipulate specific bits. The bitwise operations can be combined with masks to turn specific bits on and off. The bitwise AND operation, &, is used to clear specific bits in an integer operand, leaving the other bits unchanged. The bitwise OR operation, |, is used to set specific bits in an integer operand, leaving the other bits unchanged Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 102/256 Bitwise operators — 2 Here is the truth table for the bitwise AND operation: bit n T T F F 1 1 0 0 bit m T F T F 1 0 1 0 m&n T F F F 1 0 0 0 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Truth table for the bitwise OR operation: bit n T T F F 1 1 0 0 bit m T F T F 1 0 1 0 m|n T T T F 1 1 1 0 Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 103/256 Bitwise operators — 3 The one’s complement operator, ∼, is a unary operator. The resulting value is set to the opposite of that of the operand’s bit. C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library bit m 0 1 ∼m 1 0 Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators The bitwise exclusive OR operator, ^, results in 1 if the corresponding two bits are different: bit m 0 0 1 1 bit m 0 1 0 1 m^n 0 1 1 0 Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 104/256 Shift Operators C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview There are two shift operators: < left shift operator < > right shift operator > useful for accessing individual parts of a bit pattern shift the bits of the left operand some number of positions to the left or right. unsigned char bits = 1; bits = bits < 1; < bits = bits < 2; < bits = bits > 3; > // // // // 0000 0000 0000 0000 0001 0010 1000 0001 C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 105/256 Right Shift Operator the right shift operator will fill negative signed numbers with ‘1’s from the left, but will shift 0 into the MSb (most significant bit) of unsigned numbers. Program shiftright-demo.cpp #include #include int main( void ) { int test numbers[ ] = { −16, 16, −1, 1 }; const int len = sizeof( test numbers ) / sizeof( test numbers[ for ( int i = 0; i < len; ++i ) { int n = test numbers[ i ]; unsigned u = n; std::cout < showbase; < std::cout < < "dec n: " < dec < n < "; n > < < < > < "\thex n: " < hex < n < "; n > 2: < < < < > < ’\n’; < std::cout < < "dec u: " < dec < u < "; u > < < < > < "\thex u: " < hex < u < "; u > 2: < < < < > < ’\n’; < } } slide 106/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence 0 ] ); Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator 2: " < ( n > 2Arithmetic if Expressions < > ) " < ( n > 2 ) Bitwise Operators < > Casts 2: " < ( u > 2 ) < > Statements " < ( u > 2 ) Functions < > Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of Right Shift Operator: example output output of program shiftright-demo.cpp (folded to fit): dec n: -16; n >> 2: -4 hex n: 0xfffffff0; n >> 2: 0xfffffffc dec u: 4294967280; u >> 2: 1073741820 hex u: 0xfffffff0; u >> 2: 0x3ffffffc dec n: 16; n >> 2: 4 hex n: 0x10; n >> 2: 0x4 dec u: 16; u >> 2: 4 hex u: 0x10; u >> 2: 0x4 dec n: -1; n >> 2: -1 hex n: 0xffffffff; n >> 2: 0xffffffff dec u: 4294967295; u >> 2: 1073741823 hex u: 0xffffffff; u >> 2: 0x3fffffff dec n: 1; n >> 2: 0 hex n: 0x1; n >> 2: 0 dec u: 1; u >> 2: 0 hex u: 0x1; u >> 2: 0 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Notice that when shifted right: unsigned values have the upper two bits zero so the unsigned value 0xfffffff0 shifted right by two is 0x3ffffffc Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of signed values have the upper two bits the same as the previous value of the MSb (most significant bit) so the signed value 0xfffffff0 (−16) shifted right two places is 0xfffffffc slide 107/256 Use of bitwise operators Use the AND operator ‘&’ to clear individual bits, leaving the others unchanged For example, x = x & 0xf; will clear all but the least significant four bits of x C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Use the OR operator ‘|’ to set individual bits, leaving the others unchanged For example, y = y | ˜0xf ; will set all bits except for the least significant four bits of y Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Use the Exlusive OR operator ‘^’ to toggle (flip) individual bits, leaving the others unchanged For example, z = z ^ 0xf; will toggle the least significant four bits of z, i.e., make 1s ↔ 0s slide 108/256 Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 109/256 Cast expressions The cast operation returns the value of an expression, converting it to the type in the brackets Example: C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour ( float ) 7 This converts the integer 7 to a floating point value, 7.00. The operand may be any expression Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Examples: ( int ) ( 5.8 * 2.7 ) ( double ) ( k = 10 ) ( float ) num If a floating point value is cast to an integer, the floating point fraction is lost. Arithmetic if Expressions Bitwise Operators Casts Example: ( int ) 3.75 resulting value is 3 Casts overide the compiler’s concept of correctness — use rarely slide 110/256 Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of Conversions C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Expressions can include operands of different number types Example: An integer can be multiplied by a float. C handled operands of different types by converting one of them into the same type as that of the other operand. Conversion determines which operand to convert by a process of promotion and demotion. Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 111/256 Conversions: promotion C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview In expressions with two different types of operands, the operand with the smaller type is always promoted to that of the largest type. Example: int num = 6; float cost; cost = num * 5; C++ and iostream library Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators The expression num * 5 results in the integer 30 and will be promoted to a float, 30.0 before assigned into the cost variable. Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 112/256 Conversions: demotion C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Demotion from a floating point type to an integer type results in the loss of the floating point’s fraction. Example: int num; float cost = 62.65; num = cost; Continuing our tour Data Types Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions The fraction will be cut off, leaving just the integer, 62. The value 62 is then assigned to the variable num. Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of slide 113/256 Statements: an introduction C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour A C program is a sequence of declarations and statements. We have seen: how to declare variables, and how to create expressions using operators examples of putting this all together. Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Now let’s look at statements. Functions Arrays Pointers Arrays and Pointers slide 114/256 Multidimensional Statements: intro — 2 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview We can turn an expression such as x = 0 or std::cout < "a" into a statement simply by putting a < semicolon at the end: x = 0; std::cout < "a"; < C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope We can join these into a compound statement by putting braces { } around them. There are some which are used to create loops and make decisions. These are sometimes called control-flow statements. Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 115/256 Multidimensional Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 116/256 Multidimensional Expression statements An expression statement consists of any valid expression, followed by a semicolon. Often the expression is an assignment operation or a function call. Example: count = 8; num = 3 + 4; calc(); C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement However, the expression could just as easily be an arithmetic expression or relational expression. Example: 4 + 5; // nothing done with the result, 9. ( n < 3 ); Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 117/256 Multidimensional Null statement (empty statement) C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour If there is no expression in the expression statement, nothing happens. This is called as the null statement. Example: Data Types Expressions Statements Simple Statements Compound Statements Scope ; // just a semicolon Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 118/256 Multidimensional Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 119/256 Multidimensional Compound Statements C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview A compound statement is a statement composed of one or more statements. A compound statement consists of opening and closing braces within which statements are placed. Example: { num = 6; fact = ( 5 − 3 ); std::cout < fact < ", " < num < ’\n’; < < < < } C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 120/256 Multidimensional Blocks — 1 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Variables can be declared at the beginning of compound statement. A compound statement with variable declarations is referred to as a block. The body of a function is a compound statement itself, and is often referred to as the function block. Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 121/256 Multidimensional Program blocks.cpp #include int main( void ) { int num = 10; float cost = 100.0; { float cost = 50.0; num = 5; std::cout < "Inside: " < cost < < < ", " < num < ’\n’; < < < } std::cout < "Outside: " < cost < < < ", " < num < ’\n’; < < < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Output of program blocks.cpp: Inside: 50, 5 Outside: 100, 5 slide 122/256 Functions Arrays Pointers Arrays and Pointers Multidimensional Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 123/256 Multidimensional Scope A new scope is created in each block the compiler searches for an identifier defined in the innermost scope first then searches the scopes that the enclose current scope. . . . . . until it reaches global scope global scope is outside of any block C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto identifiers defined in an inner scope “hide” identifiers defined in an outer scope For example, in program blocks.cpp, there are two variables called cost in different nested scopes The inner output statement prints the value of the cost variable defined in the inner scope The outer output statement prints the cost defined in the outer scope. Functions Arrays Pointers Arrays and Pointers slide 124/256 Multidimensional Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 125/256 Multidimensional Iteration statements C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Loops are implemented with three iteration statements: while do for Each statement repeats a statement called the body of the loop The body of the loop can be any statement, including: compound statement, or another loop, or a null statement. Functions Arrays Pointers Arrays and Pointers slide 126/256 Multidimensional Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 127/256 Multidimensional while statement while loop consists of the keyword while, a test expression in parentheses, and a statement. statement is repeated for as long as the test expression evaluates to a non-zero value. while ( test expression ) statement ; Example: i = 0; // initialize the loop counter while ( i < 5 ) { std::cout < "ABC "; < ++i; // update the loop counter // very important } // the loop becomes infinite // without this statement that // changes the loop counter C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 128/256 Multidimensional Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 129/256 Multidimensional Iteration Statements — do loop C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements The do statement is a variation on the while statement. Instead of the test occurring at the beginning of the loop, it occurs at the end, Example: i = 0; do { std::cout < "abc\n"; < ++i; // loop counter } while ( i < 4 ); Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 130/256 Multidimensional Program square-1.cpp #include int main( void ) { int num; std::cout < "Enter a number: "; < std::cin > num; > while ( num != 0 ) { int square = num * num; std::cout < "Square of " < num < < < " = " < square < ’\n’; < < < std::cout < "Enter a number (0 to quit): "; < std::cin > num; > } } This program has a major problem. What happens if we input a character that is not part of an integer? slide 131/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers Multidimensional Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 132/256 Multidimensional Test Expression C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library The test expression for the while, for, and if statements can be any valid expression, Example: assignment operation simple primary expression consisting of a variable or a constant Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement A zero result evaluated is considered to be false while any non-zero result is true. Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 133/256 Multidimensional Traps with = and == Don’t confuse comparison with assignment in a test expression. while ( i = k ) { ... } If k equals 0, the test will always be false If k is not equal to zero, the test will always be true. Examples of incorrect test expressions: while ( n = 0 ) { /* always false */ ... } while ( n = 3 ) { /* always true, an infinite loop */ ... } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements The correct way to write these test expressions is: while ( n == 0 ) { ... } while ( n == 3 ) { ... } slide 134/256 break, continue, goto Functions Arrays Pointers Arrays and Pointers Multidimensional Program quit-1.cpp #include /* This program shows problems that come from confusing assignment with comparison */ int main( void ) { int quit = 0, num = 1, square; while ( quit = 0 ) // Oh dear; always false { // the loop body will never be executed square = num * num; std::cout < "Square of " < num < < < " = " < square < ’\n’; < < < if ( num = 10 ) // Oh dear; always true quit = 1; num++; } } slide 135/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers Multidimensional Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 136/256 Multidimensional Using a constant or single variable as a test condition C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Constants are often used to write infinite loops. Variables are used as a shorthand for comparing the value of the variable to zero. Example: while ( 1 ) while ( 0 ) while ( i ) // infinite loop // never execute loop // is equivalent to // while ( i != 0 ) Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 137/256 Multidimensional Program square-2.cpp #include int main( void ) { int num; while ( 1 ) { // or for (;;) std::cout < "Please enter a number: "; < if ( ! ( std::cin > num ) ) > break; int square = num * num; std::cout < "Square of " < num < < < " = " < square < ’\n’; < < < char ch; std::cout < "Another square? (y/n) "; < if ( std::cin > ch && ch != ’y’ ) > break; } } slide 138/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers Multidimensional Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 139/256 Multidimensional while test and null statement A while statement can be written in which the test expression does all the work. The statement following the test expression is simply a null statement. Example: while ( std::cin.get( ch ) && ch != ’\n’ ) ; // do nothing C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Three actions take place in the above example: function call to the istream member function get() std::cin.get( ch ) will return false if reach end of input file; inequality operation in which character value obtained by std::cin.get() is tested against a newline constant. Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto End result is that we wait till we get a newline character, or end of file Functions Arrays Pointers Arrays and Pointers slide 140/256 Multidimensional Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 141/256 Multidimensional The for Statement C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview The for statement consists of three expressions followed by a statement. for ( expression 1 ; expression 2 ; expression 3 ) statement ; expression 1 is executed once, before loop begins. It is often used to initialize variables used in the test expression. expression 2 is the test expression for the loop. When it evaluates as false, the loop stops. expression 3 update expression. It is executed within the loop and is usually used to update variables used in the test expression. C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 142/256 Multidimensional Example of for loop C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions for ( int i = 1; i < 3; ++i ) { std::cout < "OK\n"; < } Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 143/256 Multidimensional Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 144/256 Multidimensional for and while: a comparison C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview for loop: for ( } init ; test ; update body of loop while loop: init ; while ( C++ and iostream library Continuing our tour ){ test ) { body of loop update ; Data Types Expressions Statements Simple Statements Compound Statements Scope } example: for ( int i = 0; i < 3; ++i ) std::cout < "loop " < i < < < ’\n’; < example: int i = 0; while ( i < 3 ) { std::cout < "loop " < i < < < ’\n’; < ++i; } Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 145/256 Multidimensional Nested loops — loop within a loop The inner loop executes fully within each iteration of the outer loop Example: for ( int k = 0, i = 0; i < 3; ++i ) { for ( int j = 0; j < 3; ++j ) { ++k ; std::cout < k < ’ ’; < < } std::cout < ’\n’; < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition See example program nested-for.cpp Output: 123 456 789 slide 146/256 while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers Multidimensional Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 147/256 Multidimensional Conditions: if statement C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library The if and switch statements are decision making structures that determine which statements are to be executed and which are not. if is a condition placed on a statement’s execution. if the condition is true, the statement is executed if the condition is false, the statement is not executed Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement if ( test expression ) statement ; Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 148/256 Multidimensional if and else C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview The if statement can choose between several choices using else: if ( condition ) { doThis(); } else if ( condition 2 ) { doThat(); } else { doTheOther(); } Only one action is performed the first that matches is done. C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 149/256 Multidimensional The switch statement — 1 The switch statement provides a convenient way to choose among several alternatives. It is a conditional statement (selection) switch ( integer expression case integer : statements ; break; case integer : statements ; break; default: statements ; break; } ){ C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 150/256 Multidimensional The switch statement — 2 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types The switch compares an integer value against a set of integer constants. The execution will continue unless a break is encountered. Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 151/256 Multidimensional Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 152/256 Multidimensional The jump Statements C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview The jump statements are non-structured control statements that allow the program to jump across statements. Strickly speaking, these are not allowed in structured programming. However, break and continue are especially useful. break and continue statements are used with while, for, and switch statements. break provides an exit condition other than that of the statement’s test expression. C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 153/256 Multidimensional Example of use of continue C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Kernighan and Ritchie provide this example of using continue: for ( i = 0; i < n; ++n ) { if ( a[ i ] < 0 ) // skip negative elements continue; // do positive elements } Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition See also my example program cat.cpp while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Arrays Pointers Arrays and Pointers slide 154/256 Multidimensional goto: use it seldom C Programming for Engineers Nick Urbanik Who am I? Who are You? goto and label statements allow the program to jump to any statement. Using goto can cause the program to become very hard to understand Use it only when you really have to An example is to break out of a nested loop from the inner loop for ( i = small; i < big; ++i ) for ( j = small2; j < bigger ; ++j ) if ( i == j ) goto equal; equal: Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto equal here is a label Functions Arrays Pointers Arrays and Pointers slide 155/256 Multidimensional Functions — 1 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview A big program may be too complex to hold in your head. I need a way to break a big problem into many small, easy-to-understand problems. One way to break a problem into small problems is to divide a problem into small parts that can be written as functions. A function is a number of statements that: Perform one easily-understood job are given a single name. C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read A function is a little bit like a simple IC, with input pins and output pins. slide 156/256 Functions — 2 C Programming for Engineers Nick Urbanik Who am I? Who are You? A function may have inputs and outputs: x sin() y Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions The function call: y = sin( x ); Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays can be represented by the block diagram above. The inputs go in the parentheses: () The output of the function can be assigned, as above. Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 157/256 Functions — 3 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour To write and use functions in your program, there are two things to consider: When you define the function, you write the statements that the function will perform when it is called. When you want to use the function, we say we call the function. Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 158/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 159/256 Function definition A function definition consists of a header and a body. header contains the function name, its return type, and parameter types. The body of a function is a block, which usually contains variable declarations and statements. return type function_name ( parameter list ) { variable definitions ; . . . statements ; } Example: void calc( void ) { int num; num = 5; } slide 160/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 161/256 Function definition and call Program nowincal.cpp C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview // Program to call a function #include // function definition: void calc( void ) { std::cout < "Now in Calc\n"; < } int main( void ) { std::cout < "Hello World\n"; < calc(); std::cout < "Now in Main\n"; < } C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 162/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 163/256 Functions as expressions A function call is an expression whose value is the function’s return value. Program calc-2.cpp #include float calc( void ) { return 8.0 * 5.35; } int main( void ) { float res1 = calc(); float res2 = 7 + 5 * calc(); if ( calc() > 5 ) std::cout < "Larger\n"; < std::cout < "res1 = " < res1 < < < ", res2 = " < res2 < ’\n’; < < < } slide 164/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read return statement and function return value C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library The return statement consists of the keyword return, an expression, and a semicolon. Syntax: return expression ; The expression is called the return expression. return statement will: end the processing of a function make execution continue from where the function was called, and specify the function’s return value. Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 165/256 Function return value: example Program calc-3.cpp C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters #include // Example of a function that takes // parameters float calc( int num, float calc rate ) { return calc rate * num; } int main( void ) { float rate = 2.0; float res = calc( 5, rate ); std::cout < "res = " < res < ’\n’; < < < } Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 166/256 Return inconsistencies C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Return value inconsistencies: occur when the return expression has a type different from the function’s return type. The return expression is what comes between the keyword return and the semicolon. The return type is what is written before the name of the function in a function definition. Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 167/256 Program retbad-1.cpp #include short getnum( void ) { long num = 2147483647L; std::cout < "Number is " < num < ’\n’; < < < return num; } int main( void ) { long res = getnum(); // return value inconsistency std::cout < "result is " < res < ’\n’; < < < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Output for program retbad-1.cpp: Number is 2147483647 result is -1 slide 168/256 Reading and Writing Files Guidelines Some Things to Read Program retbad-2.c #include calc( void ) { /* return type missing */ /* gives return type inconsistency */ /* legal in C */ /* Illegal in C++, won’t compile */ float cost = 8.0 * 5.35; return cost; C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters } int main( void ) { float res1; res1 = calc(); printf ( "%f\n", res1 ); } Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Output from program retbad-2.c: 42.000000 slide 169/256 Reading and Writing Files Guidelines Some Things to Read Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 170/256 Function parameters C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Functions may have zero or more parameters. Parameters are usually the inputs to the function. Parameters appear in the parentheses after the name of the function, both in the function definition and in the function call. The type and number of parameters must match in: function definition, and function call. Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 171/256 Function parameters — 2 In this example the parameters match Program funcmult.cpp #include float mult( int a, float b ) { return a * b; } int main( void ) { int x = 3; float y = mult( x, 4.5 ); // function call std::cout < "y = " < y < ’\n’; < < < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 172/256 Function parameters — 3 In the function definition of mult(): float mult( int a, float b ) { return a * b; } the first parameter is called a. the second parameter is called b. C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters In the function call, float y = mult( x, 4.5 ); // function call the value of x is copied to a, the value 4.5 is copied into b. The type of the parameter in the function call matches the type of the parameter in the same position in the function definition. This is like pins on an IC plugging into the holes in the IC socket. Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 173/256 Arrays C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview An array is a collection of objects, all of the same data type. Any one data type can be used in an array. an array of integers an arrary of characters an array of structures an array of pointers C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Defining Arrays Arrays and Loops Strings The declaration of an array reserves memory, which is then managed by pointers (to be discussed in next section). Array objects themselves are actually referenced through pointer indirection. Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 174/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Defining Arrays Arrays and Loops Strings Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 175/256 Array declaration C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types An array declaration consists of 4 parts the data type array name, square brackets around the. . . . . . number of objects in the array Expressions Statements Functions Arrays Defining Arrays Arrays and Loops Strings Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 176/256 Arrays — 2 C Programming for Engineers Nick Urbanik Who am I? Who are You? The declaration below declares an array of 5 integers. The array name is mynums int mynums[ 5 ]; Overview C++ and iostream library Continuing our tour Data Types Expressions Many different kinds of arrays may be declared, each having its own data type and number objects. int total[10]; an array of ten integers (i.e. total[0], total[1], . . . total[9]) an array of forty characters (i.e. name[0], name[1], . . . name[39]) Statements Functions Arrays Defining Arrays Arrays and Loops Strings Pointers Arrays and Pointers char name[40]; Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 177/256 Array initialisation C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview When a variable is defined it can be initialised with a value. In the declaration: char mychar = ’E’; C++ and iostream library Continuing our tour Data Types Expressions Statements the variable mychar is initialised with the character ’E’. The elements of an array can also be initialised in an array declaration. The initalisation values are listed within curly braces and separated by commas: int mynums[ 5 ] = { 3, 4, 5, 6, 7, }; Functions Arrays Defining Arrays Arrays and Loops Strings Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 178/256 Array Length When using standard C, the initialization part of the array declaration can be used be left out of the array declarations. The number is, instead, determined by the number of values in the initialisation block. Program array-1.cpp #include int main( void ) { char letters[ ] = { ’A’, ’B’, ’C’, }; int totals[ ] = { 23, 8, 11, 31, }; std::cout < letters[ 1 ] < ’ ’; < < std::cout < totals[ 3 ] < ’\n’; < < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Defining Arrays Arrays and Loops Strings Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 179/256 Array references and array notation Once an array has been declared, its objects can be referenced and used in expressions. The array name, together with the position of an object in the array is used to reference an object. The objects in an array are arranged in sequence, starting from zero. The number of an object’s place in that sequence is referred to as either the object’s index or subscript. In the example above, we can see mynums[ mynums[ mynums[ mynums[ mynums[ 0 1 2 3 4 ] ] ] ] ] = = = = = 3; 4; 5; 6; 7; // // // // // first object second object third object fourth object fifth object C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Defining Arrays Arrays and Loops Strings Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 180/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Defining Arrays Arrays and Loops Strings Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 181/256 Array management and loops Operations cannot be performed on an array as a whole. To assign a set of values to an array, you need to assign a value to each element individually. An array is only a collection of objects. It is not an object itself. We use loops to process all these objects. Program arrayprt.cpp #include int main( void ) { int nums[ ] = { 23, 8, 11, 31 }; for ( int i = 0; i < 4; ++i ) { std::cout < nums[ i ] < ’ ’; < < } std::cout < ’\n’; < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Defining Arrays Arrays and Loops Strings Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 182/256 Array Management and Loops — 2 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library A common rule of thumb is that the test for the end of an array is the less than operator, <, tested against the number of objects declared in the array. Example: this for loop prints each number in the array: int nums[ 4 ] = { 42, 1000, 7, 103 }; for ( int i = 0; i < 4; ++i ) std::cout < "this num is " < nums[ i ] < ’\n’; < < < Continuing our tour Data Types Expressions Statements Functions Arrays Defining Arrays Arrays and Loops Strings Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 183/256 Using constants for array size C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview In the listing below, the same symbolic constant, max, is used in both the array declaration and the test for the last array object in the for statement. #include const int max = 4; int main( void ) { int mynums[ max ] = { 23, 8, 11, 31 }; for ( int i = 0; i < max; ++i ) std::cout < mynums[ i ] < ’ ’; < < std::cout < ’\n’; < } C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Defining Arrays Arrays and Loops Strings Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 184/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Defining Arrays Arrays and Loops Strings Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 185/256 Arrays of characters: strings A string is an array of characters. Here are examples of definitions of strings: char name[ 20 ]; char string[ ] = "This is a string"; char str [ 10 ] = "string"; char letters[ 10 ] = { ’s’, ’t’, ’r’, ’i’, ’n’, ’g’, ’\0’ }; C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Defining Arrays Arrays and Loops Strings Note that the string definitions str and letters are equivalent. Note that a string is automatically ended with a special character called the null character, ’\0’ Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 186/256 Arrays of characters: strings — 2 Because the string has the extra ’\0’ character at the end, the array of characters must be long enough to hold it. Example: char string2[ ] = "string"; C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Defining Arrays Arrays and Loops Strings . . . has seven characters, so this would be wrong: char string3[ 6 ] = "string"; // too short! Pointers but these are okay: char string4[ 7 ] = "string"; char string5[ 100 ] = "string"; Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 187/256 Careful: strings cf. characters A common mistake is to confuse a string with a character. Example: char c; // Wrong! c = "A"; A character has single quotes: ’A’ C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions The string "A" is actually two characters: ’A’ then ’\0’. One final note: do not assign strings! char str [ 100 ]; str = "this is a string"; /* Oh no, a mistake! Use strcpy () library function instead. */ strcpy ( str, "this is a string" ); // OK Arrays Defining Arrays Arrays and Loops Strings Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 188/256 Working with strings The standard C++ strings library is the best choice for simplicity, but the Borland 3.1 compiler does not seem to support it The standard library that comes with (nearly) every C compiler provides lots of functions for working with strings. To use them, put: #include C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Defining Arrays Arrays and Loops at the top of your program. Here are some: strlen() — give the length of a string strcpy () — copy one string to another string strcmp() — compare two strings strcat() — join one string onto the end of another Strings Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 189/256 Working with strings 2 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Example using strlen(): int len; len = strlen( "a string" ); // len = 8 Continuing our tour Data Types Expressions Statements Functions Example using strcpy (): char str1[ 100 ], str2[ ] = "a string"; strcpy ( str1, str2 ); Arrays Defining Arrays Arrays and Loops Strings Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 190/256 Pointers C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Pointers as Function Parameters Any object defined in a program can be referenced through its address. A pointer is a variable that has as its value the address of an object. A pointer is used as a referencing mechanism. A pointer provides a way to reference an object using that object’s address. There are 3 elements involved in this referencing process: a pointer variable an address and another variable Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 191/256 Pointer holds address A pointer variable holds the address of another variable of a particular type Program pointer-1.cpp #include int main( void ) { int num = 12; int *nptr ; nptr = # std::cout < "num holds " < num < < < " and nptr points to " < *nptr < ’\n’; < < < std::cout < "The address held in nptr is " < nptr < < < ’\n’; < } Output of program pointer-1.cpp: num holds 12 and nptr points to 12 The address held in nptr is 0xbfafade8 slide 192/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Pointers as Function Parameters Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Pointers as Function Parameters Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 193/256 Pointers as Function Parameters If you try to write a function to swap its parameters like this: void swap( int x, int y ) { int temp = x; x = y; y = temp; } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements and call it like this: swap( a, b );, the values of a and b are copied by value, so the final values are not changed. The right way is to pass the address of a and b like this: swap( &a, &b ); and define the function like this: void swap( int *x, int *y ) { int temp = *x; *x = *y ; *y = temp; } Functions Arrays Pointers Pointers as Function Parameters Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read This is how to change the value of a parameter. slide 194/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 195/256 C Arrays are very low level Pointers and arrays have a strong relationship Any operation using array subscripting can be done using pointers If we define an array of integers and a pointer to an integer like this: int a[ 10 ]; int *pa; C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Strong relationship between arrays and pointers and if we make pa point to the start of the array a[ ] like this: pa = &a[ 0 ]; then the value of *pa is the same as is stored in a[ 0 ]. The pointer pa + 1 points to the value of a[ 1 ], so this statement is true: *( pa + 1 ) == a[ 1 ] If we add ‘1’ to a pointer, we point to the address just after the value stored at that pointer. If sizeof( int ) is 4, and if addresses each hold one character, then the address pa + 1 is 4 address locations higher than the address pa. The type of the pointer determines what address you get when you increment a pointer. Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read similarly *( pa + i ) == a[ i ] is true. slide 196/256 C Arrays and pointers The name of an array is the same as the location of the first element, so these two statements are equivalent: pa = &a[ 0 ]; pa = a; C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour These statements are also true: a[ i ] == *( a + i ); &a[ i ] == a + i; Data Types Expressions Statements Functions An expression made of an array and index has an equivalent expression made with a pointer and offset. Important: we can do ++pa; // okay; now pa points to a[ 1 ] Arrays Pointers Arrays and Pointers Strong relationship between arrays and pointers . . . but not: ++a; // compiler error Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read . . . because an array name is a constant, but an ordinary pointer is not. slide 197/256 Passing arrays to functions C Programming for Engineers Nick Urbanik Who am I? Who are You? If a parameter is an array name, inside the function it is a pointer to the first element of the array If you find the size of an array with sizeof, you are given the number of elements × the size of one element Inside a function, the size of an array parameter is the size of a pointer. See program array-parameter.cpp. Note that the sizeof operator gives the number of characters in either a type or an expression: sizeof( T ) gives the number of characters in the type T sizeof expression gives the number of characters in the expression expression. Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 198/256 Program array-parameter.cpp #include int ar [ 10 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; void check array parameter ( int a[ ] ) { std::cout < "sizeof( a ) = " < sizeof( a ) < ’\n’; < < < std::cout < "sizeof( ar ) = " < sizeof( ar ) < ’\n’; < < < } int main( void ) { check array parameter ( ar ); int nelements = sizeof( ar ) / sizeof ar [ 0 ]; std::cout < "sizeof( ar ) = " < sizeof( ar ) < ’\n’ < < < < "number of elements in ar[ ] is " < nelements < < < ’\n’; < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read Output of array-parameter.cpp sizeof( a ) = 4 sizeof( ar ) = 40 sizeof( ar ) = 40 number of elements in ar[] is 10 slide 199/256 Passing arrays to functions — 3 To work properly, you need to pass the length of an array as a separate parameter together with the array. Example: double mean( int nums[ ], int len ) { int sum = 0; for ( int i = 0; i < len; ++i ) { sum += nums[ i ]; } if ( len == 0 ) return 0; return ( double ) sum / len; } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Strong relationship between arrays and pointers Note that it makes no difference to write the parameter as int nums[ 100 ], since that length information will not be passed to the function as part of the int nums[ 100 ] parameter If the length of the array passed to mean() is 100, then that number must be passed as a separate parameter. slide 200/256 Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Reading and Writing Files Guidelines Some Things to Read slide 201/256 Arrays of pointers C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Arrays of pointers are very commonly used in C, because this gives much greater flexibility than alternatives (see slide §216) Can easily sort an array of pointers; copy only the address, not the data Can define an array of pointers to lines like this: const int maxlines 10000; char *line[ maxlines ]; C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv We must make sure that we allocate memory using the new operator for this as we read lines. Structures Reading and Writing Files Guidelines Some Things to Read slide 202/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Reading and Writing Files Guidelines Some Things to Read slide 203/256 Allocating memory with new If we don’t know how much data we will read, we need to allocate memory as we need it The new operator allocates memory as it is needed deallocate (free) memory with the delete operator C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv If allocating a scalar value, use syntax like this: pointer = new type ; and free the memory like this: delete pointer ; if allocating an array or string, use syntax like this: pointer = new type [ length ]; and free the memory like this: delete [] pointer ; the result from new is a null pointer if the memory cannot be allocated. Always check the return value of new Structures Reading and Writing Files Guidelines Some Things to Read slide 204/256 Example use of new: Program new-1.cpp Program new-1.cpp does the following: dynamically allocate an array of ten integers terminate if allocation doesn’t succeed put a value into each element of the array print each value free up the memory #include #include int main( void ) { const int maxn = 10; int *a = new int[ maxn ]; if ( a == NULL ) { std::cerr < "Out of memory!\n"; < exit( 1 ); } for ( int i = 0; i < maxn; ++i ) a[ i ] = i + 1; for ( int i = 0; i < maxn; ++i ) std::cout < "a[ " < i < " ] = " < < < < a[ i ] < ’\n’; < < delete [ ] a; } slide 205/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Reading and Writing Files Guidelines Some Things to Read Program new.cpp — 1 #include #include // Read all of input into memory. // at a time, as we read it. Normally we would process one line C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv // Read each line into a string // allocate memory for the string and copy the string into that memory // add the newly allocated string to an array of pointers int read lines( char *lines[ ], int maxnlines ) { const int maxlinelen = 8000; char line[ maxlinelen ]; int nlines = 0; while ( std::cin.getline( line, maxlinelen ) ) { int len = std::cin.gcount(); // includes space for ’\0’ char *p; if ( nlines >= maxnlines | | ( p = new char[ len ] ) == NULL ) { return −1; } else { strcpy ( p, line ); lines[ nlines++ ] = p; } } return nlines; } slide 206/256 Structures Reading and Writing Files Guidelines Some Things to Read Program new.cpp — 2 void write lines( char *lines[ ], int nlines ) { while ( nlines−− > 0 ) std::cout < *lines++ < ’\n’; < < } void free lines( char *lines[ ], int nlines ) { while ( nlines−− > 0 ) delete [ ] *lines++; } int main( void ) { const int maxlines = 10000; char *line[ maxlines ]; int nlines = read lines( line, maxlines ); if ( nlines >= 0 ) { write lines( line, nlines ); free lines( line, nlines ); } else { std::cerr < "Input is too big to read\n"; < } } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Reading and Writing Files Guidelines Some Things to Read slide 207/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Reading and Writing Files Guidelines Some Things to Read slide 208/256 Multidimensional Arrays Not used as much as arrays of pointers Usually we allocate memory with new for each string int matrix[ 2 ][ 4 ] = { { 1, 2, 3, 4 }, { 10, 20, 30, 40 } }; C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions defines a rectangular matrix. We can access the entry with the value 30 with int entry = matrix[ 1 ][ 2 ]; Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Note that this is wrong, and just uses the comma operator: int entry = matrix[ 1, 2 ]; // WRONG!!! % Structures Reading and Writing Files Guidelines Some Things to Read slide 209/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Reading and Writing Files Guidelines Some Things to Read slide 210/256 argc and argv The main() function takes two optional parameters that are always called argc and argv : int main( int argc, char *argv [ ] ) C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions parameter argc is the number of arguments on the command line including the program name parameter argv is a pointer to an array of command line arguments if the program echo is called like this: echo this is a test then argc is 5, argv [ 0 ] is "echo", argv [ 1 ] is "this", argv [ 2 ] is "is", argv [ 3 ] is "a", argv [ 4 ] is "test" and finally argv [ 5 ] is the null pointer. Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Reading and Writing Files Guidelines Some Things to Read slide 211/256 Program echo.cpp C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview The program echo.cpp: #include int main( int argc, char *argv [ ] ) { for ( int i = 1; i < argc; ++i ) std::cout < argv [ i ] < ’ ’; < < std::cout < ’\n’; < } C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv prints its parameters, like the echo command in the Windows CMD.EXE shell, or like the echo command built into the bash shell that is popular with Linux. Structures Reading and Writing Files Guidelines Some Things to Read slide 212/256 Structures — 1 A structure consists of a set of data objects that can be referenced as one object. struct tag name { list of declarations }; A tag can be used to label a structure type declaration. In the structure type declaration, the keyword struct may be followed with a tag placed before the opening brace of the declaration list, Example: struct employee { int id; float salary ; }; C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Passing Structures to Functions typedef Reading and Writing Files Guidelines Some Things to Read slide 213/256 Defining struct variables C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview We can define a variable person of the type struct employee like this: struct employee { int id; float salary ; }; // somewhere else: struct employee person; C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Passing Structures to Functions typedef We can now refer to the two values in the variable person as person.id and person.salary Reading and Writing Files Guidelines Some Things to Read slide 214/256 Initialising struct variables C Programming for Engineers Nick Urbanik Who am I? Who are You? We can initialise a structure when it is defined by putting a list of values in braces, as we do for arrays The first item in that list initialises the first element of the structure, the second item initialises the second element of the structure, ... We could initialise our struct employee like this: struct employee person = { 8, 80000 }; Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures After this, person will contain the same values as in the next slide. Passing Structures to Functions typedef Reading and Writing Files Guidelines Some Things to Read slide 215/256 Structures: Program struct.cpp C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Passing Structures to Functions typedef #include int main( void ) { struct employee { int id; float salary ; }; struct employee person; person.id = 8; person.salary = 80000; std::cout < "ID = " < person.id < ’\n’; < < < std::cout < "Salary = $" < person.salary < ’\n’; < < < } Reading and Writing Files Guidelines Some Things to Read slide 216/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Passing Structures to Functions typedef Reading and Writing Files Guidelines Some Things to Read slide 217/256 Accessing a structure through a pointer Given a pointer to a struct declared as: struct employee { int id; float salary ; }; struct employee person; struct employee *p = &person; C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements we could access the members with the arrow operator ‘−>’ like this: p−>id = 8; p−>salary = 80000; std::cout < "ID = " < p−>id < ’\n’; < < < std::cout < "Salary = $" < p−>salary < ’\n’; < < < Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Passing Structures to Functions typedef There is nothing magic about the “−>” operator; it is just a shorthand used, because we often access members of structures through pointers Note that “p−>id” is equivalent to “(*p).id”, and “p−>salary ” is equivalent to “(*p).salary ”. slide 218/256 Reading and Writing Files Guidelines Some Things to Read Passing Structures to Functions C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Unlike arrays, structures are passed to functions by value That means that your function only gets a copy of the structure. If you want to modify the original structure, you need to either: return the modified structure, or pass a pointer to the structure. Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Passing Structures to Functions typedef Reading and Writing Files Guidelines Some Things to Read slide 219/256 Passing Structures: example Here we use the struct employee defined previously. Passing structure by value struct employee raise salary ( struct employee p, float raise ) { p.salary += raise; return p; } // in another function: struct employee manager = { 50, 100000 }; manager = raise salary ( manager, 20000 ); C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Passing a pointer to structure: void raise salary ( struct employee *p, float raise ) { p−>salary += raise; } // in another function: struct employee manager = { 50, 100000 }; raise salary ( &manager, 20000 ); slide 220/256 Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Passing Structures to Functions typedef Reading and Writing Files Guidelines Some Things to Read Structures: Program complex.cpp #include struct complex { int re; int im; }; complex cadd( complex z1, complex z2 ) { complex zt; zt.re = z1.re + z2.re; zt.im = z1.im + z2.im; return zt; } int main( void ) { complex za; za.re = 1; za.im = 2; complex zb = za; complex zc = cadd( za, zb ); std::cout < "zc.re = " < zc.re < < < ", zc.im = " < zc.im < ’\n’; < < < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Passing Structures to Functions typedef Reading and Writing Files Guidelines Some Things to Read Output of program complex.cpp: zc.re = 2, zc.im = 4 slide 221/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Passing Structures to Functions typedef Reading and Writing Files Guidelines Some Things to Read slide 222/256 typedef A typedef is used to allow the programmer to give another name to a type. typedef type NAME ; defines NAME as a new name for the existing type type Example: typedef float FF ; // FF is now a type FF abc; // equivalent to float abc; C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Often typedef is used with struct variables to avoid needing to type the word “struct” I do not encourage you to do this. See http://www.kroah.com/linux/talks/ols_2002_ kernel_codingstyle_paper/codingstyle.ps, and search for “typedef is evil” at section 3.5. Multidimensional Arrays and arrays of pointers Structures Passing Structures to Functions typedef Reading and Writing Files Guidelines Some Things to Read slide 223/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files slide 224/256 Text Files — ifstream and ofstream C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour We work with text files much the same way as with standard input and standard output Open a file for input — ifstream Open a file for output — ofstream when the fstream object goes out of scope, the file is automatically closed Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files slide 225/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files slide 226/256 If cannot open a file, what next? C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library If you fail to create an ifstream object (perhaps the file does not exist), the object evaluates as false It is always essential to test the result of things that can go wrong, and provide an error message or return an error code If things have gone wrong, it may be better to stop the program using the exit() command. Note: #include when you use exit(). Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files slide 227/256 Text Files — 7 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview #include #include // . . . std::ifstream fin( "data.in" ); if ( ! fin ) { std::cerr < "error: unable to open file " < < "’data.in’ for reading\n"; < exit( 1 ); } std::ofstream fout( "data.out" ); if ( ! fout ) { std::cerr < "error: unable to open file " < < "’data.out’ for writing\n"; < exit( 1 ); } C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files slide 228/256 Appending to files To append to a file, use the extra parameter std::ios::app when defining the ofstream object: #include #include // . . . std::ofstream fout( "data.out", std::ios::app ); if ( ! fout ) { std::cerr < "error: unable to open file " < < "’data.out’ for appending\n"; < exit( 1 ); } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures There are a number of other parameters available. OR them together with the bitwise OR operator “|” Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files slide 229/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files slide 230/256 Binary files — 1 To open a file for binary input or output, use the extra parameter std::ios::binary when defining the ofstream or ifstream object: #include #include // . . . std::ofstream fout( "data.out", std::ios::app | std::ios::binary ); if ( ! fout ) { std::cerr < "error: unable to open binary file " < < "’data.out’ for appending\n"; < exit( 1 ); } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Here we open a binary file for input: #include #include // . . . std::ifstream fin( "data.in", std::ios::in | std::ios::binary ); if ( ! fin ) { std::cerr < "error: unable to open binary file " < < "’data.in’ for reading\n"; < exit( 1 ); } slide 231/256 Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Binary files — 2 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Here we open a binary file for output: C++ and iostream library Continuing our tour Data Types #include Expressions #include Statements Functions // . . . std::ofstream fout( "data.out", std::ios::out | std::ios::binary ); Arrays Pointers if ( ! fout ) { std::cerr < "error: unable to open binary file "Arrays and Pointers < Multidimensional < "’data.out’ for writing\n"; < Arrays and arrays of pointers exit( 1 ); Structures } Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files slide 232/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files slide 233/256 Character Input and Output We can treat a file as a stream of characters. The istream member function get() and the ostream member function put() read and write one character at a time. Program copy-file-to-output.cpp: #include #include #include int main( void ) { char ch; std::ifstream fin( "abc.txt" ); if ( ! fin ) { std::cerr < "Cannot open file abc.txt\n"; < exit( 1 ); } // skips whitespace. // while ( fin > ch ) > // std::cout < ch; < while ( fin.get( ch ) ) std::cout.put( ch ); } slide 234/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Character I/O with Text Files — 2 Program copyfile.cpp #include #include #include int main( void ) { char ch; std::ifstream fin( "abc.txt" ); std::ofstream fout( "mmm.txt" ); if ( ! fin | | ! fout ) { std::cerr < "Problem opening files\n"; < exit( 1 ); } // The following skips white space: // while ( fin > ch ) > // fout < ch; < while ( fin.get( ch ) ) fout.put( ch ); } slide 235/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files slide 236/256 Working with Lines in Text Files C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour We often want to work with one line of a text file at a time the istream member function getline() reads from a file and places it in a string or character array, without the ending newline. std::cin.getline( string or character array , maximum length ); Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files getline() returns false if there is any error. slide 237/256 Program copy-lines-from-file.cpp: C Programming for Engineers Nick Urbanik Who am I? Who are You? #include #include #include int main( void ) { const int maxline = 100; char line[ maxline ]; std::ifstream fin( "abc.txt" ); if ( ! fin ) { std::cerr < "Cannot open file abc.txt\n"; < exit( 1 ); } while ( fin.getline( line, maxline ) ) std::cout < line < ’\n’; < < } Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files slide 238/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files slide 239/256 Reading other data from Text Files — 1 We can write formatted text to text files just as we can to standard output with std::cout Program fileout.cpp #include #include int main( void ) { int num = 127; std::ofstream fout( "abc.txt" ); fout < num; < std::cout < "Wrote ’" < num < < < "’ to abc.txt\n"; < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files slide 240/256 Reading other data from Text Files — 2 We can read formatted text from text files just as we can from standard input with std::cin Program filein.cpp: #include #include #include int main( void ) { int num; std::ifstream fin( "abc.txt" ); if ( ! fin ) { std::cerr < "Cannot open abc.txt\n"; < exit( 1 ); } fin > num; > std::cout < "we got ’" < num < < < "’ from abc.txt\n"; < } slide 241/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Style Guidelines Program Design Modules Some Things to Read slide 242/256 Program layout: rules of thumb Use spaces after commas, around operators, Example: printf ( "%d", i ); C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions not printf ("%d",i); and x = x + 3; Arrays Pointers not x=x+3; Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Style Guidelines Program Design Modules I suggest you put your main() function last. avoids the need to put “function prototypes” that need unnecessary extra maintainance Use modern books about C, not very old ones. Indent your program to make it easy to follow. Indent the body of loops and if statements. slide 243/256 Some Things to Read Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Style Guidelines Program Design Modules Some Things to Read slide 244/256 Program design “Real” programs need to be designed; they may be too complicated to hold in your head all at one time. Sitting at the keyboard and typing a program as you think it up may work for small programs, but bigger programs written this way will become very messy and expensive to maintain. The result is rather like a rough sketch to try out ideas. You may want to start again after the experience you get from this “sketch” C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Style Guidelines Program Design Modules The greatest cost for a program is usually in maintaining it. Flowcharts: are okay for simple programs are good for representing complicated, unstructured looping and branching But: a flowchart can easily become more complicated than the program itself! Some Things to Read slide 245/256 Pseudocode: a basic design tool C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Pseudocode is a more practical way to show how your program will work. Pseudocode is a mixture of: English and structured C programming statements, such as if, while, do. Pseudocode should be simpler and easier to understand than the final program source code Pseudocode should be written before you type in your new program! Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Style Guidelines Program Design Modules Some Things to Read slide 246/256 Program design: top-down C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview Top-down design looks at the big picture first, forgetting the details. Write pseudocode including only these important, big steps, leaving out small steps at first. This is like your main() function. Write more pseudocode for each of these big steps, giving more detail, but not the smallest details. These are written rather like function definitions. For each step, write out more pseudocode like more function definitions, until you have enough detail to begin writing your source code. Check your design carefully before you move on. C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Style Guidelines Program Design Modules Some Things to Read slide 247/256 Outline Who am I? Who are You? Overview Quick Tour Standard Input, Standard Output Redirecting Output and Input C++ and iostream library An overview of the iostream library Continuing our tour hello.cpp Basic Syntax Input characters without skipping whitespace I/O of other data to standard output and from standard input Reading into strings Loops Reading till the end of file Infinite Loop while reading Data Types Integer Types Characters Octal, Hexadecimal Output with ostream Floating Point Types Named Constants Enumerated Types: enum Expressions Arithmetic Expressions Arithmetic Operators and Precedence All Operators and their Precedence Relational Expressions Logical Expressions Assignment Expressions Increment, Decrement Operators Comma Operator Arithmetic if Expressions Bitwise Operators Casts Statements Simple Statements Compound Statements Scope Looping Statements while Statement do statement Avoid Confusing == with = Using a constant or single variable as a test condition while and the null statement for Statement Comparing while and for if and switch Statements break, continue, goto Functions Defining Functions Calling Functions Using return Value from Functions Function Parameters Arrays Defining Arrays Arrays and Loops Strings Pointers Pointers as Function Parameters Arrays and Pointers Strong relationship between arrays and pointers Multidimensional Arrays and arrays of pointers Arrays of pointers Memory Allocation Multidimensional Arrays Command Line Arguments: argc, argv Structures Passing Structures to Functions typedef Reading and Writing Files fstream: file input and output Error Handling Binary files Character I/O Reading a Line at a time: getline() I/O of other data to/from Text Files Guidelines Style Guidelines Program Design Modules Some Things to Read C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Style Guidelines Program Design Modules Some Things to Read slide 248/256 Making an application from many modules Most useful C or C++ programs are written in separate modules Each module corresponds to: one .c, .C, .cc, .cpp, or .cxx file (lets call this the source file), and one .h, .H, .hh, or .hpp file (we call this the header file). C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Style Guidelines Program Design Modules Each header file lists the publicly exported names: type definitions, global variables, and function prototypes Avoid defining variables or functions in header files It makes this set of names as small as possible to reduce the interaction between modules All non-public functions defined in the source files are defined with the keyword static so that they cannot be linked to from other modules. Some Things to Read slide 249/256 Modules — silly example main.cpp: #include #include "calc.h" #include "main.h" int glob; int main( void ) { glob = 10; int sum = calc( 15 ); std::cout < "sum = " < sum < ’\n’; < < < } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Style Guidelines Program Design Modules main.h: #ifndef MAIN H #define MAIN H extern int glob; #endif slide 250/256 Some Things to Read Modules — silly example (continued) calc.cpp: #include "main.h" #include "calc.h" int calc( int n ) { return glob + n; } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers calc.h: #ifndef CALC H #define CALC H extern int calc( int n ); #endif slide 251/256 Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Style Guidelines Program Design Modules Some Things to Read static variables A variable defined with the keyword static is visible only within its file, and does not conflict with a variable with the same name defined in another file the static keyword can (and should) be used with functions that are to be used only within one file The static keyword can be used inside functions and blocks It is initialised once, and its value remains even between function calls. See Program static.cpp: #include void show times called( void ) { static int called = 0; std::cout < "called " < ++called < " times\n"; < < < } int main( void ) { for ( int i = 0; i < 5; ++i ) show times called(); } C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Style Guidelines Program Design Modules output of static.cpp: called called called called called slide 252/256 1 2 3 4 5 times times times times times Some Things to Read Resources I Brian W. Kernighan and Dennis M. Ritchie. The C Programming Language. Prentice Hall 1988. Stanley B. Lippman and Josée Lajoie and Barbara E. Moo. C++ Primer, Fourth Edition. Addison-Wesley 2005. Bjarne Stroustrup. The C++ Programming Language (Special 3rd Edition). Addison-Wesley, 2004, ISBN 0201889544. Tom Adamson and James L. Antonakos and Kenneth C. Mansfield Jr. Structured C for Engineering and Technology, Third Edition. Prentice Hall, 1998. Steve Oualline. Practical C Programming. O’Reilly 1993. slide 253/256 C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read Resources II Paul Davies. The Indispensable Guide to C With Engineering Applications. Addison-Wesley 1995. H. M. Deitel and P. J. Deitel. C How to Program, Second Edition. Prentice Hall 1994. Vincent Kassab. Technical C Programming. Prentice Hall 1989. Marshall Cline. C++ FAQ LITE. http://www.parashift.com/c++-faq-lite/ C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 254/256 Resources III C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Data Types Bjarne Stroustrup. A Tour of the Standard Library. Chapter 3 of The C++ Programming Language. http: //public.research.att.com/~bs/3rd_tour2.pdf Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 255/256 License covering this document C Programming for Engineers Nick Urbanik Who am I? Who are You? Overview C++ and iostream library Continuing our tour Copyright c 2006 Nick Urbanik You can redistribute modified or unmodified copies of this document provided that this copyright notice and this permission notice are preserved on all copies under the terms of the GNU General Public License as published by the Free Software Foundation — either version 2 of the License or (at your option) any later version. Data Types Expressions Statements Functions Arrays Pointers Arrays and Pointers Multidimensional Arrays and arrays of pointers Structures Reading and Writing Files Guidelines Some Things to Read slide 256/256