Programming in C/C

Similar documents
Programming in C/C

Programming in C/C

What we will learn about this week:

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

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

Chapter 12. Streams and File I/O

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

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

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

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

Simple File I/O.

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

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

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

Programming in C/C Lecture 2

Programming in C/C++ Lecture 1

Scientific Computing

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

CS2141 Software Development using C/C++ Stream I/O

C++ Input/Output: Streams

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

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

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

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

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

WARM UP LESSONS BARE BASICS

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

File I/O Christian Schumacher, Info1 D-MAVT 2013

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

A SHORT COURSE ON C++

CS3157: Advanced Programming. Outline

Summary of basic C++-commands

C++ for Python Programmers

Chapter 3 - Notes Input/Output

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

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

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

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.

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

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

Introduction to C++ Systems Programming

Programming. C++ Basics

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Software Design & Programming I

Introduction to C ++

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Introduction to C++ Introduction to C++ 1

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

Definition Matching (10 Points)

C++ Quick Guide. Advertisements

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

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

do { statements } while (condition);

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

Introduction to C++ (Extensions to C)

OBJECT ORIENTED PROGRAMMING

We will exclusively use streams for input and output of data. Intro Programming in C++

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

Introduction to C++ Dr M.S. Colclough, research fellows, pgtas

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

Chapter 2 Basic Elements of C++

Engineering Problem Solving with C++, Etter/Ingber

UEE1303(1070) S 12 Object-Oriented Programming in C++

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

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

Chapter 3: Expressions and Interactivity. Copyright 2012 Pearson Education, Inc. Thursday, October 9, 14

Getting started with C++ (Part 2)

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

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

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

C++ Input/Output Chapter 4 Topics

More File Operations. Lecture 17 COP 3014 Spring april 18, 2018

CSCE 110 PROGRAMMING FUNDAMENTALS

Computing and Statistical Data Analysis Lecture 3

More on File I/O Strings in C++ CS 16: Solving Problems with Computers I Lecture #10

COMP322 - Introduction to C++

C++ does not, as a part of the language, define how data are sent out and read into the program

Lab Instructor : Jean Lai

The C++ Language. Arizona State University 1

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1

Chapter 2. Outline. Simple C++ Programs

CSCE 206: Structured Programming in C++

CS103L SPRING 2018 UNIT 7: FILE I/O

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

C++ For Science and Engineering Lecture 12

Streams. Rupesh Nasre.

C++ basics Getting started with, and Data Types.

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

3.1. Chapter 3: The cin Object in Program 3-1. Displaying a Prompt 8/23/2014. The cin Object

Chapter 3: Expressions and Interactivity

Programming II with C++ (CSNB244) Lab 10. Topics: Files and Stream

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

File I/O and String Manipula3ons CS 16: Solving Problems with Computers I Lecture #11

Program Organization and Comments

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

G52CPP C++ Programming Lecture 17

Transcription:

Programming in C/C++ 2006 http://few.vu.nl/~nsilvis/c++/2006 Natalia Silvis-Cividjian e-mail: nsilvis@few.vu.nl vrije Universiteit amsterdam Topics about C++ (10 min) about this course (5 min) C++ basics:data types (30 min) Functions and I/O (40 min) self test exercises (5 min) 2 History The legacy problem: Any C program is a legal C++ program. 3 1

C/C++ vs. Java C Java Designed in For Advantage Disadvantage 1970 system programming economy of expression, compact code Example: This sequence copies one string in another while (*p++ = *q++) ; too concise for human understanding, lack of runtime checks 1995 embedded consumer electronic devices strong type checking slow Conclusion FAST, FLEXIBLE, BUT DANGEROUS SAFE, RELIABLE, BUT (relatively) SLOW 4 C++ programming methodologies procedural programming (input => processing =>output) object oriented programming (encapsulate data and actions in one object. objects are bundles of data who know how to do things to themselves) Cat is a class. Tom, Felix are objects of type Cat Tom.Age = 4 ; Tom.walk() ; generic programming (make functions and classes for any type of the arguments) Example. T max (T left, T right) where T can be any type. 5 About this course The place of this course in the curriculum : Why C++? It is fast and widely used in companies What can we learn during this course? read and process data files create and manipulate dynamic data structures (lists and queues) learn to work with objects learn and experiment with C++ modern features, like template libraries 6 2

