What will happen if the user presses <enter> after every input? Will all work like below? Enter the values of x, y, z: Result: The sum is 17.

Size: px
Start display at page:

Download "What will happen if the user presses <enter> after every input? Will all work like below? Enter the values of x, y, z: Result: The sum is 17."

Transcription

1 (LN 2-1) Review-exercises Exercise 1. FUNCTION CALLING void x1() cout << 10; Exercise 2. MORE ON CIN int x2() return 20; Consider the functions on the left. What will happen if we write: (1) cout << x1(); (2) x1(); (3) cout << x2(); (4) x2(); To write a program to input 3 values into integers x,y,z: Enter the values of x, y, z: Result: The sum is 17. Which of the below is(are) correct? (1) cin >> x >> y >> z; (2) cin >> x; cin >> y; cin >> z; What will happen if the user presses <enter> after every input? Will all work like below? Enter the values of x, y, z: Result: The sum is 17. Exercise 3. (i) What if I run the following program and enter "abcdefghijkl<enter>"? (ii) What if I run the following program and enter "a<enter>b<enter>c<enter>.."? int i=0; while (i<10) char c; cin >> c; cout << int(c) << " "; i++; (LN 2-2) Flow-of-Control Matching between if-else How to correct the code: int temperature; cin >> temperature; Testing: Input 50. What will it show? if (temperature < 100) if (temperature <= 0) cout << "Water is frozen\n"; else cout << "Water is all boiled away\n"; 1/20

2 While-loop, do-while loop, for-loop int total, count, mark; total = 0; count = 1; while (count <=10) cout << "Enter marks: "; cin >> mark; total += mark; count +=1; - Why "total/10.0"? - Rewrite using do-while and for-loops. cout << "Average of 10 students = " << total/10.0 << endl; Empty statement (say, in an while-loop) Some common programming mistakes: - for (i=0;i<10;i++); - i=0; while (i<10);.. i++; continue / break (CS2331 Lec12) - Not encouraged to use them Continue means "skip to next iteration of this loop." break means "immediately halt execution of this loop" switch-case (CS2331 Lec05) - In switch(expr), expr must have integral data type (int, char and bool). - The case values (expr1, exprn) must be constant expressions and must be all different. // To print no. of days in a month int month; cin >> month; switch (month) case 1: case 3: case 5: case 7: case 8: case 10: case 12: cout << "31 days"; break; case 4: case 6: case 9: case 11: cout << "30 days"; break; case 2: cout << "28 or 29 days"; break; default: cout << "input error"; break; 2/20

3 (LN 2-3) Functions Call-by-value and Call-by-reference Suppose we want a function to increment a counter (as parameter) from time to time. We should apply Call-by-reference (see explanation below). Using call-by-value to pass the counter Using call-by-reference to pass the counter //Add one to the counter and display void addone(int c) c++; cout <<"It is now " << c << endl; int counter=0; addone(counter); addone(counter); addone(counter); addone(counter); addone(counter); //Add one to the counter and display void addone(int &c) c++; cout <<"It is now " << c << endl; int counter=0; addone(counter); addone(counter); addone(counter); addone(counter); addone(counter); Result: Can't do! Result: It works! What is call-by-value: In Call-by-value, The argument (counter) is evaluated, and its value is copied to the corresponding parameter (c - where c in addone is just like a local variable). Any changes made on the parameter (c) have no effect on the argument (counter). Pictorially, What is call-by-reference: In Call-by-reference, The argument passed must be a variable (counter). During the function call, the call-by-reference parameter (c) actually refers to this variable (counter). Therefore, changes made on a call-by-reference parameter will actually be done on the corresponding argument. Pictorially, 1 c Created upon each invocation of addone. Destroyed after the execution of addone is finished. 0 counter 5 c and counter refers to the same item in the memory. 3/20

4 Function Prototype Functions should be declared before they are used. Style 1: Define the function before calling it void DoSomething().... DoSomething();.. Style 2: Write function prototype before function calls Function call.. void DoSomething();.. DoSomething();.. Don't forget this semi-colon. Function definition.. void DoSomething().. Driver Programs Example, ".. write a driver program ( ie. just add a main() function ) to test your function." (LN 2-4) Arrays (A) What a Primitive array! An array is just primitively a memory address where a block of memory is allocated for one specific data type. Don t expect to call A.length, A.getAt, etc.. (An array is not a class/template object!!) Don t expect to set or change the array size during run-time: int total; cout << "Please input total: "; cin >> total; int A[total]; Though DEV-C++ etc.. permit this code, but it is not accepted in standard C++ lang.. Visual Studio gives compilation error!! 4/20

