Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

Similar documents
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.

Superior 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.6

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

LAB 4.1 Relational Operators and the if Statement

Programming Language. Functions. Eng. Anis Nazer First Semester

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.1

CS242 COMPUTER PROGRAMMING

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

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

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

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

BITG 1233: Introduction to C++


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

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

I/O Streams and Standard I/O Devices (cont d.)

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

Definition Matching (10 Points)

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

Expressions, Input, Output and Data Type Conversions

Chapter 3 Problem Solving and the Computer

Functions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 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

Lab Instructor : Jean Lai

LAB 7.1 Working with One-Dimensional Arrays

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Chapter 3: Input/Output

Engineering Problem Solving with C++, Etter/Ingber

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

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

CSCE Practice Midterm. Data Types

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Week 3: File I/O and Formatting 3.7 Formatting Output

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

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

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 4 - Notes Control Structures I (Selection)

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

CS2255 HOMEWORK #1 Fall 2012

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

Computer Engineering Department CMPE110 Midterm Sample Questions, 2017/ Fall

REPETITION CONTROL STRUCTURE LOGO

3.1. Chapter 3: The cin Object. Expressions and Interactivity

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

Program Organization and Comments

Sample Code: OUTPUT Daily Highs & Lows

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

CSCE Practice Midterm. Data Types

The American University in Cairo Computer Science & Engineering Department CSCE Dr. KHALIL Exam II Spring 2010

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

Ch 6. Functions. Example: function calls function

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

Fundamentals of Programming CS-110. Lecture 2

CSc Introduction to Computing

Exam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80

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

The following is a typical execution run of this program:

Programming in C++ The manager of a company. Lecture Notes 6. Functions (Procedures) 4/24/2018. he he he. Does Does Does

Why Is Repetition Needed?

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

TEST 1 CS 1410 Intro. To Computer Science Name KEY. October 13, 2010 Fall 2010

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

Chapter 7 - Notes User-Defined Functions II

Lab 15 Review of Arrays, Array of Objects and Vector Dr. John Abraham, Professor

CS 141, Introduction to Computer Science Fall Midterm Exam

Functions. A function is a subprogram that performs a specific task. Functions you know: cout << Hi ; cin >> number;

Getting started with C++ (Part 2)

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

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

Functions and Recursion

Add Subtract Multiply Divide

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

CS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM

The American University in Cairo Department of Computer Science & Engineeringt CSCI &09 Dr. KHALIL Exam-I Fall 2009

COMP 111 PROGRAMMING I MODULARITY USING FUNCTIONS

CSCE 2004 Midterm Exam Spring 2017

VARIABLES & ASSIGNMENTS

Chapter 4: Subprograms Functions for Problem Solving. Mr. Dave Clausen La Cañada High School

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

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 2: Basic Elements of C++

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

Introduction to C++ (Extensions to C)

PROGRAMMING EXAMPLE: Checking Account Balance

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

Computer Department. Question (1): State whether each of the following is true or false. Question (2): Select the correct answer from the following:

INTRODUCTION TO PROGRAMMING

Pointers. Variable Declaration. Chapter 10

Chapter 2. Outline. Simple C++ Programs

Objectives. In this chapter, you will:

C++ Final Exam 2017/2018

Note: The buy help from the TA for points will apply on this exam as well, so please read that carefully.

Transcription:

Superior University Department of Electrical Engineering CS-115 Computing Fundamentals Experiment No.7 User Defined Functions II Prepared for By: Name: ID: Section: Semester: Total Marks: Obtained Marks: Signature: Date:

Contents of Lab 1 7.1. Objectives:... 3 7.2. Void Functions... 3 Actual parameter list... 4 Example 1:... 4 7.3. Lab Tasks:... 8 Task 1:... 8 7.4. Home Assignment:... 9 Task 1:... 9 Task 2:... 10 2 Engr. Syed Intazar Hyder

User Defined Functions II 7.1. Objectives: To learn how to construct and use void functions in a program To learn and practice reference parameter and value-returning functions 7.2. Void Functions Void functions and value-returning functions have similar structures. Both have a heading and a body. Like value-returning functions, you can place user-defined void functions either before or after the function main. However, the program execution always begins with the first statement in the function main. If you place user-defined void functions after the function main, you should place the function prototype before the function main. A void function does not have a data type. Therefore, functiontype that is, the return type in the heading part and the return statement in the body of the void functions are meaningless. However, in a void function, you can use the return statement without any value; it is typically used to exit the function early. Like value-returning functions, void functions may or may not have formal parameters. Function Definition: The function definition of void functions with parameters has the following syntax: in which statements are usually declaration and/or executable statements. The formal parameter list may be empty, in which case, in the function heading, the empty parentheses are still needed. Formal parameter list The formal parameter list has the following syntax: You must specify both the data type and the variable name in the formal parameter list. Function call The function call has the following syntax: 3 Engr. Syed Intazar Hyder

