Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

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

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

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

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

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

Getting started with C++ (Part 2)

Why Is Repetition Needed?

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.

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

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

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

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

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold

CHAPTER 4 FUNCTIONS. 4.1 Introduction

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

Functions, Arrays & Structs

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

BITG 1233: Introduction to C++

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

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

Functions and Recursion

Introduction to C++ Systems Programming

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

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

Objectives. In this chapter, you will:

[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";

Chapter 2: Basic Elements of C++

CSCE Practice Midterm. Data Types

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

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

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

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

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

7 Arrays. 7.1 Arrays Hold Multiple Values TOPICS. CONCEPT: An array allows you to store and work with multiple values of the same data type.

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

CS242 COMPUTER PROGRAMMING

Sample Final Exam. 1) (24 points) Show what is printed by the following segments of code (assume all appropriate header files, etc.

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

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

C++ PROGRAMMING SKILLS Part 4: Arrays

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.

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

Chapter 3 Problem Solving and the Computer

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.

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

Review of Important Topics in CS1600. Functions Arrays C-strings

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

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

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

Understanding main() function Input/Output Streams

A SHORT COURSE ON C++

Functions, Arrays & Structs

Introduction to C++ (Extensions to C)

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

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Agenda / Learning Objectives: 1. Map out a plan to study for mid-term Review the C++ operators up to logical operators. 3. Read about the tips

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

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

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

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

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

do { statements } while (condition);

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

Program Organization and Comments

C Functions. Object created and destroyed within its block auto: default for local variables

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

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

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

Exam 3 Chapters 7 & 9

Pointers. Variable Declaration. Chapter 10

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

Chapter 12 Two-Dimensional Arrays

True or False (12 Points)

CS2255 HOMEWORK #1 Fall 2012

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Cpt S 122 Data Structures. Templates

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Lab Instructor : Jean Lai

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

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

1. Word Analysis: (Which nouns suggest a need for memory (a variable) and which verbs suggest a need for action (a function maybe).

Arrays. Week 4. Assylbek Jumagaliyev

C++ For Science and Engineering Lecture 12

W3101: Programming Languages C++ Ramana Isukapalli

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

C/C++ Programming Lecture 7 Name:

BTE2313. Chapter 2: Introduction to C++ Programming

Chapter 3. Numeric Types, Expressions, and Output

C++ Final Exam 2017/2018

CSCE Practice Midterm. Data Types

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

Fast Introduction to Object Oriented Programming and C++

9. Arrays. Compound Data Types: type name [elements]; int billy [5];

Control Statements: Part Pearson Education, Inc. All rights reserved.

Transcription:

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

Objectives In this tutorial, you will learn to: Create and initialize arrays to store groups of related values. Store information in an array. Access individual elements of an array.

13.1 Test-Driving the Salary Survey Application Applic a tion Req uirements A company pays its sales staff on a commission basis. Each member of the sales staff receives $200 per week, plus 9% of their gross sales for that week. For example, a salesperson who grosses $5000 in sales in a week receives $200 plus 9% of $5000, a total of $650. Write an application (using an array) to determine how many of the sales staff earned salaries in each of the following ranges (assuming that each person s salary is truncated to an integer amount): $200 299, $300 399, $400 499, $500 599, $600 699, $700 799, $800 899, $900 999 and over $999.

13.1 Test-Driving the Salary Survey Application Figure 13.1 Running the completed Salary Survey application. Figure 13.2 sales figure. Salary Survey application displaying a salary and prompting for the next Displaying the total salary

13.1 Test-Driving the Salary Survey Application (Cont.) Figure 13.3 Entering several sales figures in the Salary Survey application. Figure 13.4 Displaying the distribution of salaries.

13.2 Introducing Arrays Arrays are groups of variables with the same type Use the array name and an index (position number) to refer to individual elements Indices range from 0 to one less than the number of elements C++ will not prevent an application from attempting to access an element outside of an array s valid range Attempting to access a nonexistent element may result in a logic error

13.2 Introducing Arrays (Cont.) Figure 13.5 Array unitssold, consisting of 13 elements.

13.3 Declaring and Initializing Arrays Declare an array by using square brackets [] after the array name Array initializer lists Are comma-separated lists enclosed by braces {} If no array size is specified within the square brackets, the size of the initializer list is used Using an initializer list with more elements than the array is a syntax error Using an initializer list with fewer elements than the array causes unintialized elements to be set to 0

13.3 Declaring and Initializing Arrays (Cont.) Array initializer lists Syntax error Initializing every element to 0 If no initializer is provided values will be random. int salesperday[ 13 ];

13.3 Declaring and Initializing Arrays (Cont.) Figure 13.6 Defining and initializing an array in main. Creating and initializing an array of ints Use a const int to declare array sizes makes your code more clear and allows you to change it quickly in the future.

Figure 13.7 13.3 Declaring and Initializing Arrays (Cont.) Summing the values of an array s elements. Retrieving the value of each element and adding it to the total one at a time Figure 13.8 Displaying the sum of the values of an array s elements.

13.3 Declaring and Initializing Arrays (Cont.) Figure 13.9 Completed Sum Array application output. Total value of array elements

13.4 Constructing the Salary Survey Application Prompt the user for the first sales figure While the sales figure is greater than or equal to zero Calculate the salary based on commission Increment the number of salaries within that range Prompt the user for the next sales figure Display the distribution of salaries Figure 13.10 Pseud oc od e for the Salary Survey a pplic ation.

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.11 Declaring a function prototype for displaytotals. Declaring the displaytotals function prototype

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.12 Defining a variable to store sales and creating an array of ints. Defining and initializing double variable sales Declaring int array resultarray and initializing its elements to 0

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.13 Retrieving user input. Prompting the user for and inputting a salesperson s total sales

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.14 salary. Using the fixed and setprecision stream manipulators to display the Formatting floating-point values

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.15 while statement repeats until user enters an invalid value. while statement will process user input and prompt the user for the next salary

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.16 Calculating salary. Calculating the salary and its corresponding index in resultarray Figure 13.17 Warning issued by the compiler when assigning a double value to an int variable. Warning due to possible loss of data Warnings do not prevent the application from compiling (syntax errors), but might indicate logic errors

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.18 Explicitly converting the floating-point result to an int to prevent the compiler warning. Explicitly converting the result to an int to prevent a warning

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.19 Updating the count of salaries in resultarray. Incrementing the appropriate element of resultarray

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.20 Displaying the salary and prompting the user for the next sales figure. Prompting user for next sales value

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.21 Passing resultarray by reference to the displaytotals function. Using pass-be-reference when passing resultarray to displaytotal Arrays are passed-by-reference Arguments that are passed-by-reference give the callee direct access to the argument in the caller

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.22 displaytotals function definition Defining the displaytotals function.

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.23 Defining variables and displaying a table header in displaytotals. Defining local variables to store the upper and lower bounds for each salary range Displaying a table header

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.24 Displaying the number of salaries in each salary range. for statement varies i from 2 to 9 Assigning the upper and lower bounds for the current iteration Displaying the salary range and number of salaries in that range

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.25 Display the range and salary count for $1000 and greater. Displaying the total for the final salary range

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.26 Sample input and output for the Salary Survey application.

13.4 Constructing the Salary Survey Application (Cont.) Figure 13.27 Total of salaries in each range displayed upon exiting.

1 // Tutorial 13: SalarySurvey.cpp 2 // Application that takes information about employee salaries and 3 // uses an array to keep track of the number of employees in each 4 // salary range. 5 #include <iostream> // required to perform C++ stream I/O 6 #include <iomanip> // required for parameterized stream manipulators 7 8 using namespace std; // for accessing C++ Standard Library members 9 10 void displaytotals( int [] ); // function prototype 11 12 // function main begins program execution 13 int main() 14 { 15 // define variable and declare an array, initialize values to 0 16 double sales = 0; // sales that user inputs 17 int resultarray[ 11 ] = { 0 }; // count of salary ranges 18 19 // prompt user for and input sales 20 cout << "\nenter sales (-1 to end): "; 21 cin >> sales; // get sales SalarySurvey.cpp (1 of 4) Declare the displaytotals function Define and initialize double sales Declare int array resultarray and initialize its elements to 0

22 23 // display floating-point values as currency 24 cout << fixed << setprecision( 2 ); 25 26 // repeat until user enters sentinel value 27 while ( sales >= 0 ) 28 { 29 // calculate salary and index 30 double salary = 200 + 0.09 * sales; 31 int index = static_cast< int >( salary / 100 ); 32 33 // update statistics 34 if ( index >= 10 ) 35 { 36 resultarray[ 10 ]++; 37 } // end if 38 else 39 { 40 resultarray[ index ]++; 41 } // end else 42 while statement processes user input and prompts for the next salary Increment the appropriate element of resultarray SalarySurvey.cpp (2 of 4) Calculate the salary and its corresponding index in resultarray

43 // display salary 44 cout << "Total salary: $" << salary << endl; 45 46 // prompt user for and input next sales value 47 cout << "\nenter sales (-1 to end): "; 48 cin >> sales; // get sales 49 } // end while 50 51 // display salary ranges and totals 52 displaytotals( resultarray ); 53 54 return 0; // indicates successful termination 55 56 } // end function main 57 58 // display salary ranges and totals 59 void displaytotals( int printarray[] ) 60 { 61 // define local variables 62 int lowerbound; // current salary range's lower bound 63 int upperbound; // current salary range's upper bound SalarySurvey.cpp (3 of 4) Use pass-by-reference when passing resultarray to displaytotals Define local variables to store the upper and lower bounds for each salary range

64 65 // display a table header 66 cout << "\nsalary Range:\tTotal:" << endl; 67 68 // iterate over each salary range between $200 and $999 69 for ( int i = 2; i <= 9; i++ ) 70 { 71 lowerbound = i * 100; // set the current lower bound 72 upperbound = lowerbound + 99; // set the current upper bound 73 74 // display range and total number of salaries in that range 75 cout << "$" << lowerbound << "-" << upperbound << "\t" 76 << printarray[ i ] << endl; 77 } // end for 78 79 // display range and salary count for $1000 and greater 80 cout << "$1000+\t\t" << printarray[ 10 ] << endl << endl; 81 82 } // end function displaytotals Display a table header for header varies i from 2 to 9 SalarySurvey.cpp (4 of 4) Assign the lower and upper bounds for the current iteration Display the salary range and number of salaries in that range Display the count for the final salary range