5 When defining an array, the size must be a constant. Example: There are 2 errors in the code below. Find them out. #define n1 30; const int n2=40; char array1[n1]; char array2[n2]; int n3; cout << "Please input a number for n3"; cin >> n3; char array3[n3]; //... some work to do on n1,n2,n3 cout << "Thank you.\n"; Storage mechanism for Arrays When defining int marks[5];, the 5 integer variables are stored in contiguous memory locations: (hypothetic) marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[5] is invalid (programming error), but may not prohibited by the compiler. If not prohibited, marks[5] will be interpreted as an integer; although the location may actually store other types of data. Suppose each integer takes 4 bytes, the array occupies locations 1000 to The Watch Window shows you: the value of marks is actually the address!! (B) Actual array size and Effective array size Sample run: Input n: 7 Input 7 marks: After adding bonus: Press any key to continue... < MARK_ARR_SIZE < n > #include <iostream> using namespace std; const int MARK_ARR_SIZE=100; int marks[mark_arr_size], i, n; cout << "Input n: "; cin >> n; cout << "Input " << n << " marks: "; for (i=0;i<n;i++) cin >> marks[i]; //.. Recall : the compiler must know the actual array size early at compile time. Here we - use const int MARK_ARR_SIZE for the actual array size, and - use int n for the effective array size 5/20