About this course How much time should we spend on this course? (2 ECTS = 2 x 28 = 56 hours) Lecture 1. Procedural programming 1 (C/C++ basics) (2 hours) Lecture 2 Procedural programming 2 (pointers and linked lists) (2 hours) Lecture 3 Object oriented programming (2 hours) Lecture 4 Generic programming (2 hours) Total : 8 hours lectures Assignment 1. Bank (8 hours) Assignment 2 AEX (16 hours) Assignment 3 Company (16 hours) Assignment 4 Templates (8 hours) Total : 48 hours practicals How do we get our 2 ECTS? It is of course useful to attend the lectures. But really important to get your credit points is to deliver in time the 4 assignments. Where can we find the lectures slides and the assignments? on the course website www.few.vu.nl/~nsilvis/c++/2006. 7 About this course BOOKS: ** Leen Ammeraal, Basiscursus C++, Academic service, 1999 * W. Savitch, Problem solving with C++, Addison Wesley, 2005 T. Budd, C++ for Java Programmers, Addison Wesley, 1999 S. Lipmann, J. Lajoie, C++ Primer, ATE&T, 1998 Liberty Jones, Teach yourself C++ in 21 days, SAMS, 2005 Other resources: practical guide on the website useful links to on-line tutorials, also on the website 8 Procedural programming in C++ a simple C++ program C++ basics: data types flow of control functions input and output 9 3

A simple C++ program //example1.cpp comments Explanation /*Reads 3 numbers from the keyboard, sums the numbers and writes the sum on the screen*/ also comments #include <iostream> using namespace std; int main() int a,b,c ; cout << "Give 3 integer numbers: "; cin >> a >> b >> c; int sum = a + b + c; cout << " The sum is : " << sum << endl; return 0; include directive standard namespace; always present main() function; always present declaration of integer variables a,b,c write message to the screen (cout) read a, b, c from the keyboard (cin) declare and assign variable sum write the sum and insert a blank line end program here 10 How to test a simple C++ program? Under Unix: use g++, the GNU C/C++ compiler under Unix. Compile : g++ example1.cpp Run: a.out (The executable is named by default a.out) Compile again and specify another name for the executable : g++ example1.cpp -o example.exe Run again: example.exe Under Windows: use Microsoft Visual C++ steps Compile - Build - Execute Details can be found in the practical guide on the course website. 11 What happens to a C++ program? 12 4

FF C++ basics: data types! " #! $% & %" ' % ( ) % * +,+ # -. "/ 01010 %"** " * 2 3333 4576 4 5 6 % (!8 9 : ; < =>? : ;<=< @ "?8 A" = BB :B@ CDDE CD D E F ( F % 6/ A G % 6 H 2 I+4J KL6 I+4 JK * % 6 0G %"* % M *N O 6 %" "6 P Q5 RRRR J S JS 5L9 % # 555 % % % %?/ (?TGTU76 " # % % G0G % % 2 struct Date int month; int day int year ; struct PersonInfo double height ; int age ; Date birthday ; 13 C++ basics: data types Pointer - the memory address of a variable. (Typical C, C++ data type) C++ accepts also this notation: int* p ; Arithmetics with pointers is possible, like p++ (in Java not) 14 C++ basics: data types Arrays: How to declare? int scores [5]; (no need to allocate with new like in Java) How to initialize? int scores [5] = 2, 5, 10, 5, 7 ; How to access elements? scores [0], scores [1]... scores [4]. Warning! C++ gives no error if index is out of range (Java does!) How to assign an indexed variable? score [3] = score [3] + 3 ; 15 5

B C++ basics: data types C-string: is an array of characters terminated in '\0 Examples: #include <cstring> char name [10] = "abcd" ; char name[] = "abcd" ; 16 C++ basics: data types C++ string:!#" $ $ $ $ %%%% &('*) +,.-0//21(3,+#+54 3 ) 6 72) 89#,:(,; < =,>.?3 7 @ #include <string> string name ; string name ("abc"); string name = "abc"; \\ C++ string = C-string A B B 7.1(3,(+#++#C D ) 8(E,++(F >72G#+(7H G3(>57>.I(7DH G81 C ) F8(+@ +#C D J ) K*L D 7,M+(N OD ) C 7+737 >78#C ) P = +#C D P,C 4 ) ;L*+(,>723 ) 6 7+#C D J ) K Q(IGC1 71(6 +H FD ) 3 3 7E,3#) 8M7 +#C D R /+#C D S.T1#F81#,(C 78(,(C 7(+S.+#C D ) 8(E(+ +#C D RU+#C D S5T1#F>5?,D 7(+C OVF5+#C D ) 8(E+ +#C D P H ) 8M4 +#C D R#;TH ) 8M(+,5+GI(+#C D ) 8E.) 85,+#C D ) 8E 17 C++ basics: flow of control if - else switch break while loop do-while loop for loop goto for examples see book Ammeraal 18 6

C++ basics: program style Indenting Comments Naming constants The C++ compiler does not care, but the program readers do! 19 Functions The top down approach splits the initial problem into several sub-problems and the process continues. Once a problem is simple enough to solve, then it can be implemented as a function. A function has : a declaration = name + formal parameters (only header+comments about what is does) a definition = name + formal parameters+body (how it does) one of many calls = name + actual parameters (function at work) When called, the actual parameters of a function are plugged in its formal parameters. C++ requires that either the complete definition or at least the function declaration appears in the code before the function is called (see the following 2 examples). 20 Functions: example 1 21 7

