Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Size: px
Start display at page:

Download "Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)"

Transcription

1 Introduction to C++ 1. General C++ is an Object oriented extension of C which was derived from B (BCPL) Developed by Bjarne Stroustrup (AT&T Bell Labs) in early 1980 s 2. A Simple C++ Program A C++ program consists of: a set of data & function definitions, and the main function (or driver) Example 2.1: Stock value program Input: o # of units, user is going to buy o unit price Output: o total cost of transaction #include <iostream> using namespace std; int main() // Main function. Gets the stock price and units, calculates // and prints the total cost int units; double price; double cost; cout << Enter # of units and unit price: \n ; cin >> units; cin >> price; cost = units * price * 1.05; cout << The total cost is $ ; cout << cost; cout << endl; return 0; Sample Dialogue >Enter # of units and unit price: 10 5 Intro to C++ 1

2 > The total cost is $ 52.5 Main Points Main function defined as : int main() every C++ program has a main function It is called when the program starts (by the operating system) it returns an int value to the op. system - 0 : success - else : some error Statements perform an action end with a ; Variable declarations reserve memory space format: <type> <list of variables>; i.e. int units; - declares a variable (location) units of type integer variable names can have - letters, digits and _ - are case sensitive every variable must be given a type some built-in types: Type Represents Size int integer 16 or 32 bits float real number 32 bits double real number 64 bits char character 8 bits bool boolean 1 bit (two values: true, false) variables can be initialized - int x = 0, y = 5; - int x(0), y(5); Input cin is the standard input device (keyboard) cin >> units - reads a value from cin and stores it in units can do: cin >> x >> y Output cout << Enter...\n - displays the string Enter... on the standard output cout cout is usually set to be the monitor endl or \n is the end-of-line character cout << cost displays the value of cost Intro to C++ 2

3 can output multiple items:: - cout <<... <<... ; Expressions return a value use variables, constants and operators arithmetic operators: * / % (remainder) C++ uses infix notation (operator is between operands) i.e. units * price * 1.05 Assignment Operator ( =) <variable> = <expression> assigns the value of expression to variable Return statement return <expression>; terminates the function returns the value of the expression Preprocessor Commands Usually written at the beginning Perform tasks before the program is compiled. # include <filename> - includes a file Comments from // to end of line, or from /* to */ Namespaces C++ allow the user to define environments (called namespaces) std is the standard environment (default for most compilers) for some compilers you need to tell the compiler which namespace to use Functions A program is usually broken down into small tasks. Each task is implemented by a function. Example 2.2 : A better implementation of example 2.1 #include <iostream> using namespace std; Intro to C++ 3

4 double totalcost( int units, double unit_price ) double cost; cost = units * unit_price * 1.05; return cost int main() // Main function. Gets the stock price and units, calculates // and prints the total cost int units; double price; cout << Enter # of units and unit price: \n ; cin >> units >> price; cout << The total cost is $ << totalcost( units, price) << endl; return 0; Points (1) Function Definition <return type> <function name>( <parameter list> ) <statements> i.e. function totalcost a function must have name (C++ has no anonymous functions ) and return type (2) Local Variables parameters and variables declared inside the function are only known in the function var units inside totalcost is different than units inside main - are two different memory locations (3) Return statement terminates function returns a value to caller header or prototype function body (4) Function Call to call a fn, write the fn name with the list of arguments in () i.e. totalcost( 10, 100); a call creates a new environment with the function s parameters and local var s and executes the function Intro to C++ 4

5 3. Control Structures Most structured languages have at least 3 types of control structures simple selection if... else multiple selection switch repetition while do... while for 3.1 if statement Format: if ( <condition> ) <statements> [ else <statements> ] <statements> is either - one statement, or - a block of statements statement1... statement n eg. int grade;... if ( grade >= 50 ) cout << passed ; else cout << failed"; Conditions contain: expressions and relational operators: Symbol Usage == equal x == y!= not equal x!= y > x > y >= x >= y < x < y <= x <= y Intro to C++ 5