Actual parameter list The actual parameter list has the following syntax: In which expression can consist of a single constant value. As with value-returning functions, in a function call, the number of actual parameters together with their data types must match the formal parameters in the order given. Actual and formal parameters have a one-to-one correspondence. A function call results in the execution of the body of the called function. Example 1: // Lab_7_Example_1.cpp //Program: Print a triangle of stars #include <iostream> using namespace std; void printstars(int blanks, int starsinline); int nooflines; //variable to store the number of lines int counter; //for loop control variable int noofblanks; //variable to store the number of blanks cout << "Enter the number of star lines (1 to 20) " << "to be printed: "; cin >> nooflines; while (nooflines < 0 nooflines > 20) cout << "Number of star lines should be " << "between 1 and 20" << endl; cout << "Enter the number of star lines " << "(1 to 20) to be printed: "; cin >> nooflines; cout << endl << endl; noofblanks = 30; for (counter = 1; counter <= nooflines; counter++) printstars(noofblanks, counter); noofblanks--; return 0; void printstars(int blanks, int starsinline) Result 4 Engr. Syed Intazar Hyder

int count; for (count = 1; count <= blanks; count++) cout << ' '; for (count = 1; count <= starsinline; count++) cout << " * "; cout << endl; Value Parameters When a function is called, the value of the actual parameter is copied into the corresponding formal parameter. If the formal parameter is a value parameter, then after copying the value of the actual parameter, there is no connection between the formal parameter and actual parameter; that is, the formal parameter has its own copy of the data. Therefore, during program execution, the formal parameter manipulates the data stored in its own memory space. Example 2: // Lab_7_Example_2.cpp //Program illustrating how a value parameter works. #include <iostream> using namespace std; void funcvalueparam(int num); int number = 6; cout << "Before calling the function " << "funcvalueparam, number = " << number << endl; funcvalueparam(number); cout << "After calling the function " << "funcvalueparam, number = " << number << endl; return 0; void funcvalueparam(int num) cout << "In the function funcvalueparam, " << "before changing, num = " << num << endl; num = 15; cout << "In the function funcvalueparam, " << "after changing, num = " << num << endl; Result 5 Engr. Syed Intazar Hyder

Reference Variables as Parameters A reference parameter receives the address (memory location) of the actual parameter, reference parameters can pass one or more values from a function and can change the value of the actual parameter. Reference parameters are useful in three situations: When the value of the actual parameter needs to be changed When you want to return more than one value from a function When passing the address would save memory space and time relative to copying a large amount of data Example 3: // Lab_7_Example_3.cpp //This program reads a course score and prints the //associated course grade. #include <iostream> using namespace std; void getscore(int& score); void printgrade(int score); int coursescore; cout << "Line 1: Based on the course score, \n" << " this program computes the " << "course grade." << endl; //Line 1 getscore(coursescore); //Line 2 printgrade(coursescore); //Line 3 return 0; void getscore(int& score) cout << "Line 4: Enter course score: "; //Line 4 cin >> score; //Line 5 cout << endl << "Line 6: Course score is " << score << endl; //Line 6 void printgrade(int cscore) cout << "Line 7: Your grade for the course is "; //Line 7 if (cscore >= 90) //Line 8 cout << "A." << endl; else if (cscore >= 80) cout << "B." << endl; else if(cscore >= 70) cout << "C." << endl; Result 6 Engr. Syed Intazar Hyder

else if (cscore >= 60) cout << "D." << endl; else cout << "F." << endl; Value and Reference Parameters and Memory Allocation Example 3: // Lab_7_Example_4.cpp Result //Reference and value parameters #include <iostream> using namespace std; void funone(int a, int& b, char v); void funtwo(int& x, int y, char& w); int num1, num2; char ch; num1 = 10; //Line 1 num2 = 15; //Line 2 ch = 'A'; //Line 3 cout << "Line 4: Inside main: num1 = " << num1 << ", num2 = " << num2 << ", and ch = " << ch << endl; //Line 4 funone(num1, num2, ch); //Line 5 cout << "Line 6: After funone: num1 = " << num1 << ", num2 = " << num2 << ", and ch = " << ch << endl; //Line 6 funtwo(num2, 25, ch); //Line 7 cout << "Line 8: After funtwo: num1 = " << num1 << ", num2 = " << num2 << ", and ch = " << ch << endl; //Line 8 return 0; void funone(int a, int& b, char v) int one; one = a; //Line 9 a++; //Line 10 b = b * 2; //Line 11 v = 'B'; //Line 12 cout << "Line 13: Inside funone: a = " << a << ", b = " << b << ", v = " << v << ", and one = " << one << endl; //Line 13 void funtwo(int& x, int y, char& w) x++; //Line 14 7 Engr. Syed Intazar Hyder