Functions: example2 22 Functions:plugging in parameters C++ has 2 mechanisms for plugging in arguments: Call by value : int do_stuff (int a) ; the value of a is plugged in Call by reference : void do_stuff (int& a) ; the address of a is plugged in 23 Functions: by-value vs. by-reference 24 8

Functions: by-value vs by- reference example 3 #include <iostream> using namespace std; void do_stuff(int par_value, int& par_ref) // par_value is called by value, par_ref by reference int main() int a,b ; a=1; b=2; do_stuff (a,b); cout << "a after call"<< a << endl ; cout << "b after call" << b << endl ; return 0 ; void do_stuff (int par_value, int&par_ref) Par_value = 111; Cout << "par_value in function call is"<< par_value << endl ; Par_ref = 222; Cout << "par_ref in function call is"<< par_ref << endl ; Par_value in function call is 111 Par_ref in function call is 222 a after function call is 1 b after function call is 222 25 Functions: by-value vs by- reference example 4.1 #include <iostream> // for cout #include <cmath> // for sqrt using namespace std ; // solves the quadratic equation ax^2+bx+c = 0 // if roots are real the function returns the roots in root1 and // root2 and if they are complex function returns false bool quadsolve (float a, float b, float c, float& root1, float& root2) float disc ; disc = b*b - 4*a*c ; if (disc < 0.0) return false; else root1 = (-b + sqrt (disc)) / (2 * a) ; root2 = (-b - sqrt (disc)) / (2 * a) ; return true ; //in by value //out by reference 26 Functions: by-value vs by- reference example 4.2 int main() float c1 = 1.0,c2 = 1.0, c3 = -6.0; float r1, r2 ; if (quadsolve (c1,c2,c3,r1,r2)) // here is the call cout << "Roots are " << r1 << "and " << r2 << endl ; else cout << "Complex roots" << endl ; return 1 ; 27 9

When to use call-by-reference? If you want the arguments to remain changed also after the function call If you want your function to return more than one value (see example 4) If the argument you want to pass to the function is a large structure (like an array) 28 Passing arrays as parameters An index variable can be formal parameter for a function: add (score[3]); Arrays can be formal parameters for functions = array parameters array parameters are not quite a call by reference During the call the function gets the address of the first element but not the array length. Another parameter to tell the length is always required. void fill_array (int a[], int size) cout << "Enter " << size << "numbers":\n"); for (int i = 0 ; i < size ; i++) cin >> a[i]; function call: fill_array (score,5) ; 29 Input and output (I/O) The C standard I/O library: printf, scanf, The C++ stream I/O library Standard I/O : cin, cout File I/O 30 10

C standard I/O library <stdio.h> Standard I/O library inherited from original C. Requires #include <stdio.h> Due to legacy, it is good to know that this library exists. But it is not recommended to use this library in C++ programs. At this point it is declared obsolete. How to read/write a character? c = getchar(); putchar ('x') ; How to read/write a C-string? gets(name) and puts ( Hello ) How to format input/output? scanf and printf using the conversion characters: scanf ( %d, &a) ; // reads an integer from keyboard int i = 5 ; // writes on the screen int j = 7 ; double d = i / (double) j ; printf ("the value of %d over %d is %f", i,j,d); 31 C++ streams A stream is a flow of characters or other kind of data (~river). Each program has an input stream and an output stream. A C++ stream is an object with member functions: open(), close(), fail(), get(), put(), setf(), eof() Streams can be arguments for functions, but must be called by reference 32 standard I/O: #include < iostream> cin is an input stream standard connected to the keyboard. No need to declare. Example : cin >> number ; cout is an output stream standard connected to the screen. No need to declare. Example : cout << the number is << number ; 33 11

standard I/O: useful functions How to read characters from the keyboard? cin >> ch. OK, but does not read spaces. cin.get (ch) or ch = cin.get(). Reads any next character (also space and \n). How to read C++ strings? string line ; cin >> line ; // reads a string until a whitespace, ignores leading spaces getline (cin, line) //reads a string until \n UNRELIABLE!! getline (cin, line, ch) // reads a string line until ch. How to read C-strings? char name[25] ; cin >> name; 34 standard I/O: useful functions How to read integers from the keyboard? Use a sentinel-controlled while loop. A sentinel (or trailer) is a special predetermined value to mark the end of input. const SENTINEL = -999; int data ; cout << Enter an integer (-999 to end input): ; cin >> data ; while (data!= SENTINEL) do_stuff (data) ; cin >> data ; How to check your input? cin stream returns FALSE if the input operation fails (e.g. char instead of integer) if (! (cin >> data)) cout << please enter only numeric characters ; cin.clear() ; cin.ignore (1000) ; 35 standard I/O:useful functions How to write characters to the screen? cout << ch ; or cout.put (ch) // sends one character to the screen. How to format output? Include this sequence and use #include <iomanip> cout.setf (ios::fixed) ; cout.setf (ios::showpoint) ; cout.precision (2) ; cout.width (7) or cout << setw (7) << number ; 36 12