6 Simple conditions can be joined to larger conditions using logical operators: && logical and x>5 && y < 20 logical or x>5 y < 20! logical not!( x > 5) Example 3.1: A function returning the max of 3 numbers double max3( double a, double b. double c ) if ( a > b && a > c) return a; else if ( b > c) return b; else return c; 3.2 While Loop while ( <condition> ) <statements> evaluate condition if it is true execute statements (the body of the loop) repeat until condition is false Example 3.2 : A power function double power( double base, int exponent) // Raises base to the exponent power; exponent is a positive integer double result = 1; while ( exponent > 0 ) result = result * base; exponent = exponent 1; return result; Intro to C++ 6

7 3.3 Do-while Loop do <statements> while ( <condition> ); Same as while except that the body is executed before the condition is checked e.g. int n; cour << Enter a positive integer do cin >> n; while ( n <= 0 ); 3.4 For loop used for counter-controlled iteration for ( <initialization>; <condition>; <update> ) <statements> Example 3.4: Power function using for-statement // Raises base to the exponent power; exponent is a positive integer double power( double base, int exponent) double result = 1; for ( int i =1; i <= exponent; i++ ) result = result * base; return result; counter, known inside for loop only increment operator test; if true repeat the loop; if it is false, exit the loop Intro to C++ 7

8 3.5 More C++ operators Suppose i is an int and x is any numeric variable Operator Usage Meaning ++ i++ ++i increases i by 1 returns old value of i increases i by 1 returns new value -- i-- --i decreases i by 1 returns old value of i decreases i by 1 returns new value += x += 5 x = x + 5 -= x -= 5 x = x - 5 *= x *= 5 x = x * 5 /= x /= 5 x = x / 5 %= x %= 5 x = x % 5 Operator Precedence Operators Associativity () function call left to right right to left! left to right * / % + - << >> < <= > >= ==!= &&?: (conditional op.) right to left = += -= *= /= %= right to left, left to right Intro to C++ 8

9 3.6 Switch statement Consists of a series of case labels and optional default case Example : void print_rank( char grade ) // Get a letter grade and print the ranking: // 1st class, 2nd class, pass or fail switch ( grade ) case A : cout << "First class" ; break; // exits switch case 'B' : case 'C' : cout << "Second class" ; break; // exits switch case 'D' : cout << "Pass" ; break; case 'F' : cout << "Fail" ; break; // exits switch // exits switch default : cout << "Wrong grade" ; break; // optional break & continue Used inside loops (break is also used inside a switch ) break causes immediate exit from the loop continue skips the rest of the body of the loop and starts a new step Intro to C++ 9

10 3.7 A Complete Example: Tax culculations #include <iostream> using namespace std; const float BASIC_EXEMPT = 6800; const float LOW_INCOME = 30000; const float BASIC_TAX_RATE = float(0.3); double getincome() // Reads and returns a positive amount. If the input is negative, // it asks for another input. double income; cout << "Enter your income: "; do cin >> income; if ( income < 0 ) cout << "Amount should be positive. Enter another:"; while ( income < 0 ); return income; int getdependents() // Reads and returns a positive integer number. If the input is // negative, it asks for another input. int dependents; cout << "Enter the number of your dependents: "; do cin >> dependents; if ( dependents < 0 ) cout << "Quantity should be positive. Enter another:"; while ( dependents < 0 ); return dependents; double exempt( int dependents ) // Returns the amount that is exempted from taxation if ( dependents == 0 ) Intro to C++ 10

11 return BASIC_EXEMPT; else if (dependents <= 2) return 1.2 * BASIC_EXEMPT; else return 1.5 * BASIC_EXEMPT; double tax( double income, int dependents) // Calculates and returns the tax amount for a given // income and dependents double taxable = income - exempt( dependents); float rate; if (taxable <= 0) return 0; if (taxable <= LOW_INCOME ) rate = BASIC_TAX_RATE; else rate = 1.5 * BASIC_TAX_RATE; return taxable * rate; int get_action() // Prints menu and gets user's choice int choice; cout << endl << endl << "You may choose one of the following actions:" << endl; cout << "\t 0 Quit" << endl; cout << "\t 1 Calculate Taxes" << endl; cout << "\t 2 Calculate Exemption" << endl << endl; cout << "Please enter your choice: " ; cin >> choice; return choice; int main(int argc, char* argv[]) // The program performs two tasks: // 1. calculates the tax amount given the income and // the number of dependents. // 2. calculates the tax exemption given the number of // dependents double income; int dependents; Intro to C++ 11

