C++ program structure Variable Declarations

Size: px
Start display at page:

Download "C++ program structure Variable Declarations"

Transcription

1 C++ program structure A C++ program consists of Declarations of global types, variables, and functions. The scope of globally defined types, variables, and functions is limited to the file in which they are declared. Definitions of one or more functions, one of the functions must be named main A C++ function definition consists of Declarations of locally defined types, variables, and functions. Executable statements Functions may not be nested Declarations and executable statements may be intermixed. Types, variables, and functions must be declared before they are referenced in statements. Variable Declarations Variable declarations have the form: type variable list ; variable list ::= variable variable, variable list Example int i, j, k; // Declares three integer variables: // i, j, and k float x, y; // Declares two floating variables: // x and y. string s; // Declares s to be of type string // (a library defined type) 2

2 Statements statement ::= labeled statement expression ; compound statement selection statement iteration statement jump statement declaration statement try-block 3 labeled statements labeled statements ::= identifier : statement case constant expression : statement default : statement The form identifier : statement is used as the target of the goto statement. The case and default forms are used within switch. 4

3 expression statement expression statement ::= expression ; ; In C++ assignment is an operator. Some other programming languages have an assignment statement. 5 compound statement compound statement ::= { statement list } statement list ::= empty statement list statement 6

4 selection statement selection statement ::= if ( expression ) statement if ( expression ) statement else statement switch ( expression ) statement In the if statement, an expression value of 0 is treated as false and a nonzero value is treated as true. If if statements are nested, the closest if is associated with an else. The statement following the switch ( expression ) is generally a compound statement containing statements which are labeled using the case constant expression : or default : form. (There may be only one default label.) The expression is evaluated and control is transferred to the statement whose case constant expression : equals the expression value. If none match, the statement is skipped. Flow of control otherwise passes over case constant expression : s. One must explicitly exit the scope of the switch statement via a break statement. 7 Example of C++ switch break after each case switch (n) { case 1: case 2: cout << "Buckle my shoe\n"; break; case 3: case 4: cout << "Shut the door\n"; break; case 5: case 6: cout << "Pick up sticks\n"; break; } 8

5 Example of C++ switch No break after case switch (i+1) { case 12: voice << "Twelve lords a-leaping;" << endl; case 11: voice << "Eleven ladies dancing;" << endl; case 10: voice << "Ten pipers piping;" << endl; case 9: voice << "Nine drummers drumming;" << endl; case 8: voice << "Eight maids a-milking;" << endl; case 7: voice << "Seven swans a-swimming;" << endl; case 6: voice << "Six geese a-laying;" << endl; case 5: voice << "Five golden rings;" << endl; case 4: voice << "Four calling birds;" << endl; case 3: voice << "Three French hens;" << endl; case 2: voice << "Two turtle doves, and" << endl; case 1: voice << "A partrige in a pear tree" << endl << endl; } 9 iteration statement iteration statement ::= while ( expression ) statement do statement while ( expression ) ; for ( for init statement expression-1 ; expression-2 ) statement expression-1 ::= empty expression expression-2 ::= empty expression 10

6 The for statement The statement for ( for init statement expression-1 ; expression-2 ) statement is logically equivalent to: for init statement while ( expression-1 ) { statement expression-2 ; } Generally, the for init statement will set a variable to an initial value, expression-1 will test to see that that variable has not reached its terminating condition, and expression-2 will increment (or decrement) the variable. 11 jump statement jump statement ::= break ; continue ; return ; return expression ; goto identifier ; A break must occur within either an iteration statement or a switch statement. It causes control to pass out of the iteration or switch statement. A continue must occur within an iteration statement. It causes control to pass to the end of the iteration statement and the next iteration to be executed. 12

