Chapter 9 Text Files User Defined Data Types User Defined Header Files
|
|
- Jocelin Stokes
- 7 years ago
- Views:
Transcription
1 Chapter 9 Text Files User Defined Data Types User Defined Header Files 9-1
2 Using Text Files in Your C++ Programs 1. A text file is a file containing data you wish to use in your program. A text file does not contain any C++ declarations or statements just the data. Enter the CodeWarrior editor and create your text file. Save your file with a.dat file extension. It will make things easier if your file has any string data on a line by itself. Numeric data is easily read when you have several items per line as white space is used to delimit the various data items. 2. To use the file in your program you need to include the fstream header file in your program #include<fstream> 3. The function used to read from the file requires a local variable to represent your actual file on disk ifstream infile You may choose any name you like (I typically use infile for files I am reading from and outfile for files I am writing to). 4. You must open the file for reading with the open statement using the variable you declared and the actual file on disk infile.open( people.dat ) is the statement used to associate the variable in your program (infile) with an actual file on disk (people.dat). From now on in your program when the variable name infile is used the program will look at the file on disk specified in the open statement. The open statement also sets the file pointer to the top of the file. 5. To read from the file instead of the keyboard, replace the cin variable with the variable you declared in your program. Examples: getline(infile,name[i]) infile>>age[i] etc. 6. Always close the file before you exit the function that opened it. infile.close 7. STUDY THE FOLLOWING PROGRAMS CAREFULLY AND YOU SHOULD HAVE NO PROBLEMS USING TEXT FILES IN YOUR PROGRAMS. 9-2
3 // This program demonstrates the loading of an array when the number of // data items is known #include <iostream> #include <iomanip> #include <string> #include <fstream> using namespace std; void LoadArrays(string nm[], int ag[]); void OutputArrays(string nm[], int ag[]); void main(void) string names[5]; int ages[5]; // array of 5 names - READ from file // array of 5 ages - READ from file // call functions to read info and print contents of the arrays LoadArrays(names, ages); OutputArrays(names, ages); void LoadArrays(string nm[], // array for names - OUT int ag[]) // array of ages - OUT ifstream infile; // declared locally as no other fns need the file // open the file - infile.open("people.dat"); for(int i=0; i < 5; ++i) getline(infile,nm[i]); infile >> ag[i]; infile.ignore(100,'\n'); // close the file infile.close; void OutputArrays(string nm[], // array of names - IN int ag[]) // array of ages - IN for(int i=0; i < 5; ++i) // note use of length function to format output cout << endl << nm[i] << setw(25- nm[i].length( )) << ag[i]; 9-3
4 // This program reads an unknown number of elements from a file #include <iostream> #include <iomanip> #include <string> #include <fstream> using namespace std; void LoadArrays(string nm[], int ag[], int& ct); void OutputArrays(string nm[], int ag[], int ct); void main(void) string names[25]; int ages[25]; int counter; // array holds up to 25 names - READ from file // array holds up to 25 ages - READ from file // counts array elements as the are read - CALC // initialize counter to count people as they are read from the file counter = -1; // Call functions to load and output the arrays LoadArrays(names, ages, counter); cout << "There are " << counter+1 << " names & ages in the file\n\n"; OutputArrays(names, ages, counter); void LoadArrays(string nm[], // array of names - OUT int ag[], // array of ages - OUT int& ct) // array location counter - INOUT ifstream infile; // file variable for input file // open the file infile.open("people.dat"); while(!infile.eof()) // increment the counter each time the loop is entered ++ct; // note that the name of the file variable replaces cin getline(infile,nm[ct]); infile >> ag[ct]; // "flush" the buffer infile.ignore(1,'\n'); // close the file infile.close; void OutputArrays(string nm[], // array of names - IN int ag[], // array of ages - IN int ct) // number of items in arrays - IN for(int i=0; i <= ct; ++i) // note the use of the length function to format the output cout << endl << nm[i] << setw(25- nm[i].length( )) << ag[i]; 9-4
5 Following is the datafile, people.dat, used in the previous programs. Sam Jones 55 Susie Jones 12 Sally Jones 50 Josh Jones 15 Adam Jones
6 The typedef Statement The typedef statement is used not to create a new type but instead to give a new name to an existing type. The data type bool is relatively new. Prior to the introduction of the bool type we could define our own type to add readability to a program. typedef int Boolean; const int TRUE = 1; const int FALSE = 0; Boolean loopflag; // a variable that may contain TRUE or FALSE Although loopflag actually contains an integer value, the program is made more clear by using the named constants TRUE and FALSE. Array data type example: typedef float FloatArrayType[100]; // anything of type FloatArrayType is defined // as a 100 element array of float values FloatArrayType myarray; // myarray is a variable representing a 100 element // array of float values Because the compiler knows the size and type of the array from the definition of the type FloatArrayType, we can now use this type in a formal parameter list. void LoadArray(FloatArrayType anarray); The typedef statement allows us to create code that is more self documenting and easier to understand. 9-6
7 Modified 2-dimensional array program using the typedef statement #include <fstream.h> #include <iomanip.h> const int NUMOFROWS = 4; const int NUMOFCOLS = 5; // declaration of a two-dimensional array data type typedef float SalesArrayType[NUMOFROWS][NUMOFCOLS]; void LoadSalesData(SalesArrayType sale); void PrintSalesData(SalesArrayType sale); void CalcWeeklySales(SalesArrayType sale); void main(void) SalesArrayType sales; // call function to load the arrays with the month's sales LoadSalesData(sales); // call function to output monthly sales table PrintSalesData(sales); // call function to sum and output weekly sales total CalcWeeklySales(sales); void LoadSalesData(SalesArrayType sale) ifstream infile; // open the file infile.open("sales.dat"); // load the array for(int i = 0; i < NUMOFROWS; i++) for(int j = 0; j < NUMOFCOLS; j++) infile >> sale[i][j]; infile.close; void PrintSalesData(SalesArrayType sale) // output headings cout << setw(45) << "Monthly Sales\n\n"; cout << "\t\t\tmonday Tuesday Wednesday Thursday Friday\n\n"; // print the array for(int i = 0; i < NUMOFROWS; i++) cout << "Week " << i+1; 9-7
8 for(int j = 0; j < NUMOFCOLS; j++) cout << setw(12) << sale[i][j]; cout << endl; void CalcWeeklySales(SalesArrayType sale for(int i = 0; i < NUMOFROWS; i++) float sum; sum = 0.0; for(int j = 0; j < NUMOFCOLS; j++) sum = sum + sale[i][j]; cout << "\n\nsales for week " << i+1 << " = " << sum; 9-8
9 Enumeration Types Enumeration types are used primarily to add readability to a program and make it more self documenting. Example: enum Dogs POODLE, COLLIE, LABRADOR, GOLDEN_RETRIEVER; We have created a new type called Dogs and listed the elements (possible values) inside the braces. We can now declare variables of this type. Dogs mydog; Dogs yourdog; mydog = GOLDEN_RETRIEVER; yourdog = POODLE; yourdog = mydog; yourdog = COLLIE ; // invalid Each element has a numeric value associated with it, that is to say they are ordered. The value of POODLE is 0, the value of COLLIE is 1, etc. This allows us to use the relational operators when working with enumeration types. While each element has an int value associated with it, you may not work with this type as though it was an int. Suppose I wanted to have the value of mydog become the next value in the list. mydog = mydog + 1; mydog++; // invalid // invalid We need to use type casting mydog = Dogs(myDog + 1); // valid 9-9
10 Enumeration types may be used in switch statements and as the loop control variable in a for loop. For(Dogs mydog = POODLE; mydog <= GOLDEN_RETRIEVER; mydog = Dogs(myDog+1)) It is not possible to input or output an enumeration type directly. To output the value of the members of type Dogs a switch statement is necessary. switch(mydog) case POODLE case COLLIE case LABRADOR case GOLDEN_RETRIEVER : cout << Poodle ; : cout << Collie ; : cout << Labrador ; : cout << Golden Retriever ; 9-10
11 User Defined Header Files We have been using the #include pre-processor directive in our programs to gain access to routines supplied by the C++ standard libraries. It is also possible for us to create our own files of declarations and functions that may be written and compiled once and accessed by any program via the #include directive. Suppose I want to declare an enumeration type called Days and make this type available to any program that wishes to use it. Additionally, I would like to declare a data type for an array used to hold sales figures for the week. The declarations will be stored in a file called myheader.h. Any program wishing to access these declarations may do so by using the following directive #include myheader.h Note the use of the quotation marks. The directive #include <iostream.h> indicates that the header file will be found in the directory with the standard C++ libraries where the directive #include myheader.h indicates that the header file is located in the current directory (in our case, the current project folder). 9-11
12 // User defined header file demonstration #include <iostream.h> #include <iomanip.h> #include <fstream.h> #include "myheader.h" // file is located in the project folder // Function to load the weekly sales void LoadSales(SalesArrayType sales); // Function to output the weekly sales void OutputSales(SalesArrayType sales); void main(void) // declaration of array variable using type defined in myheader.h SalesArrayType salesarray; cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint); LoadSales(salesArray); OutputSales(salesArray); // Function to load the weekly sales void LoadSales(SalesArrayType sales) ifstream infile; infile.open("sales.dat"); for (Days index = SUN; index <= SAT; index = Days(index + 1)) infile >> sales[index]; infile.close; 9-12
13 // Function to output the weekly sales void OutputSales(SalesArrayType sales) cout << "\n\nsales for the Week\n"; cout << " \n"; for (Days index = SUN; index <= SAT; index = Days(index + 1)) // recall that enum types may not be output directly switch (index) case SUN : cout << "\nsunday: "; case MON: cout << "\nmonday: "; case TUE : cout << "\ntuesday: "; case WED : cout << "\nwednesday: "; case THU : cout << "\nthursday: "; case FRI : cout << "\nfriday: "; case SAT : cout << "\nsaturday: "; cout << setw(8) << setprecision(2) << sales[index] << endl; 9-13
14 // file myheader.h // user defined header file to specify two user defined data types // enumeration type for days of the week enum Days SUN, MON, TUE, WED, THU, FRI, SAT; // typedef for a one-dimensional array typedef float SalesArrayType[7]; It is also possible to create header files that contain more than declarations. In the following example there are three files used. 1. A program file containing the main function. 2. A header file (myheader.h) containing the enum and typedef statements as well as two function prototypes. 3. A program file (myheader.cpp) containing the code for the functions specified in myheader.h. The actual implementation of the functions is kept separate from the header file where the prototypes appear. Anyone wishing to use the data types and functions provided need only see the declaration of the types and the function prototypes. There is no need for the user to have access to the actual implementation. 9-14
15 // This file contains the main function #include "myheader.h" // file is located in the project folder void main(void) // declaration of array variable using type defined in myheader.h SalesArrayType salesarray; // Calls to functions prototypes contained in myheader.h and // implementation contained in myheader.cpp LoadSales(salesArray); OutputSales(salesArray); 9-15
16 // file myheader.h // user defined header file to specify two user defined data types // and the prototypes for two functions to act on the array // enumeration type for days of the week enum Days SUN, MON, TUE, WED, THU, FRI, SAT; // typedef for a one-dimensional array typedef float SalesArrayType[7]; // Function to load the weekly sales void LoadSales(SalesArrayType sales); // Function to output the weekly sales void OutputSales(SalesArrayType sales); 9-16
17 // File myheader.cpp contains the implementation portion of myheader.h #include <iostream.h> #include <iomanip.h> #include <fstream.h> #include "myheader.h" // file is located in the project folder // Function to load the weekly sales void LoadSales(SalesArrayType sales) ifstream infile; infile.open("sales.dat"); for (Days index = SUN; index <= SAT; index = Days(index + 1)) infile >> sales[index]; infile.close; // Function to output the weekly sales void OutputSales(SalesArrayType sales) cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint); cout << "\n\nsales for the Week\n"; cout << " \n"; for (Days index = SUN; index <= SAT; index = Days(index + 1)) // recall that enum types may not be output directly switch (index) case SUN : cout << "\nsunday: "; case MON : cout << "\nmonday: "; case TUE : cout << "\ntuesday: "; case WED : cout << "\nwednesday: "; case THU : cout << "\nthursday: "; case FRI : cout << "\nfriday: "; case SAT : cout << "\nsaturday: "; cout << setw(8) << setprecision(2) << sales[index] << endl; 9-17
18 // File myheader.cpp contains the implementation portion of myheader.h // user defined header file demonstration #include <iostream.h> #include <iomanip.h> #include <fstream.h> #include "myheader.h" // file is located in the project folder // Function to load the weekly sales void LoadSales(SalesArrayType sales) ifstream infile; infile.open("sales.dat"); for (Days index = SUN; index <= SAT; index = Days(index + 1)) infile >> sales[index]; infile.close; // Function to output the weekly sales void OutputSales(SalesArrayType sales) cout << "\n\nsales for the Week\n"; cout << " \n"; for (Days index = SUN; index <= SAT; index = Days(index + 1)) // recall that enum types may not be output directly switch (index) case SUN : cout << "\nsunday: "; case MON : cout << "\nmonday: "; case TUE : cout << "\ntuesday: "; case WED : cout << "\nwednesday: "; case THU : cout << "\nthursday: "; case FRI : cout << "\nfriday: "; case SAT : cout << "\nsaturday: "; cout << setw(8) << setprecision(2) << sales[index] << endl; 9-18
19 Notes on User Defined Header Files 1. Make certain all related files are in the project folder. 2. You may have only one.cpp file that contains a main function listed in the Sources section of the project. 3. The name of the.cpp file containing the implementation of the functions listed in the header file must be listed under the Sources section of the project. Use the Add Files option from the Project menu to add this file to the list of sources. You may eventually have several files active under Sources but remember that ONLY ONE may contain a main function. 9-19
20 Name Due Date Header Files Assignment 1. Create a header file that contains the following: - a typedef to define a one dimensional array of 10 integers - the prototype for a function to load the array from a datafile - the prototype for a function to calculate the sum of the elements in the array - the prototype for a function to output the contents of the array 2. Create the necessary.cpp file that contains the code for the functions listed in #1. 3. Create a file that contains the main function. The file will do the following: - call the load function - assign to a variable called thesum the return value from the function that sums the array - call the output function - output the value of thesum 9-20
What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...
What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control
More information7.7 Case Study: Calculating Depreciation
7.7 Case Study: Calculating Depreciation 1 7.7 Case Study: Calculating Depreciation PROBLEM Depreciation is a decrease in the value over time of some asset due to wear and tear, decay, declining price,
More informationAppendix K Introduction to Microsoft Visual C++ 6.0
Appendix K Introduction to Microsoft Visual C++ 6.0 This appendix serves as a quick reference for performing the following operations using the Microsoft Visual C++ integrated development environment (IDE):
More informationBasics of I/O Streams and File I/O
Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading
More informationLab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++)
Lab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++) (Revised from http://msdn.microsoft.com/en-us/library/bb384842.aspx) * Keep this information to
More informationC++ Input/Output: Streams
C++ Input/Output: Streams 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: istream
More informationChapter 7. Functions 7-1
Chapter 7 Functions 7-1 Functions Modules in C++ are referred to as functions. The use of functions in a program allows - a program to be broken into small tasks. - a program to be written and debugged
More informationFormatting Numbers with C++ Output Streams
Formatting Numbers with C++ Output Streams David Kieras, EECS Dept., Univ. of Michigan Revised for EECS 381, Winter 2004. Using the output operator with C++ streams is generally easy as pie, with the only
More informationThe University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002. True or False (2 points each)
True or False (2 points each) The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002 1. Using global variables is better style than using local
More informationBoolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)
Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the
More informationPART-A Questions. 2. How does an enumerated statement differ from a typedef statement?
1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members
More informationMember Functions of the istream Class
Member Functions of the istream Class The extraction operator is of limited use because it always uses whitespace to delimit its reads of the input stream. It cannot be used to read those whitespace characters,
More informationComp151. Definitions & Declarations
Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const
More informationChapter One Introduction to Programming
Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of
More informationMoving from C++ to VBA
Introduction College of Engineering and Computer Science Mechanical Engineering Department Mechanical Engineering 309 Numerical Analysis of Engineering Systems Fall 2014 Number: 15237 Instructor: Larry
More informationC++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore
More informationLecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c
Lecture 3 Data structures arrays structs C strings: array of chars Arrays as parameters to functions Multiple subscripted arrays Structs as parameters to functions Default arguments Inline functions Redirection
More informationSequential Program Execution
Sequential Program Execution Quick Start Compile step once always g++ -o Realtor1 Realtor1.cpp mkdir labs cd labs Execute step mkdir 1 Realtor1 cd 1 cp../0/realtor.cpp Realtor1.cpp Submit step cp /samples/csc/155/labs/1/*.
More informationWhile Loop. 6. Iteration
While Loop 1 Loop - a control structure that causes a set of statements to be executed repeatedly, (reiterated). While statement - most versatile type of loop in C++ false while boolean expression true
More informationThe Payroll Program. Payroll
The Program 1 The following example is a simple payroll program that illustrates most of the core elements of the C++ language covered in sections 3 through 6 of the course notes. During the term, a formal
More informationName: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.
Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to
More informationStorage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas
CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage
More information9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements
9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending
More informationThe C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures
The C++ Language Loops Loops! Recall that a loop is another of the four basic programming language structures Repeat statements until some condition is false. Condition False True Statement1 2 1 Loops
More informationAnswers to Review Questions Chapter 7
Answers to Review Questions Chapter 7 1. The size declarator is used in a definition of an array to indicate the number of elements the array will have. A subscript is used to access a specific element
More informationCalling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?
Functions in C++ Let s take a look at an example declaration: Lecture 2 long factorial(int n) Functions The declaration above has the following meaning: The return type is long That means the function
More informationLecture 2 Notes: Flow of Control
6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. The
More informationIllustration 1: Diagram of program function and data flow
The contract called for creation of a random access database of plumbing shops within the near perimeter of FIU Engineering school. The database features a rating number from 1-10 to offer a guideline
More informationSimple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language
Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from
More informationChapter 8 Selection 8-1
Chapter 8 Selection 8-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow
More informationC++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;
C++ Outline Notes taken from: - Drake, Caleb. EECS 370 Course Notes, University of Illinois Chicago, Spring 97. Chapters 9, 10, 11, 13.1 & 13.2 - Horstman, Cay S. Mastering Object-Oriented Design in C++.
More informationData Structures using OOP C++ Lecture 1
References: 1. E Balagurusamy, Object Oriented Programming with C++, 4 th edition, McGraw-Hill 2008. 2. Robert Lafore, Object-Oriented Programming in C++, 4 th edition, 2002, SAMS publishing. 3. Robert
More information6. Control Structures
- 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,
More informationVisual Studio 2008 Express Editions
Visual Studio 2008 Express Editions Visual Studio 2008 Installation Instructions Burning a Visual Studio 2008 Express Editions DVD Download (http://www.microsoft.com/express/download/) the Visual Studio
More informationPassing 1D arrays to functions.
Passing 1D arrays to functions. In C++ arrays can only be reference parameters. It is not possible to pass an array by value. Therefore, the ampersand (&) is omitted. What is actually passed to the function,
More informationAppendix M: Introduction to Microsoft Visual C++ 2010 Express Edition
Appendix M: Introduction to Microsoft Visual C++ 2010 Express Edition This book may be ordered from Addison-Wesley in a value pack that includes Microsoft Visual C++ 2010 Express Edition. Visual C++ 2010
More informationUbuntu. Ubuntu. C++ Overview. Ubuntu. History of C++ Major Features of C++
Ubuntu You will develop your course projects in C++ under Ubuntu Linux. If your home computer or laptop is running under Windows, an easy and painless way of installing Ubuntu is Wubi: http://www.ubuntu.com/download/desktop/windowsinstaller
More informationUsing C++ File Streams
Using C++ File Streams David Kieras, EECS Dept., Univ. of Michigan Revised for EECS 381, 9/20/2012 File streams are a lot like cin and cout In Standard C++, you can do I/O to and from disk files very much
More informationCommon Beginner C++ Programming Mistakes
Common Beginner C++ Programming Mistakes This documents some common C++ mistakes that beginning programmers make. These errors are two types: Syntax errors these are detected at compile time and you won't
More informationC++FA 5.1 PRACTICE MID-TERM EXAM
C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer
More informationAn Incomplete C++ Primer. University of Wyoming MA 5310
An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages
More informationC++ INTERVIEW QUESTIONS
C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get
More informationConditions & Boolean Expressions
Conditions & Boolean Expressions 1 In C++, in order to ask a question, a program makes an assertion which is evaluated to either true (nonzero) or false (zero) by the computer at run time. Example: In
More informationMS Visual C++ Introduction. Quick Introduction. A1 Visual C++
MS Visual C++ Introduction 1 Quick Introduction The following pages provide a quick tutorial on using Microsoft Visual C++ 6.0 to produce a small project. There should be no major differences if you are
More informationArrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays
Motivation Suppose that we want a program that can read in a list of numbers and sort that list, or nd the largest value in that list. To be concrete about it, suppose we have 15 numbers to read in from
More informationGoals for This Lecture:
Goals for This Lecture: Understand the pass-by-value and passby-reference argument passing mechanisms of C++ Understand the use of C++ arrays Understand how arrays are passed to C++ functions Call-by-value
More informationC++ program structure Variable Declarations
C++ program structure A C++ program consists of Declarations of global types, variables, and functions. The scope of globally defined types, variables, and functions is limited to the file in which they
More informationComputer Programming C++ Classes and Objects 15 th Lecture
Computer Programming C++ Classes and Objects 15 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2013 Eom, Hyeonsang All Rights Reserved Outline
More informationKeywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void
1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of
More informationCompiler Construction
Compiler Construction Lecture 1 - An Overview 2003 Robert M. Siegfried All rights reserved A few basic definitions Translate - v, a.to turn into one s own language or another. b. to transform or turn from
More informationC++ Language Tutorial
cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain
More informationIS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction
IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points
More informationSources: On the Web: Slides will be available on:
C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,
More informationCS 101 Computer Programming and Utilization
CS 101 Computer Programming and Utilization Lecture 14 Functions, Procedures and Classes. primitive and objects. Files. Mar 4, 2011 Prof. R K Joshi Computer Science and Engineering IIT Bombay Email: rkj@cse.iitb.ac.in
More informationEmbedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C
Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection
More information5 Arrays and Pointers
5 Arrays and Pointers 5.1 One-dimensional arrays Arrays offer a convenient way to store and access blocks of data. Think of arrays as a sequential list that offers indexed access. For example, a list of
More informationC++ DATA STRUCTURES. Defining a Structure: Accessing Structure Members:
C++ DATA STRUCTURES http://www.tutorialspoint.com/cplusplus/cpp_data_structures.htm Copyright tutorialspoint.com C/C++ arrays allow you to define variables that combine several data items of the same kind
More informationThis copy of the text was produced at 20:37 on 4/10/2014.
Programming in C++ This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike License To view a copy of this license, visit http://creativecommonsorg/licenses/by-nc-sa/30/ or
More informationFor the next three questions, consider the class declaration: Member function implementations put inline to save space.
Instructions: This homework assignment focuses on basic facts regarding classes in C++. Submit your answers via the Curator System as OQ4. For the next three questions, consider the class declaration:
More informationA brief introduction to C++ and Interfacing with Excel
A brief introduction to C++ and Interfacing with Excel ANDREW L. HAZEL School of Mathematics, The University of Manchester Oxford Road, Manchester, M13 9PL, UK CONTENTS 1 Contents 1 Introduction 3 1.1
More informationFirst Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science
First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca
More information13 Classes & Objects with Constructors/Destructors
13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.
More informationCreating a Simple Visual C++ Program
CPS 150 Lab 1 Name Logging in: Creating a Simple Visual C++ Program 1. Once you have signed for a CPS computer account, use the login ID and the password password (lower case) to log in to the system.
More informationif and if-else: Part 1
if and if-else: Part 1 Objectives Write if statements (including blocks) Write if-else statements (including blocks) Write nested if-else statements We will now talk about writing statements that make
More informationAnswers to Selected Exercises
DalePhatANS_complete 8/18/04 10:30 AM Page 1049 Answers to Selected Exercises Chapter 1 Exam Preparation Exercises 1. a. v, b. i, c. viii, d. iii, e. iv, f. vii, g. vi, h. ii. 2. Analysis and specification,
More informationIntroduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC
Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Example Assume the following specification: Input: read a number N > 0 Output:
More informationExample. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:
Example Introduction to Programming (in C++) Loops Assume the following specification: Input: read a number N > 0 Output: write the sequence 1 2 3 N (one number per line) Jordi Cortadella, Ricard Gavaldà,
More informationCSI33 Data Structures
Outline Department of Mathematics and Computer Science Bronx Community College November 25, 2015 Outline Outline 1 Chapter 12: C++ Templates Outline Chapter 12: C++ Templates 1 Chapter 12: C++ Templates
More informationCpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing
CpSc212 Goddard Notes Chapter 6 Yet More on Classes We discuss the problems of comparing, copying, passing, outputting, and destructing objects. 6.1 Object Storage, Allocation and Destructors Some objects
More informationEP241 Computer Programming
EP241 Computer Programming Topic 10 Basic Classes Department of Engineering Physics University of Gaziantep Course web page www.gantep.edu.tr/~bingul/ep241 Sep 2013 Sayfa 1 Introduction In this lecture
More informationFunctions and Parameter Passing
Chapter 5: Functions and Parameter Passing In this chapter, we examine the difference between function calls in C and C++ and the resulting difference in the way functions are defined in the two languages.
More informationRecursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., 2001. 1995-2001 Barnette ND, McQuain WD
1 Slides 1. Table of Contents 2. Definitions 3. Simple 4. Recursive Execution Trace 5. Attributes 6. Recursive Array Summation 7. Recursive Array Summation Trace 8. Coding Recursively 9. Recursive Design
More informationSyllabus OBJECT ORIENTED PROGRAMMING C++
1 Syllabus OBJECT ORIENTED PROGRAMMING C++ 1. Introduction : What is object oriented programming? Why do we need objectoriented. Programming characteristics of object-oriented languages. C and C++. 2.
More informationYou are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:
Lecture 7 Picking Balls From an Urn The problem: An urn has n (n = 10) balls numbered from 0 to 9 A ball is selected at random, its' is number noted, it is set aside, and another ball is selected from
More informationQUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1
QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For
More information! " # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1
!" #$%&%'())*%%+,-..*/*%%+- 0 )12 1 *!" 34 5 6 * #& ) 7 8 5)# 97&)8 5)# 9 : & ; < 5 11 8 1 5)=19 7 19 : 0 5)=1 ) & & >) ) >) 1? 5)= 19 7 19 : # )! #"&@)1 # )? 1 1#& 5)=19719:# 1 5)=9 7 9 : 11 0 #) 5 A
More informationIntroduction to Java
Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high
More informationCOMPUTER SCIENCE 1999 (Delhi Board)
COMPUTER SCIENCE 1999 (Delhi Board) Time allowed: 3 hours Max. Marks: 70 Instructions: (i) All the questions are compulsory. (ii) Programming Language: C++ QUESTION l. (a) Why main function is special?
More informationRepetition Using the End of File Condition
Repetition Using the End of File Condition Quick Start Compile step once always g++ -o Scan4 Scan4.cpp mkdir labs cd labs Execute step mkdir 4 Scan4 cd 4 cp /samples/csc/155/labs/4/*. Submit step emacs
More informationPIC 10A. Lecture 7: Graphics II and intro to the if statement
PIC 10A Lecture 7: Graphics II and intro to the if statement Setting up a coordinate system By default the viewing window has a coordinate system already set up for you 10-10 10-10 The origin is in the
More informationChapter 5. Selection 5-1
Chapter 5 Selection 5-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow
More informationarrays C Programming Language - Arrays
arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)
More informationThe While Loop. Objectives. Textbook. WHILE Loops
Objectives The While Loop 1E3 Topic 6 To recognise when a WHILE loop is needed. To be able to predict what a given WHILE loop will do. To be able to write a correct WHILE loop. To be able to use a WHILE
More informationCORBA Programming with TAOX11. The C++11 CORBA Implementation
CORBA Programming with TAOX11 The C++11 CORBA Implementation TAOX11: the CORBA Implementation by Remedy IT TAOX11 simplifies development of CORBA based applications IDL to C++11 language mapping is easy
More informationCh 7-1. Object-Oriented Programming and Classes
2014-1 Ch 7-1. Object-Oriented Programming and Classes May 10, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497;
More informationUEE1302 (1102) F10 Introduction to Computers and Programming
Computational Intelligence on Automation Lab @ NCTU UEE1302 (1102) F10 Introduction to Computers and Programming Programming Lecture 03 Flow of Control (Part II): Repetition while,for & do..while Learning
More informationChapter 3: Writing C# Expressions
Page 1 of 19 Chapter 3: Writing C# Expressions In This Chapter Unary Operators Binary Operators The Ternary Operator Other Operators Enumeration Expressions Array Expressions Statements Blocks Labels Declarations
More informationC Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands
C Programming for Embedded Microcontrollers Warwick A. Smith Elektor International Media BV Postbus 11 6114ZG Susteren The Netherlands 3 the Table of Contents Introduction 11 Target Audience 11 What is
More informationArrays in Java. Working with Arrays
Arrays in Java So far we have talked about variables as a storage location for a single value of a particular data type. We can also define a variable in such a way that it can store multiple values. Such
More informationC++FA 3.1 OPTIMIZING C++
C++FA 3.1 OPTIMIZING C++ Ben Van Vliet Measuring Performance Performance can be measured and judged in different ways execution time, memory usage, error count, ease of use and trade offs usually have
More informationPrograming the Microprocessor in C Microprocessor System Design and Interfacing ECE 362
PURDUE UNIVERSITY Programing the Microprocessor in C Microprocessor System Design and Interfacing ECE 362 Course Staff 1/31/2012 1 Introduction This tutorial is made to help the student use C language
More informationJ a v a Quiz (Unit 3, Test 0 Practice)
Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points
More informationOperator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example
Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics
More informationEmbedded SQL. Unit 5.1. Dr Gordon Russell, Copyright @ Napier University
Embedded SQL Unit 5.1 Unit 5.1 - Embedde SQL - V2.0 1 Interactive SQL So far in the module we have considered only the SQL queries which you can type in at the SQL prompt. We refer to this as interactive
More information?<BACBC;@@A=2(?@?;@=2:;:%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
NGS data format NGS data format @SRR031028.1708655 GGATGATGGATGGATAGATAGATGAAGAGATGGATGGATGGGTGGGTGGTATGCAGCATACCTGAAGTGC BBBCB=ABBB@BA=?BABBBBA??B@BAAA>ABB;@5=@@@?8@:==99:465727:;41'.9>;933!4 @SRR031028.843803
More informationShort Notes on Dynamic Memory Allocation, Pointer and Data Structure
Short Notes on Dynamic Memory Allocation, Pointer and Data Structure 1 Dynamic Memory Allocation in C/C++ Motivation /* a[100] vs. *b or *c */ Func(int array_size) double k, a[100], *b, *c; b = (double
More informationSubject Name: Object Oriented Programming in C++ Subject Code: 2140705
Faculties: L.J. Institute of Engineering & Technology Semester: IV (2016) Subject Name: Object Oriented Programming in C++ Subject Code: 21405 Sr No UNIT - 1 : CONCEPTS OF OOCP Topics -Introduction OOCP,
More informationHow to: Use Basic C++, Syntax and Operators
June 7, 1999 10:10 owltex Sheet number 22 Page number 705 magenta black How to: Use Basic C++, Syntax and Operators A In this How to we summarize the basic syntax of C++ and the rules and operators that
More information