12 cout << " MnM's Super Tax Calculator" << endl << endl; int action = get_action(); while ( action!= 0 ) switch (action) case 1: case 2: default: action = get_action(); // calculates the tax amount income = getincome(); dependents = getdependents(); cout << "The amount of taxes is: " << tax(income, dependents) << endl; break; // calculates the tax exemption dependents = getdependents(); cout << "The tax exemption amount is: " << exempt(dependents) << endl; break; cout << "Wrong command. Please try again. " << endl; cout << " Thank you for using MnM's Tax Calculator " << endl; return 0; Intro to C++ 12

13 Sample Output MnM's Super Tax Calculator You may choose one of the following actions: 0 Quit 1 Calculate Taxes 2 Calculate Exemption Please enter your choice: 1 Enter your income: Enter the number of your dependents: 2 The amount of taxes is: You may choose one of the following actions: 0 Quit 1 Calculate Taxes 2 Calculate Exemption Please enter your choice: 2 Enter the number of your dependents: 2 The tax exemption amount is: 8160 You may choose one of the following actions: 0 Quit 1 Calculate Taxes 2 Calculate Exemption Please enter your choice: 3 Wrong command. Please try again. You may choose one of the following actions: 0 Quit 1 Calculate Taxes 2 Calculate Exemption Please enter your choice: 0 Thank you for using MnM's Tax Calculator Press any key to continue Intro to C++ 13

14 4. Functions Function Definition: <return type> <fn name>( <parameter list>) <body> Function declaration ( or prototype) similar but without the body i.e. double power( double base, int exp ) parameter names may be omitted in a function declaration a function with no parameters that returns no value - void print_headers() Scope of a name: - portion of program where the name is known scope of a variable: - block in which it is declared scope of function parameters and local variables: - the function body 4.1 Reference Parameters We want a function swap that swaps two integers i.e. int x = 5, y = 10; swap(x, y) should x be 10 and y be 5. First attempt: void swap( int a, int b) int tmp = a; a = b; b = tmp; It does not work. The call " swap(x, y)" creates a new environment, different than caller's environment caller's environment call's environment x y 5 10 values are copied from caller to call Intro to C a b tmp

15 To do that we need to use reference parameters (not value parameters) void swap( int & a, int & b) int tmp = a; a = b; b = tmp; During a call a reference parameter is an alias of the actual argument (passed to function): caller's environment call's environment x y a b no values are copied 5 tmp We use reference parameters when: the function has to modify its arguments (i.e. swap ) the function returns a value through its argument i.e. void get_date( int& year, int& month, int& day) we want to avoid copying the arguments, but we dont want the function to change them - use references to constant objects - i.e. void foo( const double & a) a = 5; X not allowed... Intro to C++ 15

16 6. Arrays An array is a group of consecutive memory locations, all having the same name and same type. An array declaration looks like: <element type> <array name>[ <size> ]; I.e. the following declares an array throw of 5 integers (representing 5 die throws): int throw[5]; /5 dice throws This allocates the following space for throw throw To access an element of an array, we specify its position using subscripts. For instance the elements of throw are: throw[0] throw[1]... throw[4] i.e. throw throw[0] throw[1] throw[4] Note: <size> in an array declaration must be a constant. An array subscript always starts at 0. Array initialization: int a[5] = 20, 30, 10, 5, 40; int b[5] = 5; first element is 5 rest are 0 Intro to C++ 16

17 double c[] = 5, 10, 20; c has 3 elements of type double Array usage example: int throw[10] = 0; throw[0] = 5; cin >> throw[1]; throw[2] = throw[1];... // can print all the elements cout << " The outcomes are: "; for (int i =0; i<10; i++) cout << throw[i] << ", " ; cout << endl; Accessing a position outside an array produces an error. i.e. throw[15] = 5; // error throw[10] = 3; // error Cannot assign one array to another. i.e. int a[20], b[20]; // read values for a and b for (int i =0; i<20; i++) cout << "Enter next value for a and b:" ; cin >> a[i] >> b[i] ;... a = b; // Error, you cannot do that Need to assign element by element: for (int i =0; i<20; i++) a[i] = b[i] ; Intro to C++ 17