7 The return statement, without an expression, returns control to the caller of a function that has a void return type. The return statement with an expression returns control to the caller of a function with the expression as the value of the function. 13 Exception Handling try-block ::= try compound statement handler-seq handler-seq ::= handler handler-seq-opt handler-seq-opt ::= empty handler-seq handler ::= catch ( exception-declaration ) compound statement exception-declaration ::= type-specifier-seq object name... throw-expression ::= throw assignment-expression-opt When a function detects an error, it should throw an exception. The function that calls this function (directly or indirectly) may catch the exception. If an exception is not caught, the program aborts. Exceptions are objects that may be of any type. The type-matching of a thrown exception to the catch is similar to the type-matching of a function call. A catch (...) will catch any exception, but not provide any information about the specific exception caught. A standard set of exceptions is defined in the header file <stdexcept>. 14

8 Expressions Expressions are of the general form operand 1 operator operand 2 or operator operand or operand operator Operands and operators are grouped from left to right according to the operator precedence. The depth of the operator in the syntax tree determines operator precidence. The following is an abbreviated syntax for C++ expressions. 15 name ::= identifier primary expression ::= literal name ( expression ) post-fix expression ::= primary expression post-fix expression ( expression list opt ) post-fix expression [ expression ] post-fix expression. member name post-fix expression -> member name post-fix expression ++ post-fix expression -- expression list opt ::= empty expression list expression list ::= assignment expression expression list, assignment expression unary expression ::= post-fix expression ++ unary expression -- unary expression unary operator cast expression unary operator ::= + - ~! * & cast expression ::= unary expression ( type name ) cast expression pm expression ::= cast expression 16

9 multiplicative expression ::= pm expression multiplicative expression * pm expression multiplicative expression / pm expression multiplicative expression % pm expression additive expression ::= multiplicative expression additive expression + multiplicative expression additive expression - multiplicative expression shift expression ::= additive expression shift expression << additive expression shift expression >> additive expression relational expression ::= shift expression relational expression < shift expression relational expression > shift expression relational expression <= shift expression relational expression >= shift expression 17 equality expression ::= relational expression equality expression == relational expression equality expression!= relational expression and expression ::= equality expression and expression & equality expression exclusive-or expression ::= and expression exclusive-or expression ^ and expression inclusive-or expression ::= exclusive-or expression inclusive-or expression exclusive-or expression logical-and expression ::= inclusive-or expression logical-and expression && inclusive-or expression logical-or expression ::= logical-and expression logical-or expression logical-and expression conditional expression ::= logical-or expression logical-or expression? expression : conditional expression 18

10 assignment expression ::= conditional expression unary expression assignment operator assignment expression assignment operator ::= = *= /= %= += -= >>= <<= &= ^= = expression ::= assignment expression expression, assignment expression 19 The form post-fix expression ( expression list opt ) is known as the function call. C++ a function may be an expression. The form post-fix expression [ expression ] is known as the array access operation, which will be discussed later. The forms post-fix expression. member name and post-fix expression -> member name access members of classes, which will be discussed later. The forms post-fix expression ++ and post-fix expression -- are post increment (decrement). The value is the value of post-fix expression but there is a side-effect that the post-fix expression is incremented (decremented) by one. post-fix expression must be what is known as a modifiable l-value. I.E. it must be capable of being the target of an assignment. 20

11 The forms ++ unary expression and -- unary expression are pre increment(decrement). The value is the value of unary expression incremented (decremented) by one. There is also the side effect that the unary expression is incremented (decremented) by one. unary expression must be what is known as a modifiable l-value. I.E. it must be capable of being the target of an assignment. The unary operator + has no effect; - returns the arithmetic negative; ~ the bit-wise complement, and! the logical complement. (! turns a zero into a non-zero value and a non-zero value into a zero). The unary operator * is used to de-reference a pointer. (More on pointers later.) The unary operator & is used to create a pointer value. 21 The form: cast expression ::= unary expression ( type name ) cast expression has the effect of either forcing a type conversion or having the cast expression interpreted as the type type name. While still part of the language, its use is discouraged. The following are the new cast operators: static_cast < type-id > ( expression ) Convert the expression to the specified type, if there is a conversion defined. reinterpert_cast < type-id > ( expression ) The raw bits are reinterpreted to represent the specified type. The results are computer and compiler implementation specific. Should be used with caution and desperation. dynamic_cast < type-id > ( expression ) This will be discussed after polymorphism is introduced. const_cast < type-id > ( expression ) Can be used to change the const status of the expression. 22