Files I/O #include <fstream> Files are also streams. <fstream> library contains a few classes: ifstream for input file stream; Example : ifstream in_stream ; ofstream for output file stream; Example: ofstream out_stream ; 37 File I/O A file has 2 names: an external name (SYSTEM name) = infile.dat the stream name (PROGRAM VARIABLE) = in_stream. 38 File I/O Steps to read from a file infile.dat and write to a file outfile.dat: -Place the #include <fstream> directive -Declare input and output streams -Connect each stream to a file = open files in_stream >> some_variable; -Get input from the file -Send output to the output file -Disconnect the streams = close files #include <fstream> using namespace std; ifstream in_stream ; ofstream out_stream ; in_stream.open( infile.dat ); out_stream.open( outfile.dat ); out_stream << somevariable <<endl; in_stream.close() ; out_stream.close(); 39 13

File I/O. Example #include <fstream> //reads 3 numbers from the file infile.dat and sends the sum to the output file outfile.dat using namespace std; int main() int first, second, third; ifstream in_stream ; ofstream out_stream ; in_stream.open ("infile.dat"); out_stream.open ("outfile.dat"); in_stream >> first >> second >> third ; out_stream << "The sum of the first 3 \n" << "numbers in the infile.dat file\n" << "is " << (first + second + third) << endl ; in_stream.close(); out_stream.close(); return 0 ; 40 File I/O:useful functions All techniques with cin and cout are valid for file streams. How to put back a character in the input buffer? in_stream.putback (ch) How to read the next character but not consume it? in_stream.peek(ch) How to read integers from a file? in_stream >> number ;// jumps over blank characters in the file. How to read the file name form keyboard? string filename ; ifstream instream ; cout << Enter file name: \n ; cin >> filename ; instream.open (filename.c_str()) ; // converts C++ string to C- string 41 File I/O: useful functions How to check for file opening success? Use fail() member function and exit (1) from <cstdlib> library. #include <cstdlib> #include <fstream> #include <iostream> using namespace std; int main() ifstream ins ; // file to be opened for input ins.open ( data.dat ) ; if (ins.fail()) // if opening fails end program cout << input file opening failed. \n ; exit (1) ; // exit function from cstdlib library 42 14

File I/O : useful functions How to test the end of the file? Each stream has a member function eof() which becomes true when the program tries to read a character beyond the end of the file. in_stream.get (next) ; while (! in_stream.eof()) do_stuff (next) ; in_stream.get(next) ; Example: ab c program reads: a b eof() false false \n false c false End of file marker true => stop 43 File I/O: eof () and fail () example #include <iostream> #include <fstream> #include <cstdlib> using namespace std ; int main() float x,sum; ifstream ins ; //input stream ofstream outs ; //output stream ins.open ("indata.dat") ; //opens files, exit if fail if (ins.fail()) cout << "Can't open indata.dat" << endl ; exit(1) ; outs.open ("results.dat") ; if (outs.fail()) cout << "Can't open results.dat" << endl ; exit(1) ; 44 File I/O: eof () and fail () example sum = 0.0 ; ins >> x ; while (!ins.eof()) sum+=x ; ins >> x ; outs << "The sum is " << sum << endl ; cout << "The sum is " << sum << endl ; ins.close() ; outs.close() ; return 0 ; 45 15

Self test exercises 1. What is the output of the following program lines, when embedded in a correct program that declares all variables to be of type char? a = b ; b = c ; c = a ; cout << a << b << c << c ; 2. What is the output of the following program lines, when embedded in a correct program that declares x to be of type int? x = 10 ; while (x >0) cout << x << endl ; x = x - 3; 46 Self test exercises 3. What is the output of the following program lines, when embedded in a correct program that declares x to be of type int? x = - 42 ; do cout << x << endl ; x = x 3 ; while (x>0) ; 4. Write a complete C++ program to output the even numbers from 0 to 20 one per line. The program does nothing else. 5. Write a function to swap two doubles. Use this function in a program to determine and print the maximum element of an array. 47 Self test exercises 6. What output will be produced when the folowing lines are executed, assuming the file list.dat contains the data shown? ifstream ins ; ins.open ( list,dat ) ; int count = 0, next ; while (ins >> next) count ++ ; cout << next << endl ; ins.close() ; cout >> count ; The file list.dat contains the following three numbers: 1 2 3 48 16