6 (C) Different ways to initialize an array int marks[5]=27, 31, 25, 50, 70; List fewer values than the array size => remaining array elements are initialized to zero: If you initialize an array when it is declared, you can omit the size, e.g., int marks[]=34, 87, 72, 65; is equivalent to int marks[4]=34, 87, 72, 65; If we omit the size, it is automatically calculated according to the initializing values given (here size is 4) int marks[5]=51,52,53,54,55; int marks[5]=51,52; int marks[5]=0,0,0,0,0; int marks[5]=0; int marks[5]; int marks[ ]=51,52,53,54,55; int marks[ ]=0,0,0,0,0; ????? Not initialized int marks[ ]=0; int marks[ ]; 0 If no initializer, we must NOT leave the array size empty (compilation error) (D) Passing arrays to functions Can Arrays be RETURNED? Answer: No! int some_function(..); char some_function(..); double some_function(..); bool some_function(..); int[] some_function(..); char[] some_function(..); double[] some_function(..); bool[] some_function(..); Therefore, we pass "array parameters" (The default mechanism is a weak form of call-by-reference, through which the caller's array contents can be directly changed.) Recall: the associated value of an array name (eg. marks) is actually the address of the array (eg. int marks[5];) 6/20

7 The common format for passing an array into a function: #include <iostream> using namespace std; const int MARK_ARR_SIZE=100; // read integers from console and store in an array void input_into_arr(int arr[], int size) for (int i=0; i<size; i++) cin >> arr[i]; int marks[mark_arr_size], i, n; cout << "Input n: "; cin >> n; cout << "Input " << n << " marks: "; input_into_arr(marks,n); for (i=0;i<n;i++) marks[i]+=10; cout << "After adding bonus: "; for (i=0;i<n;i++) cout << marks[i] << " "; cout << endl; Sample run: Input n: 7 Input 7 marks: After adding bonus: Press any key to continue... Array Parameter void input_into_arr(int arr[], int size) The first parameter (int arr[]) is called an array parameter int arr[n] (1) We often DON'T specify the size in the array parameter (no need actually ignored by the compiler ). (2) An array parameter is a weak form of call-by-reference parameter (**) in which the starting memory address of the array is told to the function (but the size of the array is not told). Advantage: arrays of different sizes can use the same function, as long as they have the same base type (above is int) (3) Adding & is not needed: void input_into_arr(int &arr[], int size) 7/20

8 Omitting the parameter for effective size (if array's effective size is known, eg. equal to actual size) #include <iostream> using namespace std; const int N=5; // read integers from console and store in an array void input_into_arr(int arr[], int size) for (int i=0; i<size; i++) cin >> arr[i]; N int marks[n], i; cout << "Input " << N << " marks: "; input_into_arr( marks,n ); for (i=0;i<n;i++) marks[i]+=10; cout << "After adding bonus: "; for (i=0;i<n;i++) cout << marks[i] << " "; cout << endl; ** However, if you want to make the function useful as well in other occasions (or other programs) which do not restrict to the size N, then you better keep the original approach: keep int size as parameter and pass the argument in function call. Passing arguments: array vs array element #include <iostream> using namespace std; const int MARK_ARR_SIZE=100; //swap the contents of 2 input arguments. void swap(int &x1, int &x2) int temp; temp=x1; x1=x2; x2=temp; // read integers from console and store in an array void input_into_arr(int arr[], int size) for (int i=0; i<size; i++) cin >> arr[i]; Sample run: Input n: 5 Input 5 marks: After swapping: Press any key to continue.. Passing an array ( array_name ) int marks[mark_arr_size],i,n; Passing 2 array elements (array_name [ array_index ]) cout << "Input n: "; cin >> n; cout << "Input " << n << " marks: "; input_into_arr( marks, n ); swap( marks[0], marks[4] ); cout << "After swapping: "; for (i=0;i<n;i++) cout << marks[i] << " "; cout << endl; Self-test: Why don't we add & to marks: void input_into_arr(int &arr[], int size) 8/20

9 (E) const parameter modifier If the function is not to change the array contents, add const to the array parameter like:.. // display integer items stored in an array void display_arr_items( const int arr[], int size) int i; for (i=0; i<size; i++) cout << arr[i] << " "; int marks[5]=80,81,82,83,84; display_arr_items(marks,5); We say, "I don t want the function call display_arr_items(marks,n); to modify marks. Now the array parameter has the const modifier. I feel safe." - The const modifier indicates that the array parameter should not be changed. - If violated (eg. typing "=" by mistake: "if (arr[i]=100)"), the compiler will give compilation error and the program can't run. Note: We should use the const modifier on an all-or-nothing basis, eg., the following will cause a compilation error. Line A=> // display one integer item void display_one( int arr[], int index ) cout << arr[index] << " "; Missing const Line B=> // display integer items stored in an array void display_arr_items(const int arr[], int size) for (int i=0; i<size; i++) display_one(arr,i); - In the above, const is missing at line A. - The compiler will give compilation error at line B: 'display_one' : cannot convert parameter 1 from 'const int []' to 'int []' Reason: The compiler thinks that at line B, the call to display_one may change the value of the parameter arr. But arr is a const array parameter of display_arr_items that mustn't be changed compilation error: 9/20

10 (F) Multidimentional Arrays Start-up Questions: (1) Fill in the blank below, so that the data array can be passed to the testing function. #include <iostream> using namespace std; void testing( ) //.. some processing int data[5][4][3]; testing(data); //.. some processing (2) Suppose the above data[5][4][3] array is to represent a 3D table (several sheets, each sheet has some rows/columns). Which one of the below is the best match? (a) (b) (c) (d) (e) (f) 10/20

11 2-dimensional array Pictorially: int values[6][10]; is an array of 6 rows: Row 0 (an array of 10 integers) Row 1 (an array of 10 integers) Row 2 (an array of 10 integers) Row 3 (an array of 10 integers) Row 4 (an array of 10 integers) Row 5 (an array of 10 integers) You can think of it as an array of 6 arrays (each of these 6 arrays is an array of 10 integers). Actual storage in the memory: int values[6][10]; Row 0 values[0][0] W: number of columns H: number of rows Row 1 Between values[0][0] and values[2][7], there are 2 rows + 7 elements Row 2 cout << values[2][7]; values[2][7] Suppose values[0][0] is at location And the size of an integer is 4 bytes. Row 3 From the example (or observe the picture), Row 4 The location of values[2][7] is at : = location (2* ) * 4 Row 5 = location 1108 W 4 bytes per integer Note: Calculation of values[2][7] is based on the number of columns W (2 nd dimension), but NOT the number of rows H (1 st dimension), 11/20

12 3-dimensional array int values[5][4][3]; declares a 3-dimensional array of integers 1 st index 2 nd index 3 nd index An array of 5 pages: Page 0 (a 2D array: 4x3) Page 1 (a 2D array: 4x3) Page 2 (a 2D array: 4x3) Page 3 (a 2D array: 4x3) Page 4 (a 2D array: 4x3) Actual storage in the memory: int values[5][4][3]; cout << values[3][1][2]; Suppose values[0][0][0] is at location And the size of an integer is 4 bytes. From this example (or observe the picture), Each row has 3 elements. Each page has 12 elements (ie. 4x3 elements). The location of values[3][1][2] is: = location (3*4*3 + 1*3 + 2) * 4 = location 1164 W: number of columns H: number of rows P: number of pages H * W W 4 bytes per integer Row 0 Row 1 Row 2 Row 3 Row 0 Row 1 Row 2 Row 3 Row 0 Row 1 Row 2 Row 3 Row 0 Row 1 Row 2 Row 3 Row 0 Row 1 Row 2 Row 3 Page 0 Page 1 Page 2 Page 3 Page 4 Note from the above: Calculation of values[3][1][2] is based on H and W (2 nd and 3 rd dimensions), but NOT the number of pages P (1 st dimension), Similarly, for other kinds of arrays (4D, 5D,..), the 1 st dimension is not needed. (But the remaining dimensions are needed.) As a result, the compiler doesn't need to know it for multidimensional array parameters: Omit P void display(const int data[][4][3], int size) Passing a Multidimensional Array: All the dimension sizes except the first must be specified in the function header. E.g., void display(const int data[][10], int size) void display(const int data[][4][3], int size) 12/20

13 (LN 2-5) File I/O To handle File I/O, we use the ifstream and ofstream classes (in <fstream>) Example: Read the width and height from a file and output a rectangle of asterisks (*) #include <iostream> #include <fstream> using namespace std; ifstream infile; int width, height, i, j; char filepathname[300]; cout << "Please input the file pathname: "; cin >> filepathname; infile.open(filepathname); infile >> width >> height; for (i=0;i<height;i++) for (j=0;j<width;j++) cout << '*'; cout << endl; infile.close(); Please input the file pathname: 1.txt *** *** *** *** *** Press any key to continue... To output contents to a file, write ofstream outfile; outfile.open(filepathname); /* where filepathname is a string (character array) */ outfile << "some contents to be added to the file"; outfile.close(); 13/20

14 Detecting end-of-file End Of File Member function eof() returns true if and only if the program has attempted to read from the input file beyond the end of the file: Only for input files (objects of class ifstream). We typically read a value into a variable and then process the value in the variable. Before processing with the variable, we may use.fail() to check whether the program has actually failed in reading any value into the variable. (This is essential in certain cases. Example: if the file may have extra blank line(s) at the end, then "not yet end-of-file" doesn't guarrentee a sucessful reading.) Example: Extra blank line (newline character) #include <fstream> #include <iostream> using namespace std; ifstream in_stream; int x; Code A I in_stream.open("infile.txt"); while (!in_stream.eof())// ie. if in_stream.eof() is NOT true in_stream >> x; if (!in_stream.fail()) cout << x << endl; in_stream.close(); Note: If we remove "if (!in_stream.fail())" Then we may get a wrong result (17 is displayed twice). Explanation: In Code B: After reading 25, then 4, then 17, in_stream.eof() is still false (because the reading of 17 stops at the newline character, so "end-of-file" hasn't been known), so the while-loop will run the 4 th time. while (!in_stream.eof()) Code B (Wrong) in_stream >> x; if (!in_stream.fail()) cout << x << endl; Press any key to continue... When the loop runs the 4 th time, "in_stream >> x" will encounter end-of-file. It cannot read a new value. Since no checking is done, "cout << x << endl;" will display the old value of x again => WRONG result. The expression in_stream >> x has value 0 if in_stream has no more data E.g. #include <fstream> #include <iostream> using namespace std; ifstream in_stream; int x; in_stream.open("infile.txt"); while ( (in_stream >> x)!=0 ) //or simply: while (in_stream >> x) cout << x << endl; in_stream.close(); 14/20

15 File doesn't exist? Use of.fail() after file opening: If fail, then terminate the program with exit(). ifstream infile; infile.open(filepathname); if (infile.fail()) cout << "Cannot open file\n"; exit(1); // 1 stands for error, program ended. (LN 2-6) Exercises (Test all your programs in PASS except Q5 and Q6) LN2-Q1. [ Sample Question paper Q1 ] Code Fixing In Q1 of the Sample Question paper (available at the course web), the function count_0_to_100 is wrong in logic and syntax. Download the complete program from the course web and fix it. Hint: - There are more than 10 errors. - We need to type A[][WIDTH] instead of A[][] for the function parameter. After fixing, the program should output the following result (No user input is needed): The count is: 25 You should - Submit the program to PASS for correctness checking (only 1 test case: no input) - Afterwards you may further modify the main function and values of the WIDTH and HEIGHT constants for more testing on your own. LN2-Q2. Flow of Control - Multiplication Table Write a C++ program that prints out a 9 x 9 multiplication table as shown below: Sample output: This is a 9 x 9 multiplication table Suggestion: (Approach A) nested for-loops (2 levels) Another approach (B) is to use only one for-loop, but that is a bit tricky. If you use approach B, you need to design a way to determine the line breaks, and also the changes on product factors. Tips: To align the columns properly, use setw(). setw is provided by <iomanip>. Suggested solution/approach is available at the course web (Download Area) 15/20

16 LN2-Q3. Merging two lists Write a function that merges two sorted integer arrays into one sorted integer array: Inputs Outputs source1[] name of the first sorted array size1 size of first array source2[] name of second sorted array size2 size of second array result[] name of array for storing the result size size of resultant array result[] store the merged array size store the size of the merged array Assuming each input array has size at most 10, write a driver program ( ie. just add a main() function ) to test your function. For easy debugging at the early stage, you may hard-code the input arrays to some fixed values. When the merge function is fully debugged, you may write a function to input an array and another function for display. Follow the input/output format shown below. Sample input and output: size of source1[]: 4 element(s) of source1[]: size of source2[]: 3 element(s) of source2[]: Size of result[]: 7 Element(s) of result[]: Press any key to continue... Underlined contents are input by the user Note that size of result (7) should be generated by the program (not input by user). Suggested solution/approach is available at the course web (Download Area) LN2-Q4. Minesweeper Write a program to input an H x W array of 0 s and 1 s where H and W are also user inputs. You may assume that both H and W are non-zero and at most 10. The array represents an H x W minefield so that a cell with a 1 (resp. 0) means the cell contains (does not contain) a bomb. Your program should print the minefield as follows: (1) If a cell contains a bomb, print a `#. (2) If a cell does not contain a bomb and is not adjacent to any bomb, print a `. (3) Otherwise, print the number of neighboring bombs. Sample input and output: Enter H and W: 5 5 Enter the minefield: #32#1 ## #...11 Underlined contents are input by the user Suggested solution/approach is available at the course web (Download Area) 16/20

17 LN2-Q5. File I/O Write a program to read in pairs of integers from an input file (Infile1.dat) and output the sum of each pair to an output file (Outfile1.dat). The number of pairs is specified in the first line of Infile1.dat, subsequent lines contain one pair of integers on each line. Use number of pairs to control the loop (not to use eof()). Use fail() to check for file-opening and reading. Here s a sample input and output: ** Please find the test cases at the course web. ** Sample Infile1.dat Corresponding Outfile1.dat should contain: [ Testing is NOT AVAILABLE in PASS for this question. ] LN2-Q6. File I/O Same as last question, but the number of pairs is not specified. Use eof() to detect end of input, and fail() to check for file-opening and reading. ** Please find the test cases at the course web. * Sample Infile2.dat Corresponding Outfile2.dat should contain: [ Testing is NOT AVAILABLE in PASS for this question. ] 17/20

18 LN2-Q7. Call-by-reference Simple Statistics Example 1 Please input the total count: 6 Please input a value: 2 Please input a value: 3 Please input a value: 3 Please input a value: 4 Please input a value: 4 Please input a value: 4 Result: average= , median=3.5, mode=4 Example 2 Please input the total count: 5 Please input a value: 2 Please input a value: 3 Please input a value: 3 Please input a value: 4 Please input a value: 5 Result: average=3.4, median=3, mode=3 Underlined contents are input by the user Write a C++ function that finds the average, median, and mode of the integers in an array. The function should return nothing: void function_name(..) The function should have the following parameters: (1) array (2) total count of items in the array (3) [call-by-reference] average, median, mode values. (To find out what are average, median, and mode, you my use the help in Microsoft Excel.) Implement the main function that calls the above function to work like the examples above: Assumptions and guidelines: - All input values are within 0 to The input numbers are already in non-descending order. - If the total count is even, the median should be the average of the middle 2 values. Eg. the median of 2,3,4,5,5 is 4 the median of 3,3,4,5 is Assume that the mode value is unique. That is, no 2 integers have the same maximum count. - The default maximum precision for floating point numbers in C++ is 6. For this question, we just leave it in the normal way that C++ behaves. Suggested solution/approach is available at the course web (Download Area) LN2-Q8. Poker game Write a program to input five integers in the range [1,13] and determine if they are consecutive. Hint: Define an array of size 13 to count the frequency of each value in [1,13]. Sample input and output: Enter 5 integers in [1,13]: A straight Underlined contents are input by the user Sample input and output: Enter 5 integers in [1,13]: Not a straight Underlined contents are input by the user Suggested solution/approach is available at the course web (Download Area) 18/20

19 LN2-Q9. Rounding Off Write a function to round off a floating-point number n (of type double) to the nearest 10 k th where k is another function parameter. The layout of the driver program is given as follows: (Available for download at the course web) // Round up n to the nearest 10^kth #include <iostream> #include <math.h> using namespace std; int funcround(double n, int k) // Precondition : n >= 0, k >= 0 // Postcondition: return n rounded off to the nearest 10^k (return n // rounded off to the nearest integer if k == 0) // put your code here double parn; // parameter n int park; // parameter k cout << "Enter a floating-point number n: "; cin >> parn; cout << "Enter an integer k: "; cin >> park; cout << parn << " rounded to the nearest 10^" << park << " = " << funcround(parn, park) << endl; Sample input and output: Input n Input k Output Tips: You may use library functions provided by <math.h>, e.g. ceil(), pow() etc. Mind the data types!!! For example, suppose k and x are integers, then: - pow(10,k) is wrong. It should be pow(10.0,k). - ceil(x/2) is wrong. It should be ceil(x*0.5) or ceil(7/2.0). Reason: pow has several forms for float and double. If you pass an integer argument (eg. 10), then it can't resolve to which specific version. Visual Studio will give compilation error on pow(10,k): It won t determine for you whether to use the double form or the float form. Suggested solution/approach is available at the course web (Download Area) 19/20

20 LN2-Q10. Palindrome detection A palindrome is a word that is spelled the same forward and backward. For example, radar and noon are palindromes. Write a program that repeatedly accepts a string of letters (all in lowercase) and determines whether or not the string is a palindrome. Each input string is at most 20 letters long and is terminated by a period '.' while the program is terminated by an empty string: '.'. Input and output Sample 1: radar.abc.. true false Underlined contents are input by the user Input and output Sample 2: abcdefghijjihgfedcba.dddd.. true true Underlined contents are input by the user Suggested solution/approach is available at the course web (Download Area) --- end /20

What we will learn about this week:

What we will learn about this week: What we will learn about this week: Streams Basic file I/O Tools for Stream I/O Manipulators Character I/O Get and Put EOF function Pre-defined character functions Objects 1 I/O Streams as an Introduction

More information

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points) Name Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Relational Expression Iteration Counter Count-controlled loop Loop Flow

More information

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

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible) 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 information

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