y = y * 2; //Line 15 w = 'G'; //Line 16 cout << "Line 17: Inside funtwo: x = " << x << ", y = " << y << ", and w = " << w << endl; //Line 17 7.3. Lab Tasks: Task 1: Consider the definition of the function main. int x, y; char z; double rate, hours; double amount;... The variables x, y, z, rate, and hours referred to in items a through f below are the variables of the function main. Each of the functions described must have the appropriate parameters to access these variables. Write the following definitions: a) Write the definition of the function initialize that initializes x and y to 0 and z to the blank character. b) Write the definition of the function gethoursrate that prompts the user to input the hours worked and rate per hour to initialize the variables hours and rate of the function main. c) Write the definition of the value-returning function paycheck that calculates and returns the amount to be paid to an employee based on the hours worked and rate per hour. The hours worked and rate per hour are stored in the variables hours and rate, respectively, of the function main. The formula for calculating the amount to be paid is as follows: For the first 40 hours, the rate is the given rate; for hours over 40, the rate is 1.5 times the given rate. d) Write the definition of the function printcheck that prints the hours worked, rate per hour, and the salary. e) Write the definition of the function funcone that prompts the user to input a number. The function then changes the value of x by assigning the value of the expression 2 times the (old) value of x plus the value of y minus the value entered by the user. f) Write the definition of the function nextchar that sets the value of z to the next character stored in z. g) Write the definition of a function main that tests each of these functions. 8 Engr. Syed Intazar Hyder

7.4. Home Assignment: Task 1: Consider the following C++ code: #include <iostream> #include <cmath> #include <iomanip> using namespace std; void func1(); void func2(/*formal parameters*/); int num1, num2; double num3; int choice; cout << fixed << showpoint << setprecision(2); do func1(); cin >> choice; cout << endl; if (choice == 1) func2(num1, num2, num3); cout << num1 << ", " << num2 << ", " << num3 << endl; while (choice!= 99); return 0; void func1() cout << "To run the program, enter 1." << endl; cout << "To exit the pogram, enter 99." << endl; cout << "Enter 1 or 99: "; void func2(/*formal parameters*/) //Write the body of func2. The function func2 has three parameters of type int, int, and double, say a, b, and c, respectively. Write the definition of func2 so that its action is as follows: a) Prompt the user to input two integers and store the numbers in a and b, respectively. b) If both of the numbers are nonzero: i. If a >= b, the value assigned to c is a to the power b, that is, a b. ii. If a < b, the value assigned to c is b to the power a, that is, b a. c) If a is nonzero and b is zero, the value assigned to c is the square root of the absolute value of a. d) If b is nonzero and a is zero, the value assigned to c is the square root of the absolute value of b. e) Otherwise, the value assigned to c is 0. The values of a, b, and c are passed back to the calling environment. After completing the definition of the func2 and writing its function prototype, test run your program. 9 Engr. Syed Intazar Hyder

Task 2: For research purposes and to better help students, the admissions office of your local university wants to know how well female and male students perform in certain courses. You receive a file that contains female and male student GPAs for certain courses. Due to confidentiality, the letter code f is used for female students and m for male students. Every file entry consists of letter code followed by a GPA. Each line has one entry. The number of entries in the file is unknown. Write a program that computes and outputs the average GPA for both female and male students. Format your results to two decimal places. Your program should use the following functions: a) Function openfiles: This function opens the input and output files, and sets the output of the floating-point numbers to two decimal places in a fixed decimal format with a decimal point and trailing zeros. b) Function initialize: This function initializes variables such as countfemale, countmale, sumfemalegpa, and summalegpa. c) Function sumgrades: This function finds the sum of the female and male students GPAs. d) Function averagegrade: This function finds the average GPA for female and male students. e) Function printresults: This function outputs the relevant results. f) There can be no global variables. Use the appropriate parameters to pass information in and out of functions. 10 Engr. Syed Intazar Hyder