18 Passing an array to a function function parameter for array does not show size size is passed using another parameter i.e. to pass a to function f, f's prototype could be void f( int array_par[], int size) then a call to f that passes a could be: f(a, 20); arrays are passed by reference so, if f sets array_par[2] = 50; then a[2] is 50. Intro to C++ 18

19 Example 6.1 A program that collects responses how much a student spends for lunch at the SUB, and prints out the min, max and the average of the responses. #include <iostream> using namespace std; const int MAX_NO_OF_RESPONSES = 100; float max(float array[], int size) // returns the max value in an array of integers int result= array[0]; for (int i=0; i<size; i++) if ( array[i] > result ) result = array[i]; return result; float min(float array[], int size) // returns the min value in an array of integers // Write the code for this function as an exercise float average(float array[], int size) // returns the mean from an array of integers int sum= 0; for (int i=0; i<size; i++) sum += array[i]; if ( size > 0 ) return sum/size; else return 0; float get_response() Intro to C++ 19

20 // gets a response for the survey float response; cout << "Enter the amount you spend for lunch at SUB or a negative to quit: "; cin >> response; return response; int main() float poll[max_no_of_responses]; int count = 0; float response = get_response(); while ( response >= 0 ) poll[count] = response; count++; response = get_response(); cout << "\n Results of the SUB survey: \n" << "\t Max: " << max(poll, count) << endl << "\t Min: " << min(poll, count) << endl << "\t Average: " << average(poll, count) << endl; return 0; Intro to C++ 20

21 Example 6.2 : An array of points We can use an arrayof 6 points to represent a hexagon: Point hex[6]; Hex looks like: The following functions calculates the length of the i-th side and the perimeter of a hexagon: double length( Point hexar [], int i) // side 1 is from hexar[0] to hexar[1],..., side 6 is from hexar[5] to hexar[0] if ( i<1 i>6 ) cout << "Error: Not a valid side "; return 0; // left point of side i is in i-1 but position of right point depends on i lnt right = i==6? 0 : i; int xd = hexar[i-1].getx() - hexar[right].getx(); int yd = hexar[i-1].gety() - hexar[right].gety(); return sqrt(xd*xd yd*yd); double perimeter( Point hexar []) double perim = 0; for(int i=1; i<=6; i++) perim = perim+ length(hexar, i); return perim; Intro to C++ 21

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

CS2141 Software Development using C/C++ C++ Basics

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. 1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format

More information

A First Program - Greeting.cpp

A First Program - Greeting.cpp C++ Basics A First Program - Greeting.cpp Preprocessor directives Function named main() indicates start of program // Program: Display greetings #include using namespace std; int main() { cout

More information

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3 Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

More information

Name SECTION: 12:45 2:20. True or False (12 Points)

Name SECTION: 12:45 2:20. True or False (12 Points) Name SECION: 12:45 2:20 rue or False (12 Points) 1. (12 pts) Circle for true and F for false: F a) Local identifiers have name precedence over global identifiers of the same name. F b) Local variables

More information

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 2. Overview of C++ Prof. Amr Goneid, AUC 1 Overview of C++ Prof. Amr Goneid, AUC 2 Overview of C++ Historical C++ Basics Some Library

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points) Name rue or False (12 Points) 1. (12 pts) Circle for true and F for false: F a) Local identifiers have name precedence over global identifiers of the same name. F b) Local variables retain their value

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

Unit 7. 'while' Loops

Unit 7. 'while' Loops 1 Unit 7 'while' Loops 2 Control Structures We need ways of making decisions in our program To repeat code until we want it to stop To only execute certain code if a condition is true To execute one segment

More information

Chapter 2: Overview of C++

Chapter 2: Overview of C++ Chapter 2: Overview of C++ Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman C++ Background Introduced by Bjarne Stroustrup of AT&T s Bell Laboratories in

More information

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. Week 3 Functions & Arrays Gaddis: Chapters 6 and 7 CS 5301 Fall 2015 Jill Seaman 1 Function Definitions! Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements... Where