Multiple 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 information

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 I/O Streams as an Introduction to Objects and Classes Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Slide 6-3 6.1 Streams and Basic File I/O I/O Streams I/O

More information

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

Multiple 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 information

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

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible) 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 information

Simple File I/O.

Simple File I/O. Simple File I/O from Chapter 6 http://www.cplusplus.com/reference/fstream/ifstream/ l / /f /if / http://www.cplusplus.com/reference/fstream/ofstream/ I/O Streams I/O refers to a program s input and output

More information

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects Chapter 6 I/O Streams as an Introduction to Objects and Classes Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Copyright 2008 Pearson Addison-Wesley. All rights reserved.

More information

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam. Name: Print legibly! Section: COMPUTER SCIENCE 261 PROGRAMMING CONCEPTS EXAM 1 VERSION 1 Fall 2014 150 Points Absolutely no electronic devices may be used during this exam. 1. No cell phones, computers,

More information

File I/O CS 16: Solving Problems with Computers I Lecture #9

File I/O CS 16: Solving Problems with Computers I Lecture #9 File I/O CS 16: Solving Problems with Computers I Lecture #9 Ziad Matni Dept. of Computer Science, UCSB I/O Data Streams and File I/O Lecture Outline An introduction to Objects and Member Functions Handling

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams Basic I/O 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:

