LAB: INTRODUCTION TO FUNCTIONS IN C++
|
|
- Imogen Shaw
- 6 years ago
- Views:
Transcription
1 LAB: INTRODUCTION TO FUNCTIONS IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2014 VERSION 4.0
2 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 2 Introduction This lab will provide students with an introduction to the fundamentals of user-defined functions in C++. The focus of this lab is on how to solve simple problems using C++ data types, variables, and arithmetic operations. At the end of this module, students will Be able to solve simple problems using C++ Understand the structure of a simple C++ program Understand the basic C++ data types Understand and apply the basic concepts behind C++ variables Understand and be able to apply simple arithmetic expressions using C++ variables Understand and apply the basic concepts behind C++ arithmetic operators Understand and be able to apply simple C++ arithmetic expressions These exercises have two different types of answers. Some questions ask for answers to specific questions; you should collect these answers in a Microsoft Word document. Other exercises ask you to write code; for these exercises, structure your storage drive in the following manner. There should be a palms folder, and within that folder there should be a LabFunctions folder. All coding exercises (and related folders) for this lesson should be placed in the LabFunctions folder. Let s begin! Part 1: Programming With Functions in C++ We've said before that C++ code is broken down into small code segments called functions. These functions, when combined, form a program. Until now we have only dealt with one function called main; however, we can define our own functions to make them easier to read and to maintain. In addition, C++ provides us with a number of useful functions to perform common tasks, like finding square roots of numbers and converting between different numerical representations. In this lab, we will learn how to use some of the built-in C++ functions to simplify our programs, as well as learn how to create our own. In the future, our programs will grow to include a larger number of functions. Functions in C++ Functions are defined as a unit of computational abstraction. In programming, as in life, very often we want to ignore the small details and concentrate on the big picture. Functions allow us to do just that, by allowing us to use previously written code to perform a task without worrying about how the task is performed. For instance, in the following two lines of code:
3 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 3 sum = pow(side1, 2) + pow(side2, 2); side3 = sqrt(sum); This code uses two functions that C++ provides in the <cmath> standard library. The first line uses the pow function to compute the result of raising a number to a power (in this case, the value of side1 raised to the second power). We don't know how the function works, all we know is that it will do a certain task and give us a result we desire. Likewise, the second line uses sqrt to compute the square root of a given number (in this case, the value of sum). When calling a function in C++, the function name is written first, followed by the inputs in parentheses. For example, suppose the variable sum contained the value 9. The function call or invocation sqrt(sum) would return the value 3. Similarly, the call sqrt(25) would return the value 5, and pow(3, 2) would return the value 3 2 = 9. A function call can appear anywhere in a C++ expression. When an expression containing a function call is evaluated, the return value for that call is substituted into the expression. For example, in the assignment "value = sqrt(4);", the call on the right-hand side would evaluate to 2, and so the variable value would be assigned the value 2. In order to use a function effectively, we need to know the type of data that is returned by the function. We can only use C++ functions in expressions where data of the same type as the function's return type is needed. For instance, the following code would not make sense: char my_char; my_char = sqrt(30); Because sqrt returns a real number, it does not make sense to try and place that result into a variable of type character. Watch and listen to the What is a C++ Function? podcast before proceeding:
4 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 4 Part 2: User-Defined Functions Until now we have only used functions that were either (a) required by the language, or (b) provided by the C++ Standard Library of functions. The standard library functions help to simplify the programmer's task in two major ways. First, functions help to minimize the amount of detail of which the programmer must keep track. Since the sqrt function is available, the programmer does not need to remember the sequence of steps involved in computing the square root. He or she only needs to remember how to call the sqrt function. Second, functions help to minimize the size and complexity of code. Once the sqrt function has been defined, a single call to this function will suffice to compute a square root. Since the number of steps required to otherwise compute the square root would be considerable, this can represent a significant savings in the complexity of code. The C++ Standard Library is designed to provide the programmer with a set of common tools which can be used without worrying about the nitty-gritty details of how they do their job. These predefined functions represent a collection of useful, general purpose abstractions. In addition to these, you are able to define new abstractions by defining your own functions. Any computation that you find especially useful can be encapsulated as a function. Once defined and loaded into a C++ file, your function can be called just like any predefined function. Therefore, your function may be viewed as extending the capabilities of the C++ language itself. As an example, consider the formula for converting a temperature in degrees Fahrenheit (F) to degrees Celsius (C): C = (5.0 / 9.0) * (F - 32) We can use this formula to create a C++ program. If converting temperatures was a task that you were to perform relatively often in other programs, you would spend a lot of time remembering and retyping this formula. Alternatively, you could encapsulate this computation in a function and save it in a C++ file. Any time you wanted to convert temperatures, you could then add this C++ file to your project and call the function. You wouldn't need to remember the formula anymore, just the name of the function and how to call it. The following is the definition of a C++ function that performs the temperature conversion. A description of the key parts of this definition is given below:
5 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 5 / FUNCTION NAME: fahrtocelsius PARAMETERS: double fahr -- The degrees in Fahrenheit RETURN TYPE: double PURPOSE: Converts a given degree reading from F to C. / double fahrtocelsius(double fahr) { variable declarations and initialization double celsius = 0.0; convert the value from F to C... celsius = (5.0 / 9.0) * (fahr - 32); } return the converted value... return celsius; The first eight lines are a function header comment, describing the important aspects of the function (name, inputs, output, and purpose). You should always have comments in your functions to improve readability. The next line is the function header. The header specifies that you are defining a function named fahrtocelsius with one input. The input value is represented by a variable inside of the parentheses, also known as a parameter This variable name (fahr) is preceded by the data type of that variable (in this case, double). When the function is called, the input specified in the function call is assigned to the parameter for use in the function's computation. For example, for the call fahrtocelsius(212), the parameter fahr would be assigned the value 212. Thus, the value 212 would be used in the function code as the value for fahr, resulting in the function returning the value 100. The actual code that carries out the computation of the function is enclosed in curlybraces and is called the function body. In this example, there is only three C++ code statements, but functions can contain any number of statements. A return statement is a special C++ statement that specifies the value that should be returned by the function. It consists of the keyword return followed by an expression. When a return statement is executed, the expression is evaluated and the resulting value is returned as the value of the function call. In order to make a user-defined function accessible in a C++ program, it must be included in the C++ project. This can be accomplished in two ways. When the function is specific to that program only, its definition can be inserted directly into the.cpp file in the project; for instance,
6 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 6 we could have a single file in our fahrtocelsius project with two functions: main and fahrtocelsius. Alternatively, general-purpose function definitions can be entered into a separate library file and loaded into your project. In the future, we will see how to do this. Exercise #1: Create a new C++ code file called converttemp.cpp and type the following code into the file: / Name: converttemp.cpp Author: Jeffrey A. Stone Purpose: Program which converts a Fahrenheit reading to Celsius. / #include <iostream> using namespace std; / FUNCTION NAME: fahrtocelsius PARAMETERS: double fahr -- The degrees in Fahrenheit RETURN TYPE: double PURPOSE: Converts a given degree reading from F to C. / double fahrtocelsius(double fahr) { variable declarations and initialization double celsius = 0.0; convert the value from F to C... celsius = (5.0 / 9.0) * (fahr - 32); } return the converted value... return celsius; / FUNCTION NAME: main PARAMETERS: None RETURN TYPE: int PURPOSE: Entry point for the application. /
7 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 7 int main() { variable declaration and initialization double fahr_temp = 0.0; variable declaration and initialization double cel_temp = 0.0; prompt the user... cout << "Enter a reading in fahrenheit degrees : "; input the value from the user... cin >> fahr_temp; convert... cel_temp = fahrtocelsius(fahr_temp); output the temperature, in both units... cout << "You entered " << fahr_temp << " F degrees." << endl << "That is " << cel_temp << " C degrees." << endl; } return success to the Operating System... return 0; Compile and run the program, and verify that it works as it should. Next, watch and listen to the Walking Through a Function Call in C++ podcast before proceeding. This podcast will present a dynamic view of how the above program executes.
8 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 8 Exercise #2: Add a new function to converttemp.cpp called celsiustofahr. Modify the code in main to input two values: the degree reading, along with an F or a C, with the two values separated by a space. If the user inputs an F, the degree reading is in Fahrenheit; your program should convert the degrees to Celsius and output the result to the screen. If the user inputs a C, the degree reading is in Celsius; your program should convert the degrees to Fahrenheit and output the result to the screen. Don't forget to properly comment your code! Hint: You case use a predefined function called toupper to convert a character from lowercase to uppercase. This may prove useful for your conditional tests. For example, simplechar = toupper(simplechar); takes the value of simplechar and (if it is an alphabetic character) returns the uppercase version of the letter. Simply add #include <cctype> right below #include <iostream> to gain access to the function. Local Variables Notice from Exercise 1 that the function fahrtocelsius contains a single variable declaration, namely double celsius = 0.0; The first line in this function is a variable declaration specifying that the new variable celsius is to be used in the function. Declaring variables in this way signifies that they are local to the function, meaning they will only exist inside of the function. In this sense, local variables are similar to parameters. Declaring a local variable tells the C++ compiler that you are going to use it as temporary storage while computing the function value, and that the storage should go away i.e. be returned to the pool of available storage when execution of the function is complete. In all functions, including main, variables have a defined scope, the area(s) and time for which they are allowed to be used. In the case of C++ functions, this scope is limited to the code statements within the beginning and ending brackets ({ }). The lifetime of these variables (i.e. the time from which memory is allocated by the system to the time in which the memory is given back) is the time for which the function is executing. Global variables are variables declared outside of any function. Global variables are thus accessible by any function within the code file. While the C++ language permits this functionality, it is generally considered poor programming practice to declare variables with global scope. Do not declare global variables in any program you create in this course.
9 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 9 Part 3: Function Calling Sequence Whenever a function is called, a specific sequence of events takes place. If you understand this sequence, it should be possible to trace the execution of any function and ascertain its behavior. For example, consider the following program that computes the sum of a range of integers. / Name: sumnumbers.cpp Author: Jeffrey A. Stone Purpose: Sums the numbers in a user-defined sequence. / #include <iostream> using namespace std; / FUNCTION NAME: sumnumbers PARAMETERS: long min -- The lower bound value. long max -- The upper bound value. RETURN TYPE: long PURPOSE: Sums the numbers from low to high. / long sumnumbers(long min, long max) { long counter = 0; keeps a count of the number of loops long sum = 0; keeps a running sum of values set the counter to the min value... counter = min; while (counter <= max) { Add to our running total... sum = sum + counter; } Add to lcounter... counter = counter + 1; } return the sum of the numbers in the sequence... return sum;
10 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 10 / FUNCTION NAME: main PARAMETERS: None RETURN TYPE: int PURPOSE: Entry point for the application. / int main() { long low = 0, high = 0; stores the input values cout << "Enter two integers separated by a space, "; cout << "smallest integer first : "; cin >> low >> high; cout << "\nthe sum from " << low << " to " << high; cout << " is " << sumnumbers(low, high) << "\n"; prompt prompt input output output } return 0; return "success" to the operating system When the sumnumbers function is called in the main function, the following events occur: 1. Execution shifts to the sumnumbers function. 2. The inputs to the function are evaluated first, with the parameters min and max assuming the values contained within low and high, respectively. 3. Within the function, new memory cells are allocated for the parameters min and max. These memory cells are assigned the values of the corresponding arguments from the call: the values contained within the variables low and high, respectively. Throughout the function, any references to these parameters will be associated with these memory cells. 4. Memory cells are next allocated (created) for each local variable: counter and sum. Similarly, any references within the function to these local variable names will be associated with these memory cells. They are initialized with a zero value. 5. The statements in the function are executed in order, assigning sum the value of the sum of the integers from min to max. 6. When the return statement is reached, the expression in the statement is evaluated, yielding the value contained within sum. 7. After computing the return value, the execution of the function is over. Since the local variables exist only inside the function itself, the memory cells associated with the variables are de-allocated, i.e., made available for other uses. 8. Similarly, the memory cells associated with parameters are de-allocated.
11 PALMS MODULE 2 LAB: FUNCTIONS IN C Once the memory cells have been freed, the value in sum can be returned as the value of the function call. In this case, the value returned by the function replaces the function call in the assignment, and so that value is output to the screen. In general, the calling sequence for functions is as follows: 1. The arguments in the function call are evaluated. 2. Execution shifts to the function being called. 3. Memory cells are allocated (created) for each parameter in the function, and the values of the corresponding arguments are assigned to these memory cells. 4. Memory cells are allocated (created) for each local variable. 5. The statements in the body of the function are executed in order. 6. When a return statement is encountered, the expression is evaluated. 7. Memory cells associated with the local variables are de-allocated (destroyed). 8. Memory cells associated with the parameters are de-allocated (destroyed). 9. Upon return, the value of the expression in the return statement replaces the function call in whatever expression it appears in. Watch and listen to the Function Calling Sequence podcast before proceeding: Exercise #3: Create a new C++ workspace called incometax. Your main function should prompt the user for his/her gross income and itemized deduction (both double values). Construct a function called incometax which computes the tax due using the input values (gross income and itemized deduction) as follows:
12 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 12 The taxpayer's taxable income is determined by subtracting the taxpayer s deduction from the taxpayer's gross income. Total tax is determined by multiplying the taxable income by the tax rate (0.17). Your main function should call your incometax function to compute the total tax due, giving it appropriate arguments. Your incometax function should return the total tax due back to your main function. Finally, your main function should output the tax due to the screen with a descriptive message. Please watch and listen to the Techniques for User-Defined Functions in C++ podcast before proceeding. This podcast will present a description of how to create input, processing/computation, and output functions. These tips will be used heavily in this course. Part 4: Calculating the Energy Produced by a Wind Generator Suppose you wanted to harness to power of wind to generate electricity. One question you might want to ask is: what is the amount of power my wind generator can produce? To answer this question, you will need at least the following information: The average wind speed in your backyard (in m/s) The operating efficiency of your wind generator (in %) The radius of the blades on your wind generator (in meters)
13 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 13 To compute the maximum power output for your wind generator, you will need the following math formulas: A = πr 2, which represents the cross-sectional area of a circle (π = ). P max = 1 2 ρav3, which calculates the maximum available power given the wind speed (ν), cross-sectional area of the blades (A), and the density of the air (ρ= 1.2 kg/m 3 ). Once you have the maximum available power, computing the actual amount of power (not the maximum) produced by the wind generator is a matter of determining the amount of power based on the operating efficiency. Exercise #4: Create a program to compute the amount of power produced by a wind generator. Your program should take three double precision inputs (see the discussion above) before performing its calculations. Create two functions other than main in your program. Both of these functions will return a double value. One function should be called computearea and should take one double parameter named radius. The other function should be called computemaximumpower and should take two double parameters (named area and wind_speed). You will need to call these functions from main function. Your output should include two calculated results the maximum power output and the actual power output. All numeric amounts should be precise to two decimal places. Remember: a percentage is really a number between 0 and 1, inclusive. Here are few sample tests you can run to check if your program is working correctly: Test Case #1: Enter the Average Wind Speed (in m/s): 5.0 Enter the Operating Efficiency [0...1]: 0.98 Enter the Blade Radius (in meters): 2.0 Maximum Power = , Actual Power = Test Case #2: Enter the Average Wind Speed (in m/s): Enter the Operating Efficiency [0...1]: 0.10 Enter the Blade Radius (in meters): 3.0 Maximum Power = , Actual Power =
14 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 14 Part 5: Vocabulary Words You will be assessed on your knowledge of the following terms and concepts as well as the function concepts discussed in this document. As a result, you are encouraged to review these terms in the preceding document. Argument a value that is provided in a function call to fill in a parameter. Arguments provide functions with the data necessary to complete its task. Comment a statement, sentence, or phrase which describes a piece of code. Comments are ignored by the compiler and exist only to document the C++ code with a more natural language (e.g. English). In C++, single-line comments begin with. Multi-line comments are bounded with /* and */. C++ Standard Library a set of common tools which can be used in any program. These predefined functions and classes represent a collection of useful, general purpose abstractions. Function a specific unit of code in C++ containing a header and a body. Functions can be called by other functions to perform tasks, and can return a value back to the caller. Function Body The actual code that carries out the computation of the function; that part of the function which is enclosed in curly-braces. Function Call the act of invoking a function. A function call is made by using the function name and providing the function with any necessary arguments. Function Header the first line of a function, containing the function name, the parameter list, and the type of data returned by the function. Local Variable a variable declared within a set of { }, such as a function body. Local variables can only be used within that set of { }. Declaring a local variable tells the C++ compiler that you are going to use it as temporary storage while computing the function value, and that the storage should go away i.e. be returned to the pool of available storage when execution of the function is complete. Parameter a value that a function expects to be given when the function is called. A function can have 0 or more parameters. These are placeholders that must be filled in by arguments when the function is called. As a result, parameters can take on different
15 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 15 values each time the function is called. Parameters act as local variables within the function body. Parameter List a set of parameters, enclosed in parentheses within the function header. Parameter lists follow the function name in a function header. Each parameter is declared using a data type and a name, much like a variable declaration. The parameter declarations in the list are separated by commas. Return Statement a special C++ statement that specifies the value that should be returned by the function; begins with the keyword return. Scope the visibility or lifetime of a variable. All variables have a defined area and time for which they are allowed to be used. In the case of C++ functions, this scope is limited to the code statements within the beginning and ending brackets ({ }). The lifetime of these variables (i.e. the time from which memory is allocated by the system to the time in which the memory is given back) is the time for which the function is executing.
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 informationLAB: WHILE LOOPS IN C++
LAB: WHILE LOOPS IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2014 VERSION 4.0 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 2 Introduction This lab will provide students with an introduction
More informationExpressions, Input, Output and Data Type Conversions
L E S S O N S E T 3 Expressions, Input, Output and Data Type Conversions PURPOSE 1. To learn input and formatted output statements 2. To learn data type conversions (coercion and casting) 3. To work with
More informationFunctions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92
L E S S O N S E T 6.2 Functions that Return a Value PURPOSE PROCEDURE 1. To introduce the concept of scope 2. To understand the difference between static, local and global variables 3. To introduce the
More informationReview. Modules. CS 151 Review #6. Sample Program 6.1a:
Review Modules A key element of structured (well organized and documented) programs is their modularity: the breaking of code into small units. These units, or modules, that do not return a value are called
More informationLAB: FOR LOOPS IN C++
LAB: FOR LOOPS IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2014 VERSION 4.0 PALMS MODULE 2 LAB: FOR LOOPS IN C++ 2 Introduction This lab will provide students with an introduction to
More informationObjectives. In this chapter, you will:
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 arithmetic expressions Learn about
More informationCS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.
REVIEW cout Statement The cout statement invokes an output stream, which is a sequence of characters to be displayed to the screen. cout
More informationLab 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 informationTOPIC 2 INTRODUCTION TO JAVA AND DR JAVA
1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared
More informationBinomial pricer (1.1)
1 Binomial pricer 1.1 Program shell 1.2 Entering data 1.3 Functions 1.4 Separate compilation 1.5 CRR pricer 1.6 Pointers 1.7 Function pointers 1.8 Taking stock In the binomial model the prices of assets
More informationGE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004
GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 Functions and Program Structure Today we will be learning about functions. You should already have an idea of their uses. Cout
More informationChapter 2 Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion
More informationBasic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces
Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationChapter 2. Outline. Simple C++ Programs
Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.
More informationC++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh
C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh CHAPTER TWO: Fundamental Data Types Chapter Goals In this chapter, you will learn how to work with numbers and text,
More informationChapter 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 information6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions
Chapter 6: 6.1 Functions Introduction to Functions What Is A Function? Why Functions? We ve been using functions ( e.g. main() ). C++ program consists of one or more functions Function: a collection of
More informationComputer 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 informationFunction Call Example
Function Call Example A Function Call Example (1) ch 3-25 A Function Call Example (2) ch 3-26 Alternative Function Declaration Recall: Function declaration is "information for compiler Compiler only needs
More informationdownload instant at Introduction to C++
Introduction to C++ 2 Programming: Solutions What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would
More informationCSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York
CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this
More informationREVIEW. The C++ Programming Language. CS 151 Review #2
REVIEW The C++ Programming Language Computer programming courses generally concentrate on program design that can be applied to any number of programming languages on the market. It is imperative, however,
More information1. In C++, reserved words are the same as predefined identifiers. a. True
C++ Programming From Problem Analysis to Program Design 8th Edition Malik TEST BANK Full clear download (no formatting errors) at: https://testbankreal.com/download/c-programming-problem-analysis-program-design-8thedition-malik-test-bank/
More informationFundamentals 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 informationObjectives. 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 informationChapter 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 informationChapter 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 informationLab # 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 informationSuperior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.6
Superior University Department of Electrical Engineering CS-115 Computing Fundamentals Experiment No.6 Pre-Defined Functions, User-Defined Function: Value Returning Functions Prepared for By: Name: ID:
More informationProgramming for Engineers Introduction to C
Programming for Engineers Introduction to C ICEN 200 Spring 2018 Prof. Dola Saha 1 Simple Program 2 Comments // Fig. 2.1: fig02_01.c // A first program in C begin with //, indicating that these two lines
More information19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd
19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd Will you walk a little faster? said a whiting to a snail, There s a porpoise close behind us, and he s treading
More informationFunctions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.
Lab 4 Functions Introduction: A function : is a collection of statements that are grouped together to perform an operation. The following is its format: type name ( parameter1, parameter2,...) { statements
More informationc) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.
2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C
More informationVARIABLES & 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 information2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program
Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program
More informationModule 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)
Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Module 10A Lecture - 20 What is a function?
More informationLecture 3 Tao Wang 1
Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers
More information2 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 informationWeek 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.
Week 2: Console I/O and Operators Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.1) CS 1428 Fall 2014 Jill Seaman 1 2.14 Arithmetic Operators An operator is a symbol that tells the computer to perform specific
More informationC++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.
EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic
More informationIntroduction to the C++ Programming Language
LESSON SET 2 Introduction to the C++ Programming Language OBJECTIVES FOR STUDENT Lesson 2A: 1. To learn the basic components of a C++ program 2. To gain a basic knowledge of how memory is used in programming
More informationChapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 4 Procedural Abstraction and Functions That Return a Value 1 Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables
More informationProgram Organization and Comments
C / C++ PROGRAMMING Program Organization and Comments Copyright 2013 Dan McElroy Programming Organization The layout of a program should be fairly straight forward and simple. Although it may just look
More informationIn this chapter you ll learn:
Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd Will you walk a little faster? said a whiting to a snail, There s a porpoise close behind us, and he s treading on
More informationFaculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions
Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2013 C++ Programming Language Lab # 6 Functions C++ Programming Language Lab # 6 Functions Objective: To be familiar with
More informationChapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++
Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure
More informationThe 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 informationHonors Computer Science C++ Mr. Clausen Program 4A, 4B, 4C (4D, 4G)
Honors Computer Science C++ Mr. Clausen Program 4A, 4B, 4C (4D, 4G) Program 4A: Function: Comments And Output 10 points Write a program that practices comments, output, and void functions. Save the program
More informationEngineering Problem Solving with C++, Etter/Ingber
Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input
More informationUnderstanding main() function Input/Output Streams
Understanding main() function Input/Output Streams Structure of a program // my first program in C++ #include int main () { cout
More informationIntroduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)
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
More informationHonors Computer Science C++ Mr. Clausen Program 6A, 6B, 6C, & 6G
Honors Computer Science C++ Mr. Clausen Program 6A, 6B, 6C, & 6G Special Note: Every program from Chapter 4 to the end of the year needs to have functions! Program 6A: Celsius To Fahrenheit Or Visa Versa
More informationSpecial Section: Building Your Own Compiler
cshtp6_19_datastructures_compiler.fm Page 1 Tuesday, February 14, 2017 10:31 AM 1 Chapter 19 Special Section: Building Your Own Compiler In Exercises8.31 8.33, we introduced Simpletron Machine Language
More informationChapter 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 informationComputer Programming
Computer Programming Dr. Deepak B Phatak Dr. Supratik Chakraborty Department of Computer Science and Engineering Session: Structure of a Simple C++ Program Dr. Deepak B. Phatak & Dr. Supratik Chakraborty,
More informationUNIT- 3 Introduction to C++
UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage
More informationMultiple 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 informationCSc Introduction to Computing
CSc 10200 Introduction to Computing Lecture 2 Edgardo Molina Fall 2011 - City College of New York Thursday, September 1, 2011 Introduction to C++ Modular program: A program consisting of interrelated segments
More informationCpt S 122 Data Structures. Introduction to C++ Part II
Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function
More informationLecture 2 Tao Wang 1
Lecture 2 Tao Wang 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common programming errors
More informationBITG 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 informationReview: 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 informationCCBC Math 081 Order of Operations Section 1.7. Step 2: Exponents and Roots Simplify any numbers being raised to a power and any numbers under the
CCBC Math 081 Order of Operations 1.7 1.7 Order of Operations Now you know how to perform all the operations addition, subtraction, multiplication, division, exponents, and roots. But what if we have a
More informationSuperior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.5. for loop and do-while loop
Superior University Department of Electrical Engineering CS-115 Computing Fundamentals Experiment No.5 for loop and do-while loop Prepared for By: Name: ID: Section: Semester: Total Marks: Obtained Marks:
More informationDepartment of Computer and Mathematical Sciences. Lab 10: Functions. CS 1410 Intro to Computer Science with C++
_ Unit 2: Programming in C++, pages 1 of 8 Department of Computer and Mathematical Sciences CS 1410 Intro to Computer Science with C++ 10 Lab 10: Functions Objectives: The objective of this lab is to understand
More informationChapter 3 - Functions
Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number
More informationHonors Computer Science C++ Mr. Clausen Program 3A, 3B, 3C
Honors Computer Science C++ Mr. Clausen Program 3A, 3B, 3C Program 3A Cone Heads (25 points) Write a program to calculate the volume and surface area of a right circular cone. Allow the user to enter values
More informationCS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise
More informationProgramming 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 informationConcepts 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 information4. Java Project Design, Input Methods
4-1 4. Java Project Design, Input Methods Review and Preview You should now be fairly comfortable with creating, compiling and running simple Java projects. In this class, we continue learning new Java
More informationMicrosoft Excel Level 2
Microsoft Excel Level 2 Table of Contents Chapter 1 Working with Excel Templates... 5 What is a Template?... 5 I. Opening a Template... 5 II. Using a Template... 5 III. Creating a Template... 6 Chapter
More informationAdd Subtract Multiply Divide
ARITHMETIC OPERATORS if AND if/else AND while LOOP Order of Operation (Precedence Part 1) Copyright 2014 Dan McElroy Add Subtract Multiply Divide + Add - Subtract * Multiply / Divide = gives the quotient
More informationIntroductionto C++ Programming
What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the most fun? Peggy Walker Take some more
More information1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary
Topic 2 1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary Arithmetic Operators C++ has the same arithmetic operators as a calculator:
More informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
More informationEE 109 Lab 8a Conversion Experience
EE 109 Lab 8a Conversion Experience 1 Introduction In this lab you will write a small program to convert a string of digits representing a number in some other base (between 2 and 10) to decimal. The user
More informationFull file at C How to Program, 6/e Multiple Choice Test Bank
2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,
More informationLAB: STRUCTURES, ARRAYS,
LAB: STRUCTURES, ARRAYS, AND FILES IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2008-2016 VERSION 3.3 PALMS MODULE 2 LAB: STRUCTURES, ARRAYS, AND FILES IN C++ 2 Introduction This lab
More informationQuestion 2. [5 points] Given the following symbolic constant definition
CS 101, Spring 2012 Mar 20th Exam 2 Name: Question 1. [5 points] Determine which of the following function calls are valid for a function with the prototype: void drawrect(int width, int height); Assume
More informationCHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.
More informationCSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions
CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions User Defined Functions In previous labs, you've encountered useful functions, such as sqrt() and pow(), that were created by other
More informationBy the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program
1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize
More informationUnit 1 Lesson 4. Introduction to Control Statements
Unit 1 Lesson 4 Introduction to Control Statements Essential Question: How are control loops used to alter the execution flow of a program? Lesson 4: Introduction to Control Statements Objectives: Use
More information3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.
1 3. Functions 1. What are the merits and demerits of modular programming? Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.
More informationComputer Programming & Problem Solving ( CPPS ) Turbo C Programming For The PC (Revised Edition ) By Robert Lafore
Sir Syed University of Engineering and Technology. Computer ming & Problem Solving ( CPPS ) Functions Chapter No 1 Compiled By: Sir Syed University of Engineering & Technology Computer Engineering Department
More informationCISC 1110 (CIS 1.5) Introduc2on to Programming Using C++
CISC 1110 (CIS 1.5) Introduc2on to Programming Using C++ Spring 2012 Instructor : K. Auyeung Email Address: Course Page: Class Hours: kenny@sci.brooklyn.cuny.edu hbp://www.sci.brooklyn.cuny.edu/~kenny/cisc1110
More informationLESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long
LESSON 5 ARITHMETIC DATA PROCESSING The arithmetic data types are the fundamental data types of the C language. They are called "arithmetic" because operations such as addition and multiplication can be
More informationLecture 05 I/O statements Printf, Scanf Simple statements, Compound statements
Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple
More information7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING
KEY CONCEPTS COMP 10 EXPLORING COMPUTER SCIENCE Lecture 2 Variables, Types, and Programs Problem Definition of task to be performed (by a computer) Algorithm A particular sequence of steps that will solve
More informationExercise: Inventing Language
Memory Computers get their powerful flexibility from the ability to store and retrieve data Data is stored in main memory, also known as Random Access Memory (RAM) Exercise: Inventing Language Get a separate
More informationComputer Science & Engineering 150A Problem Solving Using Computers
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Stephen Scott (Adapted from Christopher M. Bourke) 1 / 41 Fall 2009 Chapter 3 3.1 Building Programs from Existing Information
More informationChapter 1 - What s in a program?
Chapter 1 - What s in a program? I. Student Learning Outcomes (SLOs) a. You should be able to use Input-Process-Output charts to define basic processes in a programming module. b. You should be able to
More informationGovernment Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING
Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++
More informationIntroduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays
Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #43 Multidimensional Arrays In this video will look at multi-dimensional arrays. (Refer Slide Time: 00:03) In
More informationChapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved
Chapter Four: Loops Slides by Evan Gallagher The Three Loops in C++ C++ has these three looping statements: while for do The while Loop while (condition) { statements } The condition is some kind of test
More informationIntroduction 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