More information

CS2255 HOMEWORK #1 Fall 2012

CS2255 HOMEWORK #1 Fall 2012 CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The

More information

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF

More information

VARIABLES & ASSIGNMENTS

VARIABLES & ASSIGNMENTS Fall 2018 CS150 - Intro to CS I 1 VARIABLES & ASSIGNMENTS Sections 2.1, 2.2, 2.3, 2.4 Fall 2018 CS150 - Intro to CS I 2 Variables Named storage location for holding data named piece of memory You need

More information

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018 Week 3 Functions & Arrays Gaddis: Chapters 6 and 7 CS 5301 Spring 2018 Jill Seaman 1 Function Definitions l Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements...

More information

Chapter 1 INTRODUCTION

Chapter 1 INTRODUCTION Chapter 1 INTRODUCTION A digital computer system consists of hardware and software: The hardware consists of the physical components of the system. The software is the collection of programs that a computer

More information

C++ Programming for Non-C Programmers. Supplement

C++ Programming for Non-C Programmers. Supplement C++ Programming for Non-C Programmers Supplement ii C++ Programming for Non-C Programmers C++ Programming for Non-C Programmers Published by itcourseware, 10333 E. Dry Creek Rd., Suite 150, Englewood,

More information

Fundamentals of Programming CS-110. Lecture 2

Fundamentals of Programming CS-110. Lecture 2 Fundamentals of Programming CS-110 Lecture 2 Last Lab // Example program #include using namespace std; int main() { cout

More information

Why Is Repetition Needed?

Why Is Repetition Needed? Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable

More information

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme Chapter 4: 4.1 Making Decisions Relational Operators Simple Program Scheme Simple Program Scheme So far our programs follow a simple scheme Gather input from the user Perform one or more calculations Display

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Spring 2005 Lecture 1 Jan 6, 2005 Course Information 2 Lecture: James B D Joshi Tuesdays/Thursdays: 1:00-2:15 PM Office Hours:

More information

Introduction to Programming EC-105. Lecture 2

Introduction to Programming EC-105. Lecture 2 Introduction to Programming EC-105 Lecture 2 Input and Output A data stream is a sequence of data - Typically in the form of characters or numbers An input stream is data for the program to use - Typically

More information

C++ Programming for Non-C Programmers. Supplement