More information

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

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size

More information

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9 File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9 Ziad Matni Dept. of Computer Science, UCSB Midterm Exam grades out! Announcements If you want to see your exams, visit

More information

Name Section: M/W T/TH Number Definition Matching (6 Points)

Name Section: M/W T/TH Number Definition Matching (6 Points) Name Section: M/W T/TH Number Definition Matching (6 Points) 1. (6 pts) Match the words with their definitions. Choose the best definition for each word. Event Counter Iteration Counter Loop Flow of Control

More information

Programming in C/C

Programming in C/C Programming in C/C++ 2004-2005 http://cs.vu.nl/~nsilvis/c++/2005 Natalia Silvis-Cividjian e-mail: nsilvis@few.vu.nl Topics about C++ language about this course C++ basics self test exercises (10 min) (10

More information

Name Section: M/W T/TH Number Definition Matching (8 Points)

Name Section: M/W T/TH Number Definition Matching (8 Points) Name Section: M/W T/TH Number Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Iteration Counter Event Counter Loop Abstract Step

More information

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.

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. 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. B. Outputs to the console a floating point number f1 in scientific format

More information

Week 5: Files and Streams

Week 5: Files and Streams CS319: Scientific Computing (with C++) Week 5: and Streams 9am, Tuesday, 12 February 2019 1 Labs and stuff 2 ifstream and ofstream close a file open a file Reading from the file 3 Portable Bitmap Format

