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)

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

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

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

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.

A First Program - Greeting.cpp

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

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

Multiple Choice (Questions 1 13) 26 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)

CSCE 110 PROGRAMMING FUNDAMENTALS

Computer Programming : C++

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

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

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

Unit 7. 'while' Loops

Chapter 2: Overview of C++

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

CS2255 HOMEWORK #1 Fall 2012

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

VARIABLES & ASSIGNMENTS

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

Chapter 1 INTRODUCTION

C++ Programming for Non-C Programmers. Supplement

Fundamentals of Programming CS-110. Lecture 2

Why Is Repetition Needed?

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

IS 0020 Program Design and Software Tools

Introduction to Programming EC-105. Lecture 2

C++ Programming for Non-C Programmers. Supplement

BITG 1233: Introduction to C++

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

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

CS242 COMPUTER PROGRAMMING

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

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

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

Chapter 3 Problem Solving and the Computer

Outline. 1 About the course

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

6.096 Introduction to C++ January (IAP) 2009

Computer Science II Lecture 1 Introduction and Background

CSCE 206: Structured Programming in C++

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

Chapter 1 Introduction to Computers and C++ Programming

Introduction to C++ Systems Programming

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

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

Getting started with C++ (Part 2)

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

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

Loops and Files. of do-while loop

Programming. C++ Basics

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

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

The C++ Language. Arizona State University 1

Input And Output of C++

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)

COMP322 - Introduction to C++ Lecture 01 - Introduction

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

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

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

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

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

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

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

Introduction to Programming

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

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

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

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

Introduction to C++ Introduction to C++ 1

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

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

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

CE221 Programming in C++ Part 1 Introduction

Chapter 2: Basic Elements of C++

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Scientific Computing

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

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

A SHORT COURSE ON C++

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

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

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

Introduction to C ++

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

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:

CHAPTER 3 BASIC INSTRUCTION OF C++

Introducing C++ to Java Programmers

CS 115 Midterm 2A Solutions

Today s Learning Objectives

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

In this chapter you will learn:

Chapter 2: Introduction to C++

Lab Instructor : Jean Lai

1 Lexical Considerations

Week 3: Pointers (Part 2)

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

2 nd Week Lecture Notes

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

Transcription:

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

> 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

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

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

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

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

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

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

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

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

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

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

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: 60000 Enter the number of your dependents: 2 The amount of taxes is: 23328 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

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 5 10 10 5 Intro to C++ 14 5 a b tmp

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 5 10 10 5 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

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

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

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

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

// 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

Example 6.2 : An array of points We can use an arrayof 6 points to represent a hexagon: Point hex[6]; Hex looks like: 0 1 2 3 4 5 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