C++ Programming for Non-C Programmers. Supplement C++ Programming for Non-C Programmers Supplement C++ Programming for Non-C Programmers C++ Programming for Non-C Programmers Published by ITCourseware, 7245 S. Havana St, Suite 100, Centennial, CO 80112

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); } 1. (9 pts) Show what will be output by the cout s in this program. As in normal program execution, any update to a variable should affect the next statement. (Note: boolalpha simply causes Booleans to

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ 0.1 Introduction This is a session to familiarize working with the Visual Studio development environment. It

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl? Exercises with solutions. 1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl? #include b) What using statement do you always put at the top of

More information

Chapter 3 Problem Solving and the Computer

Chapter 3 Problem Solving and the Computer Chapter 3 Problem Solving and the Computer An algorithm is a step-by-step operations that the CPU must execute in order to solve a problem, or to perform that task. A program is the specification of an

More information

Outline. 1 About the course

Outline. 1 About the course Outline EDAF50 C++ Programming 1. Introduction 1 About the course Sven Gestegård Robertz Computer Science, LTH 2018 2 Presentation of C++ History Introduction Data types and variables 1. Introduction 2/1

More information

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

Computer Science II Lecture 1 Introduction and Background

Computer Science II Lecture 1 Introduction and Background Computer Science II Lecture 1 Introduction and Background Discussion of Syllabus Instructor, TAs, office hours Course web site, http://www.cs.rpi.edu/courses/fall04/cs2, will be up soon Course emphasis,

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 2 Monday, March 20, 2017 Total - 100 Points B Instructions: Total of 13 pages, including this cover and the last page. Before starting the exam,

More information

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is

More information

Chapter 1 Introduction to Computers and C++ Programming

Chapter 1 Introduction to Computers and C++ Programming Chapter 1 Introduction to Computers and C++ Programming 1 Outline 1.1 Introduction 1.2 What is a Computer? 1.3 Computer Organization 1.7 History of C and C++ 1.14 Basics of a Typical C++ Environment 1.20

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1 300580 Programming Fundamentals 3 With C++ Variable Declaration, Evaluation and Assignment 1 Today s Topics Variable declaration Assignment to variables Typecasting Counting Mathematical functions Keyboard

More information

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017 Loops! Loops! Loops! Lecture 5 COP 3014 Fall 2017 September 25, 2017 Repetition Statements Repetition statements are called loops, and are used to repeat the same code mulitple times in succession. The

More information

Getting started with C++ (Part 2)

Getting started with C++ (Part 2) Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Elements of C in C++ data types if else statement for loops. random numbers rolling a die

Elements of C in C++ data types if else statement for loops. random numbers rolling a die Elements of C in C++ 1 Types and Control Statements data types if else statement for loops 2 Simulations random numbers rolling a die 3 Functions and Pointers defining a function call by value and call

More information

Loops and Files. of do-while loop

Loops and Files. of do-while loop L E S S O N S E T 5 Loops and Files PURPOSE PROCEDURE 1. To introduce counter and event controlled loops 2. To work with the while loop 3. To introduce the do-while loop 4. To work with the for loop 5.

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

C++ Programming Lecture 7 Control Structure I (Repetition) Part I C++ Programming Lecture 7 Control Structure I (Repetition) Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department while Repetition Structure I Repetition structure Programmer

More information

Tutorial-2a: First steps with C++ programming

Tutorial-2a: First steps with C++ programming Programming for Scientists Tutorial 2a 1 / 18 HTTP://WWW.HEP.LU.SE/COURSES/MNXB01 Introduction to Programming and Computing for Scientists Tutorial-2a: First steps with C++ programming Programming for

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Input And Output of C++

Input And Output of C++ Input And Output of C++ Input And Output of C++ Seperating Lines of Output New lines in output Recall: "\n" "newline" A second method: object endl Examples: cout

More information

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

COMP322 - Introduction to C++ Lecture 01 - Introduction

COMP322 - Introduction to C++ Lecture 01 - Introduction COMP322 - Introduction to C++ Lecture 01 - Introduction Robert D. Vincent School of Computer Science 6 January 2010 What this course is Crash course in C++ Only 14 lectures Single-credit course What this

More information

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1 NAGERCOIL COMPUTER SCIENCE Grade: IX C++ PROGRAMMING 1 C++ 1. Object Oriented Programming OOP is Object Oriented Programming. It was developed to overcome the flaws of the procedural approach to programming.

More information

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes Distributed Real-Time Control Systems Lecture 17 C++ Programming Intro to C++ Objects and Classes 1 Bibliography Classical References Covers C++ 11 2 What is C++? A computer language with object oriented

More information

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Copyright 2011 Pearson Addison-Wesley. All rights reserved.

More information

Connecting with Computer Science, 2e. Chapter 15 Programming II

Connecting with Computer Science, 2e. Chapter 15 Programming II Connecting with Computer Science, 2e Chapter 15 Programming II Objectives In this chapter you will: Gain an understanding of the basics of high-level programming languages, using Java and C++ as examples

More information

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++. Concepts Review 1. An algorithm is a sequence of steps to solve a problem. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++. 3. A flowchart is the graphical

More information

Chapter 7 Array. Array. C++, How to Program

Chapter 7 Array. Array. C++, How to Program Chapter 7 Array C++, How to Program Deitel & Deitel Spring 2016 CISC 1600 Yanjun Li 1 Array Arrays are data structures containing related data items of same type. An array is a consecutive group of memory

More information

Name Section: M/W or T/TH. True or False (14 Points)

Name Section: M/W or T/TH. True or False (14 Points) Name Section: M/W or T/TH True or False (14 Points) 1. (14 pts) Circle T for true and F for false: T F a) In C++, a function definition should not be nested within another function definition. T F b) Static

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

More information

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana POINTERS Programación de Computadores Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana 2018-01 Pointers A pointer is a reference to

More information

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1 ELEC 330 1 Structured Programming Control Structures ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne Algorithm Development Conditional Expressions Selection Statements Loops 206_C3