12 The forms: multiplicative expression ::= pm expression multiplicative expression * pm expression multiplicative expression / pm expression multiplicative expression % pm expression additive expression ::= multiplicative expression additive expression + multiplicative expression additive expression - multiplicative expression % is the modulus operator. The operators << and >> are the left shift and right shift respectively. The operands must be integers. They are also known as the insertion and extraction operators when applied to I/O streams. The forms equality expression ::= relational expression equality expression == relational expression equality expression!= relational expression logical-and expression ::= inclusive-or expression logical-and expression && inclusive or expression logical-or expression ::= logical-and expression logical-or expression logical-and expression 23 The forms: and expression ::= equality expression and expression & equality expression exclusive-or expression ::= and expression exclusive-or expression ^ and expression inclusive-or expression ::= exclusive-or expression inclusive-or expression exclusive-or expression perform bit-wise operations. Care must be taken in using & vs. && and vs.. The form: logical-or expression? expression : conditional expression Its value is the value of expression (the second operand) if logical-or expression (the first operand) is true and conditional expression (the third operand) if logical-or expression is false. 24

13 The form unary expression = assignment expression is the same as the assignment statement in other languages. The left hand side must be what is known as a modifiable l-value. I.E. it must be capable of being the target of an assignment. The value is the value of assignment expression. While other operations of equal precidence are associated from left to right, the assignment operators are associated from right to left. Thus assignments may be nested or chained such as i = j = k = 0; which is equivalent to (i = (j = (k = 0))); and has the effect of setting all of the variables to 0. The form unary expression operator = assignment expression is equivalent to unary expression = unary expression operator assignment expression where operator is * / % + - >> << & ^ or I.E. x /= 5; is the same as x = x / 5 25 Fundamental Types The fundamental (built-in) types are as follows: C++ Type bool Meaning The logical values true and false. There is an implicit conversion from all non-zero numeric values or non-null pointers to true, and all zero numeric values or null pointers to false. char The character set recognized by the computer; generally 8-bit bytes. May be either unsigned or signed. unsigned char The character set recognized by the computer; generally 8-bit bytes. Explicitly treated as an un-signed value. signed char The character set recognized by the computer; generally 8-bit bytes. Explicitly treated as a signed value. int The integers. Range is implementation defined. Generally either 16 or 32 bits. short The integers. Generally 16 bits. May also be written as short int. long The integers. Generally 32 bits. May also be written as long int. 26

14 C++ Type Meaning unsigned short The integers treated as an unsigned value. Generally 16 bits. May also be written as unsigned short int. unsigned long The integers treated as an unsigned value. Generally 32 bits. May also be written as unsigned long int. float Floating point or real arithmetic values. double Double precision floating point. long double Extended double precision floating point. 27 Form: return type function name (); Example: void skip_three(); Function Declarations (functions without arguments) Declares the function skip_three as taking no arguments and returning no value. Function Call (functions without arguments, and returning no value) Form: function name (); Example: draw_circle(); Initiates the execution of the function. After the function has finished, the next statement in the parent function will be executed. 28