More information

Why Is Repetition Needed?

Why Is Repetition Needed? Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable

More information

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents File I/O 1 File Names and Types A file name should reflect its contents Payroll.dat Students.txt Grades.txt A file s extension indicates the kind of data the file holds.dat,.txt general program input or

More information

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

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

More information

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver) 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 information

CPE Summer 2015 Exam I (150 pts) June 18, 2015

CPE Summer 2015 Exam I (150 pts) June 18, 2015 Name Closed notes and book. If you have any questions ask them. Write clearly and make sure the case of a letter is clear (where applicable) since C++ is case sensitive. You can assume that there is one

More information

Chapter 12. Streams and File I/O

Chapter 12. Streams and File I/O Chapter 12 Streams and File I/O Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag settings Introduction Streams Special objects Deliver

More information

Chapter 3 - Notes Input/Output

Chapter 3 - Notes Input/Output Chapter 3 - Notes Input/Output I. I/O Streams and Standard I/O Devices A. I/O Background 1. Stream of Bytes: A sequence of bytes from the source to the destination. 2. 2 Types of Streams: i. Input Stream:

More information

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration) Week 7: Advanced Loops while Loops in C++ (review) while (expression) may be a compound (a block: {s) Gaddis: 5.7-12 CS 1428 Fall 2015 Jill Seaman 1 for if expression is true, is executed, repeat equivalent

More information

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

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011 The American University in Cairo Department of Computer Science & Engineering CSCI 106-07&09 Dr. KHALIL Exam-I Fall 2011 Last Name :... ID:... First Name:... Form I Section No.: EXAMINATION INSTRUCTIONS

More information

Basic 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 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 information

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

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016 Chapter 6: User-Defined Functions Objectives In this chapter, you will: Learn about standard (predefined) functions Learn about user-defined functions Examine value-returning functions Construct and use

More information

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?

More information

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

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 12 Streams and File I/O Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag

More information

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 12 Streams and File I/O Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output,

More information

pointers + memory double x; string a; int x; main overhead int y; main overhead

pointers + memory double x; string a; int x; main overhead int y; main overhead pointers + memory computer have memory to store data. every program gets a piece of it to use as we create and use more variables, more space is allocated to a program memory int x; double x; string a;

More information

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

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

WARM UP LESSONS BARE BASICS

WARM UP LESSONS BARE BASICS WARM UP LESSONS BARE BASICS CONTENTS Common primitive data types for variables... 2 About standard input / output... 2 More on standard output in C standard... 3 Practice Exercise... 6 About Math Expressions

More information

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency Introduction Fundamentals Declaring arrays Indexing arrays Initializing arrays Arrays and functions Multidimensional arrays Sorting and algorithm efficiency An array is a sequence of values of the same

More information

Getting started with C++ (Part 2)

Getting started with C++ (Part 2) Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output

More information

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

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;

More information

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12 CS31 Discussion 1E Jie(Jay) Wang Week3 Oct.12 Outline Problems from Project 1 Review of lecture String, char, stream If-else statements Switch statements loops Programming challenge Problems from Project

More information

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

Name SECTION: 12:45 2:20. True or False (12 Points) Name SECION: 12:45 2:20 rue or False (12 Points) 1. (12 pts) Circle for true and F for false: F a) Local identifiers have name precedence over global identifiers of the same name. F b) Local variables

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