More information

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition) Structures Programming in C++ Sequential Branching Repeating Loops (Repetition) 2 1 Loops Repetition is referred to the ability of repeating a statement or a set of statements as many times this is necessary.

More information

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size

More information

Introduction to C++ Introduction to C++ 1

Introduction to C++ Introduction to C++ 1 1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module

More information

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement Last Time Let s all Repeat Together 10/3/05 CS150 Introduction to Computer Science 1 1 We covered o Counter and sentinel controlled loops o Formatting output Today we will o Type casting o Top-down, stepwise

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Outline 13.1 Test-Driving the Salary Survey Application 13.2 Introducing Arrays 13.3 Declaring and Initializing Arrays 13.4 Constructing

More information

Scientific Computing

Scientific Computing Scientific Computing Martin Lotz School of Mathematics The University of Manchester Lecture 1, September 22, 2014 Outline Course Overview Programming Basics The C++ Programming Language Outline Course

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

A SHORT COURSE ON C++

A SHORT COURSE ON C++ Introduction to A SHORT COURSE ON School of Mathematics Semester 1 2008 Introduction to OUTLINE 1 INTRODUCTION TO 2 FLOW CONTROL AND FUNCTIONS If Else Looping Functions Cmath Library Prototyping Introduction

More information

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY Pages 800 to 809 Anna Rakitianskaia, University of Pretoria STATIC ARRAYS So far, we have only used static arrays The size of a static array must

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

More information

Introduction to C ++

Introduction to C ++ Introduction to C ++ Thomas Branch tcb06@ic.ac.uk Imperial College Software Society October 18, 2012 1 / 48 Buy Software Soc. s Free Membership at https://www.imperialcollegeunion.org/shop/ club-society-project-products/software-products/436/

More information

Lab # 02. Basic Elements of C++ _ Part1

Lab # 02. Basic Elements of C++ _ Part1 Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

CHAPTER 3 BASIC INSTRUCTION OF C++

CHAPTER 3 BASIC INSTRUCTION OF C++ CHAPTER 3 BASIC INSTRUCTION OF C++ MOHD HATTA BIN HJ MOHAMED ALI Computer programming (BFC 20802) Subtopics 2 Parts of a C++ Program Classes and Objects The #include Directive Variables and Literals Identifiers

More information

Introducing C++ to Java Programmers

Introducing C++ to Java Programmers Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:

More information

CS 115 Midterm 2A Solutions

CS 115 Midterm 2A Solutions CS115Midterm2ASolutions November13,2008 Rules Youmustbrieflyexplainyouranswerstoreceivepartialcredit. Whenasnippetofcodeisgiventoyou,youcanassumethatthecodeis enclosedwithinsomefunction,evenifnofunctiondefinitionisshown.you

More information

Today s Learning Objectives

Today s Learning Objectives Today s Learning Objectives 15-123 Systems Skills in C and Unix We will Review ints and modular arithmetic Learn basic Data types and Formats How Conditionals and loops work How Arrays are defined, accessed,

More information

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char Week 1 Operators, Data Types & I/O Gaddis: Chapters 1, 2, 3 CS 5301 Fall 2016 Jill Seaman Programming A program is a set of instructions that the computer follows to perform a task It must be translated

More information

In this chapter you will learn:

In this chapter you will learn: 1 In this chapter you will learn: Essentials of counter-controlled repetition. Use for, while and do while to execute statements in program repeatedly. Use nested control statements in your program. 2

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

More information

Lab Instructor : Jean Lai

Lab Instructor : Jean Lai Lab Instructor : Jean Lai Group related statements to perform a specific task. Structure the program (No duplicate codes!) Must be declared before used. Can be invoked (called) as any number of times.

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Week 3: Pointers (Part 2)

Week 3: Pointers (Part 2) Advanced Programming (BETC 1353) Week 3: Pointers (Part 2) Dr. Abdul Kadir abdulkadir@utem.edu.my Learning Outcomes: Able to describe the concept of pointer expression and pointer arithmetic Able to explain

More information

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup starting in 1979 based on C Introduction to C++ also

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++ CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,

More information