15 Function Definition (functions taking no arguments) return type function name () { statement list } Example: void draw_triangle() { // Draw a triangle. draw_intersect(); draw_base(); } // end draw_triangle 29 Draw Stick Figure // FILE: StkFigMn.cpp // DRAW A STICK FIGURE (Main Function Only) // Functions used... // DRAWS A CIRCLE void draw_circle(); // DRAWS A TRIANGLE void draw_triangle(); // DRAWS INTERSECTING LINES void draw_intersect(); int main() { // Draw the figure. // Draw a circle. draw_circle(); // Draw a triangle. draw_triangle(); // Draw intersecting lines. draw_intersect(); return 0; } 30

16 IXQFWLRQPDLQ // FILE: StkFigMn.cpp // DRAW A STICK FIGURE (Main Function Only) // Functions used... // DRAWS A CIRCLE void draw_circle(); // DRAWS A TRIANGLE void draw_triangle(); // DRAWS INTERSECTING LINES void draw_intersect(); int main() { // Draw the figure. // Draw a circle. draw_circle(); // Draw a triangle. draw_triangle(); // Draw intersecting lines. draw_intersect(); return call IXQFWLRQGUDZBFLUFOH // FILE: DrawCir.cpp // DRAWS A CIRCLE #include <iostream.h> void draw_circle() { cout << " * " << endl; cout << " * *" << endl; cout << " * * " << endl; } // end draw_circle } return 0; 31 Function Declaration (functions taking arguments) Form: return type function name ( formal argument type list ); argument list is a list of zero or more formal argument s separated by commas. formal argument ::= type type argument name default value default value ::= empty = expression Normally only the type is declared unless a default value is specified. Arguments with default values must be specified after arguments without. Example: int max(int, int, int); Declares the function max as taking a three integer values and returning an integer result. 32

17 Function Call (functions with arguments) function name ( actual argument list ) actual argument list is a list of zero or more expression s separated by commas. There must be one actual argument for each formal argument which does not have a default value specified. The type of each actual argument must correspond to each formal argument. The value of this expression is the result returned by the function. The types of the expressions in the actual argument list must correspond (or be convertible to) the types in the formal argument list. Example a = max(1, 3, 2); will get the value of 3 and assign it to a. 33 Function Definition (functions taking arguments) return type function name ( formal argument list ){ function body } argument list is a list of zero or more formal argument s separated by commas. formal argument ::= type type argument name default value Example: int max (int x, int y, int z) { int m = (x > y)? x : y; return (m > z)? m : z; } 34

18 Steps in a Function Call 1. Each expression in actual argument list is evaluated. 2. The declarations of the formal argument list are executed with each of its corresponding actual argument as the initial value. 3. The function body is executed. 4. The return value becomes the value of the function call expression. Example: a = max(1, 3, 2); Is equivalent to int x = 1, y = 3, z = 2; int m = (x > y)? x : y; a = (m > z)? m : z; Observe that the values of the actual argument s are copied into the corresponding formal argument s. 35 References A declaration of the form: type & identifier1 = identifier2 Declares that identifier1 is a reference to identifier2. Effectively identifier1 becomes an alias for identifier2. Used mostly in functions. Example: void compute_sum_ave (float num1, // IN: values used in compuation float num2, float& sum, // OUT: sum of num1 and num2 float& average) // OUT: average of num1 and num2 { sum = num1 + num2; average = sum / 2.0; } 36

19 The expression: compute_sum_average(x, y, s, m); is equivalent to: float num1 = x, num2 = y; float& the_sum = s; float& average = m; the_sum = num1 + num2; average = the_sum / 2.0; Observe that the values of the actual arguments corresponding to num1 and num2 (x and y) are copied into these variables for the duration of the function execution. On the other hand, the names sum and average take the place of the corresponding actual arguments (s and m). 37 calling function data area compute_sum_ave data area x 8.0 y 10.0 s? m? value of x copied into num1 value of y copied into num2 reference to s stored in sum reference to m stored in average num1 num2 sum average 38

20 // FILE: MkChange.cpp // DETERMINES THE NUMBER OF UNITS OF CHANGE OF A PATICULAR // DENOMINATION TO DISPENSE WHEN MAKING CHANGE void make_change (int change_denom, // IN: denomination in // which change is // to be returned int& change_needed, // INOUT: amount for which // change is needed int& num_units) // OUT: number of units // of specified // denomination to // be returned // Pre: Change_denomination > 0 and change_needed >= 0 // Post: Num_units is the number of units of change to // dispense and change_needed is reduced by the // amout given. { num_units = change_needed / change_denom; change_needed = change_needed - (num_units * change_denom); return; } // end of make_change 39 // FILE: MakChng.cpp // DRIVER PROGRAM FOR make_change #include <iostream> #include <string> void make_change(int, int&, int&); int main() { float change; int pennies; int num; int denoms[] = {2000, 1000, 500, 100, 25, 10, 5, 1}; std::string names[] = {"twenties", "tens", "fives", "ones", "quarters", "dimes", "nickels", "pennies"}; for (;;){ // Loop forever std::cout << "Enter amount (0 terminates) "; std::cin >> change; if (change == 0.0) break; // exit loop pennies = int(change * ); for (int i = 0; i < 8; i++){ make_change(denoms[i], pennies, num); if (num!= 0) std::cout << num << ' ' << names[i] << std::endl; } // end for loop } // end loop forever return 0; } 40

21 The main program A program is invoked by the operating system. This can be as a result of a command issued to the shell, clicking an icon on the window desk-top, or from another program, such as the a GUI development environment. The operating system creates a run-time environment and then transfers control to a pre-defined entry point. For C++ programs, this pre-defined entry point is an implementation and operating system specific program that calls the function main. When main returns, this program passes the return value from main back to the operating system. A return value of 0 is considered a normal return, and a non-zero value is considered an error return. The function main can be in one of two forms: int main () { /* */ return 0;} or int main (int argc, char* argv[]){ /* */ return 0;} In the second form, argc is the count of the number of arguments, and argv is an array of pointers to char that are the arguments themselves. There is always at least one argument, which is the name of the program. Arguments are either specified on the command line, or they may be defined for the window icon, or passed as part of an operating system call from a GUI. 41 For example, the g++ compiler may be invoked as follows: g++ -o hello hello.cpp Since g++ is a c++ program, its main function will be called, in this example, with the following: argc 4 argv[0] "g++" argv[1] "-o" argv[2] "hello" argv[3] "hello.cpp" 42

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements 9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

6. Control Structures

6. Control Structures - 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

Comp151. Definitions & Declarations

Comp151. Definitions & Declarations Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const

More information

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral

More information

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

More information

How to: Use Basic C++, Syntax and Operators

How to: Use Basic C++, Syntax and Operators June 7, 1999 10:10 owltex Sheet number 22 Page number 705 magenta black How to: Use Basic C++, Syntax and Operators A In this How to we summarize the basic syntax of C++ and the rules and operators that

More information

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions Phys4051: C Lecture 2 & 3 Functions (Review) Comment Statements Variables & Operators Branching Instructions Comment Statements! Method 1: /* */! Method 2: // /* Single Line */ //Single Line /* This comment

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics

More information

C++ Language Tutorial

C++ Language Tutorial cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain

More information

Basics of I/O Streams and File I/O

Basics of I/O Streams and File I/O Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading

More information

While Loop. 6. Iteration

While Loop. 6. Iteration While Loop 1 Loop - a control structure that causes a set of statements to be executed repeatedly, (reiterated). While statement - most versatile type of loop in C++ false while boolean expression true

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

Chapter One Introduction to Programming

Chapter One Introduction to Programming Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of

More information

Passing 1D arrays to functions.

Passing 1D arrays to functions. Passing 1D arrays to functions. In C++ arrays can only be reference parameters. It is not possible to pass an array by value. Therefore, the ampersand (&) is omitted. What is actually passed to the function,

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

An Incomplete C++ Primer. University of Wyoming MA 5310

An Incomplete C++ Primer. University of Wyoming MA 5310 An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

More information

Lecture 2 Notes: Flow of Control

Lecture 2 Notes: Flow of Control 6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. The

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

Chapter 5 Functions. Introducing Functions

Chapter 5 Functions. Introducing Functions Chapter 5 Functions 1 Introducing Functions A function is a collection of statements that are grouped together to perform an operation Define a function Invoke a funciton return value type method name

More information

JavaScript: Control Statements I

JavaScript: Control Statements I 1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can

More information

C++ Essentials. Sharam Hekmat PragSoft Corporation www.pragsoft.com

C++ Essentials. Sharam Hekmat PragSoft Corporation www.pragsoft.com C++ Essentials Sharam Hekmat PragSoft Corporation www.pragsoft.com Contents Contents Preface 1. Preliminaries 1 A Simple C++ Program 2 Compiling a Simple C++ Program 3 How C++ Compilation Works 4 Variables

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be... What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

More information

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

An Introduction to Assembly Programming with the ARM 32-bit Processor Family An Introduction to Assembly Programming with the ARM 32-bit Processor Family G. Agosta Politecnico di Milano December 3, 2011 Contents 1 Introduction 1 1.1 Prerequisites............................. 2

More information

I PUC - Computer Science. Practical s Syllabus. Contents

I PUC - Computer Science. Practical s Syllabus. Contents I PUC - Computer Science Practical s Syllabus Contents Topics 1 Overview Of a Computer 1.1 Introduction 1.2 Functional Components of a computer (Working of each unit) 1.3 Evolution Of Computers 1.4 Generations

More information

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points

More information

Objective-C Tutorial

Objective-C Tutorial Objective-C Tutorial OBJECTIVE-C TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i ABOUT THE TUTORIAL Objective-c tutorial Objective-C is a general-purpose, object-oriented programming

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

Statements and Control Flow

Statements and Control Flow Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10. Introduction to

More information

Member Functions of the istream Class

Member Functions of the istream Class Member Functions of the istream Class The extraction operator is of limited use because it always uses whitespace to delimit its reads of the input stream. It cannot be used to read those whitespace characters,

More information

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

C++ Outline. cout << Enter two integers: ; int x, y; cin >> x >> y; cout << The sum is:  << x + y << \n ; C++ Outline Notes taken from: - Drake, Caleb. EECS 370 Course Notes, University of Illinois Chicago, Spring 97. Chapters 9, 10, 11, 13.1 & 13.2 - Horstman, Cay S. Mastering Object-Oriented Design in C++.

More information

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero THEN the Average is Sum divided by Count Conditions

More information

C++FA 3.1 OPTIMIZING C++

C++FA 3.1 OPTIMIZING C++ C++FA 3.1 OPTIMIZING C++ Ben Van Vliet Measuring Performance Performance can be measured and judged in different ways execution time, memory usage, error count, ease of use and trade offs usually have

More information

Answers to Review Questions Chapter 7

Answers to Review Questions Chapter 7 Answers to Review Questions Chapter 7 1. The size declarator is used in a definition of an array to indicate the number of elements the array will have. A subscript is used to access a specific element

More information

Syllabus OBJECT ORIENTED PROGRAMMING C++

Syllabus OBJECT ORIENTED PROGRAMMING C++ 1 Syllabus OBJECT ORIENTED PROGRAMMING C++ 1. Introduction : What is object oriented programming? Why do we need objectoriented. Programming characteristics of object-oriented languages. C and C++. 2.

More information

Chapter 3 Operators and Control Flow

Chapter 3 Operators and Control Flow Chapter 3 Operators and Control Flow I n this chapter, you will learn about operators, control flow statements, and the C# preprocessor. Operators provide syntax for performing different calculations or

More information

Conditions & Boolean Expressions

Conditions & Boolean Expressions Conditions & Boolean Expressions 1 In C++, in order to ask a question, a program makes an assertion which is evaluated to either true (nonzero) or false (zero) by the computer at run time. Example: In

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Introduction to the C language Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) The C language

More information

Chapter 8 Selection 8-1

Chapter 8 Selection 8-1 Chapter 8 Selection 8-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

More information

Keil C51 Cross Compiler

Keil C51 Cross Compiler Keil C51 Cross Compiler ANSI C Compiler Generates fast compact code for the 8051 and it s derivatives Advantages of C over Assembler Do not need to know the microcontroller instruction set Register allocation

More information

Parameter Passing. Standard mechanisms. Call by value-result Call by name, result

Parameter Passing. Standard mechanisms. Call by value-result Call by name, result Parameter Passing Standard mechanisms Call by value Call by reference Other methods Call by value-result Call by name, result Terms Function definition where the details of the function are presented (type,

More information

PL / SQL Basics. Chapter 3

PL / SQL Basics. Chapter 3 PL / SQL Basics Chapter 3 PL / SQL Basics PL / SQL block Lexical units Variable declarations PL / SQL types Expressions and operators PL / SQL control structures PL / SQL style guide 2 PL / SQL Block Basic

More information

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

A brief introduction to C++ and Interfacing with Excel

A brief introduction to C++ and Interfacing with Excel A brief introduction to C++ and Interfacing with Excel ANDREW L. HAZEL School of Mathematics, The University of Manchester Oxford Road, Manchester, M13 9PL, UK CONTENTS 1 Contents 1 Introduction 3 1.1

More information

6.087 Lecture 2 January 12, 2010

6.087 Lecture 2 January 12, 2010 6.087 Lecture 2 January 12, 2010 Review Variables and data types Operators Epilogue 1 Review: C Programming language C is a fast, small,general-purpose,platform independent programming language. C is used

More information

Functions and Parameter Passing

Functions and Parameter Passing Chapter 5: Functions and Parameter Passing In this chapter, we examine the difference between function calls in C and C++ and the resulting difference in the way functions are defined in the two languages.

More information

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

Chapter 2: Elements of Java

Chapter 2: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

Example of a Java program

Example of a Java program Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);

More information

Pemrograman Dasar. Basic Elements Of Java

Pemrograman Dasar. Basic Elements Of Java Pemrograman Dasar Basic Elements Of Java Compiling and Running a Java Application 2 Portable Java Application 3 Java Platform Platform: hardware or software environment in which a program runs. Oracle

More information

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c Lecture 3 Data structures arrays structs C strings: array of chars Arrays as parameters to functions Multiple subscripted arrays Structs as parameters to functions Default arguments Inline functions Redirection

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

Moving from C++ to VBA

Moving from C++ to VBA Introduction College of Engineering and Computer Science Mechanical Engineering Department Mechanical Engineering 309 Numerical Analysis of Engineering Systems Fall 2014 Number: 15237 Instructor: Larry

More information

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

J a v a Quiz (Unit 3, Test 0 Practice)

J a v a Quiz (Unit 3, Test 0 Practice) Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

More information

13 Classes & Objects with Constructors/Destructors

13 Classes & Objects with Constructors/Destructors 13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.

More information

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures The C++ Language Loops Loops! Recall that a loop is another of the four basic programming language structures Repeat statements until some condition is false. Condition False True Statement1 2 1 Loops

More information

Compiler Construction

Compiler Construction Compiler Construction Lecture 1 - An Overview 2003 Robert M. Siegfried All rights reserved A few basic definitions Translate - v, a.to turn into one s own language or another. b. to transform or turn from

More information

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

For the next three questions, consider the class declaration: Member function implementations put inline to save space. Instructions: This homework assignment focuses on basic facts regarding classes in C++. Submit your answers via the Curator System as OQ4. For the next three questions, consider the class declaration:

More information

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

More information

Conditionals (with solutions)

Conditionals (with solutions) Conditionals (with solutions) For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations: final int MAX = 25, LIMIT = 100; int num1 = 12, num2 = 25, num3 = 87;

More information

MISRA-C:2012 Standards Model Summary for C / C++

MISRA-C:2012 Standards Model Summary for C / C++ MISRA-C:2012 Standards Model Summary for C / C++ The LDRA tool suite is developed and certified to BS EN ISO 9001:2000. This information is applicable to version 9.4.2 of the LDRA tool suite. It is correct

More information

CORBA Programming with TAOX11. The C++11 CORBA Implementation

CORBA Programming with TAOX11. The C++11 CORBA Implementation CORBA Programming with TAOX11 The C++11 CORBA Implementation TAOX11: the CORBA Implementation by Remedy IT TAOX11 simplifies development of CORBA based applications IDL to C++11 language mapping is easy

More information

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1 QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

arrays C Programming Language - Arrays

arrays C Programming Language - Arrays arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)