Scientific Computing

Scientific Computing Scientific Computing Martin Lotz School of Mathematics The University of Manchester Lecture 1, September 22, 2014 Outline Course Overview Programming Basics The C++ Programming Language Outline Course

More information

C++ Quick Guide. Advertisements

C++ Quick Guide. Advertisements C++ Quick Guide Advertisements Previous Page Next Page C++ is a statically typed, compiled, general purpose, case sensitive, free form programming language that supports procedural, object oriented, and

More information

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

I/O Streams and Standard I/O Devices (cont d.) Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Lesson 2 Variables and I/O

Lesson 2 Variables and I/O Lesson 2 Variables and I/O Pic 10A Ricardo Salazar Free form layout C++ lets you use spaces and returns (enter key) wherever you see fit. cout

More information

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

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping). 1 causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping). Before considering specifics we define some general terms that

More information

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

Name Section: M/W or T/TH. True or False (14 Points) Name Section: M/W or T/TH True or False (14 Points) 1. (14 pts) Circle T for true and F for false: T F a) In C++, a function definition should not be nested within another function definition. T F b) Static

More information

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

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points) Name rue or False (12 Points) 1. (12 pts) Circle for true and F for false: F a) Local identifiers have name precedence over global identifiers of the same name. F b) Local variables retain their value

More information

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

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF

More information

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing Input Data 1 Streams 2 Streams Conceptual Model of a Stream Associating a File Stream with a File Basic Stream Input Basic Stream Output Reading Single Characters: get() Skipping and Discarding Characters:

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

Lecture 3 The character, string data Types Files

Lecture 3 The character, string data Types Files Lecture 3 The character, string data Types Files The smallest integral data type Used for single characters: letters, digits, and special symbols Each character is enclosed in single quotes 'A', 'a', '0',

More information

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() { Text File I/O We can use essentially the same techniques we ve been using to input from the keyboard and output to the screen and just apply them to files instead. If you want to prepare input data ahead,

More information

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

C++ 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 information

Lab 10: Alternate Controls

Lab 10: Alternate Controls _ Unit 2: Programming in C++, pages 1 of 8 Department of Computer and Mathematical Sciences CS 1410 Intro to Computer Science with C++ 9 Objectives: Lab 10: Alternate Controls The objective of this lab

More information

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types. The C++ Language Input and Output Output! Output is information generated by a program.! Frequently sent the screen or a file.! An output stream is used to send information. Another type supplied by C++

More information

Computer Science II Lecture 1 Introduction and Background

Computer Science II Lecture 1 Introduction and Background Computer Science II Lecture 1 Introduction and Background Discussion of Syllabus Instructor, TAs, office hours Course web site, http://www.cs.rpi.edu/courses/fall04/cs2, will be up soon Course emphasis,

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Chapter 5: Loops and Files

Chapter 5: Loops and Files Chapter 5: Loops and Files 5.1 The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1;

More information

PROGRAMMING EXAMPLE: Checking Account Balance

PROGRAMMING EXAMPLE: Checking Account Balance Programming Example: Checking Account Balance 1 PROGRAMMING EXAMPLE: Checking Account Balance A local bank in your town is looking for someone to write a program that calculates a customer s checking account

More information

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

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 Date: 01/18/2011 (Due date: 01/20/2011) Name and ID (print): CHAPTER 6 USER-DEFINED FUNCTIONS I 1. The C++ function pow has parameters.

More information

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:

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: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

Chapter void Test( int, int, int ); // Function prototype int main() // Function heading { int h; // Local variable

Chapter void Test( int, int, int ); // Function prototype int main() // Function heading { int h; // Local variable EXERCISE ANSWERS Chapter 7 Exam Preparation Exercises 1 Function call The mechanism that transfers control to the body of a function Argument list A mechanism by which functions communicate with each other;

More information

Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance

Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance Chapter 6 In this chapter, you will learn about: Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance Streams and Basic File I/O I refers to the program Input O refers to program Output:

More information

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1 Chapter 5: Loops and Files The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix)

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

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

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ 0.1 Introduction This is a session to familiarize working with the Visual Studio development environment. It