More information

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters The char Type ASCII Encoding The C char type stores small integers. It is usually 8 bits. char variables guaranteed to be able to hold integers 0.. +127. char variables mostly used to store characters

More information

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from

More information

El Dorado Union High School District Educational Services

El Dorado Union High School District Educational Services El Dorado Union High School District Course of Study Information Page Course Title: ACE Computer Programming II (#495) Rationale: A continuum of courses, including advanced classes in technology is needed.

More information

Computer Programming C++ Classes and Objects 15 th Lecture

Computer Programming C++ Classes and Objects 15 th Lecture Computer Programming C++ Classes and Objects 15 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2013 Eom, Hyeonsang All Rights Reserved Outline

More information

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE PROGRAMMING IN C CONTENT AT A GLANCE 1 MODULE 1 Unit 1 : Basics of Programming Unit 2 : Fundamentals Unit 3 : C Operators MODULE 2 unit 1 : Input Output Statements unit 2 : Control Structures unit 3 :

More information

Stacks. Linear data structures

Stacks. Linear data structures Stacks Linear data structures Collection of components that can be arranged as a straight line Data structure grows or shrinks as we add or remove objects ADTs provide an abstract layer for various operations

More information

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

Selection Statements

Selection Statements Chapter 5 Selection Statements 1 Statements So far, we ve used return statements and expression ess statements. e ts. Most of C s remaining statements fall into three categories: Selection statements:

More information

VB.NET Programming Fundamentals

VB.NET Programming Fundamentals Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

More information

public static void main(string[] args) { System.out.println("hello, world"); } }

public static void main(string[] args) { System.out.println(hello, world); } } Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static

More information

The programming language C. sws1 1

The programming language C. sws1 1 The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan

More information

Windows PowerShell Essentials

Windows PowerShell Essentials Windows PowerShell Essentials Windows PowerShell Essentials Edition 1.0. This ebook is provided for personal use only. Unauthorized use, reproduction and/or distribution strictly prohibited. All rights

More information

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++ MS Visual C++ Introduction 1 Quick Introduction The following pages provide a quick tutorial on using Microsoft Visual C++ 6.0 to produce a small project. There should be no major differences if you are

More information

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore

More information

5 Arrays and Pointers

5 Arrays and Pointers 5 Arrays and Pointers 5.1 One-dimensional arrays Arrays offer a convenient way to store and access blocks of data. Think of arrays as a sequential list that offers indexed access. For example, a list of

More information

URI and UUID. Identifying things on the Web.

URI and UUID. Identifying things on the Web. URI and UUID Identifying things on the Web. Overview > Uniform Resource Identifiers (URIs) > URIStreamOpener > Universally Unique Identifiers (UUIDs) Uniform Resource Identifiers > Uniform Resource Identifiers

More information

An API for Reading the MySQL Binary Log

An API for Reading the MySQL Binary Log An API for Reading the MySQL Binary Log Mats Kindahl Lead Software Engineer, MySQL Replication & Utilities Lars Thalmann Development Director, MySQL Replication, Backup & Connectors

More information

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer About The Tutorial C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system.

More information

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays Motivation Suppose that we want a program that can read in a list of numbers and sort that list, or nd the largest value in that list. To be concrete about it, suppose we have 15 numbers to read in from

More information

C++ Crash Kurs. C++ Object-Oriented Programming

C++ Crash Kurs. C++ Object-Oriented Programming C++ Crash Kurs C++ Object-Oriented Programming Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ classes A class is user-defined type

More information

Chapter 2 Introduction to Java programming

Chapter 2 Introduction to Java programming Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break

More information

C++ Programming Language

C++ Programming Language C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

More information