More information

Objects and streams and files CS427: Elements of Software Engineering

Objects and streams and files CS427: Elements of Software Engineering Objects and streams and files CS427: Elements of Software Engineering Lecture 6.2 (C++) 10am, 13 Feb 2012 CS427 Objects and streams and files 1/18 Today s topics 1 Recall...... Dynamic Memory Allocation...

More information

Program Organization and Comments

Program 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 information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 2.11 Assignment Operators 2.12 Increment and Decrement Operators 2.13 Essentials of Counter-Controlled Repetition 2.1 for Repetition Structure 2.15 Examples Using the for

More information

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1] CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1] LEARNING OBJECTIVES Upon completion, you should be able to: o define C++ text files o explain the benefits of using I/O file processing o explain

More information

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

CS201 Spring2009 Solved Sunday, 09 May 2010 14:57 MIDTERM EXAMINATION Spring 2009 CS201- Introduction to Programming Question No: 1 ( Marks: 1 ) - Please choose one The function of cin is To display message

More information

Introduction to C ++

Introduction 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

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

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 CS 117 Programming II, Spring 2018 Dr. Ghriga Midterm Exam Estimated Time: 2 hours March 21, 2018 DUE DATE: March 28, 2018 at 12:00 PM INSTRUCTIONS: Do all exercises for a total of 100 points. You are

More information

Department of Computer and Mathematical Sciences. Lab 10: Functions. CS 1410 Intro to Computer Science with C++

Department 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 information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Winter 2011 Lecture 05 - I/O using the standard library & Introduction to Classes Milena Scaccia School of Computer Science McGill University February 1, 2011 Final note on

More information

Programming Language. Functions. Eng. Anis Nazer First Semester

Programming Language. Functions. Eng. Anis Nazer First Semester Programming Language Functions Eng. Anis Nazer First Semester 2016-2017 Definitions Function : a set of statements that are written once, and can be executed upon request Functions are separate entities

More information

Exercise 1.1 Hello world

Exercise 1.1 Hello world Exercise 1.1 Hello world The goal of this exercise is to verify that computer and compiler setup are functioning correctly. To verify that your setup runs fine, compile and run the hello world example

More information

Fundamentals of Programming CS-110. Lecture 2

Fundamentals 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 information

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

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

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

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type. CS 7A - Fall 2016 - Midterm 1 10/20/16 Write responses to questions 1 and 2 on this paper or attach additional sheets, as necessary For all subsequent problems, use separate paper Do not use a computer

More information

CS2255 HOMEWORK #1 Fall 2012

CS2255 HOMEWORK #1 Fall 2012 CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The

More information

A SHORT COURSE ON C++

A SHORT COURSE ON C++ Introduction to A SHORT COURSE ON School of Mathematics Semester 1 2008 Introduction to OUTLINE 1 INTRODUCTION TO 2 FLOW CONTROL AND FUNCTIONS If Else Looping Functions Cmath Library Prototyping Introduction

More information

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York CSc 10200 Introduc/on to Compu/ng Lecture 19 Edgardo Molina Fall 2011 City College of New York 18 Standard Device Files Logical file object: Stream that connects a file of logically related data to a program

More information

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator:

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator: Chapter 7: 7.1 Arrays Arrays Hold Multiple Values Arrays Hold Multiple Values Array - Memory Layout A single variable can only hold one value int test; 95 Enough memory for 1 int What if we need to store

More information

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

Review of Important Topics in CS1600. Functions Arrays C-strings Review of Important Topics in CS1600 Functions Arrays C-strings Array Basics Arrays An array is used to process a collection of data of the same type Examples: A list of names A list of temperatures Why

More information

Input and Output File (Files and Stream )

Input and Output File (Files and Stream ) Input and Output File (Files and Stream ) BITE 1513 Computer Game Programming Week 14 Scope Describe the fundamentals of input & output files. Use data files for input & output purposes. Files Normally,

More information

LAB: WHILE LOOPS IN C++

LAB: 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 information

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

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. Week 3 Functions & Arrays Gaddis: Chapters 6 and 7 CS 5301 Fall 2015 Jill Seaman 1 Function Definitions! Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements... Where

More information

Multiple Choice Questions (20 questions * 6 points per question = 120 points)

Multiple Choice Questions (20 questions * 6 points per question = 120 points) EECS 183 Fall 2014 Exam 2 Closed Book Minimal Notes Closed Electronic Devices Closed Neighbor Turn off Your Cell Phones We will confiscate all electronic devices that we see including cell phones, calculators,

More information

BITG 1113: Files and Stream LECTURE 10

BITG 1113: Files and Stream LECTURE 10 BITG 1113: Files and Stream LECTURE 10 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of input & output files. 2. Use data files for input & output

More information

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:

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: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information