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

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

Simple File I/O.

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

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

Scientific Computing

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

C++ Input/Output: Streams

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

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

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.)

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

WARM UP LESSONS BARE BASICS

Summary of basic C++-commands

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

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

A SHORT COURSE ON C++

CS3157: Advanced Programming. Outline

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

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.

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

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

Introduction to C++ Introduction to C++ 1

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

Introduction to C ++

Introduction to C++ Systems Programming

Software Design & Programming I

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

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

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

Programming. C++ Basics

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

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

UEE1303(1070) S 12 Object-Oriented Programming in 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).

OBJECT ORIENTED PROGRAMMING

Introduction to C++ (Extensions to C)

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

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

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

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

Computing and Statistical Data Analysis Lecture 3

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

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

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

Chapter 2 Basic Elements of C++

Engineering Problem Solving with C++, Etter/Ingber

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

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

Getting started with C++ (Part 2)

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

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

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

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

C++ Input/Output Chapter 4 Topics

CSCE 110 PROGRAMMING FUNDAMENTALS

COMP322 - Introduction to C++

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

The C++ Language. Arizona State University 1

Lab Instructor : Jean Lai

Chapter 2. Outline. Simple C++ Programs

CS103L SPRING 2018 UNIT 7: FILE I/O

CSCE 206: Structured Programming in C++

Streams. Rupesh Nasre.

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

C++ For Science and Engineering Lecture 12

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

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

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

G52CPP C++ Programming Lecture 17

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

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

Transcription:

Programming in C/C++ 2006 C/C++ vs. Java C Designed in 1970 Java 1995 http://few.vu.nl/~nsilvis/c++/2006 For Advantage system programming economy of expression, compact code Example: This sequence copies one string in another embedded consumer electronic devices strong type checking Natalia Silvis-Cividjian e-mail: nsilvis@few.vu.nl Disadvantage while (*p++ = *q++) ; too concise for human understanding, lack of runtime checks slow vrije Universiteit amsterdam Conclusion FAST, FLEXIBLE, BUT DANGEROUS SAFE, RELIABLE, BUT (relatively) SLOW 4 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) 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. 2 5 History 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 The legacy problem: Any C program is a legal C++ program. 3 6 1

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 A simple C++ program //example1.cpp /*Reads 3 numbers from the keyboard, sums the numbers and writes the sum on the screen*/ #include <iostream> 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; comments also comments Explanation 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 About this course How to test a simple C++ program? BOOKS: ** Leen Ammeraal, Basiscursus C++, Academic service, 1999 Under Unix: use g++, the GNU C/C++ compiler under Unix. * W. Savitch, Problem solving with C++, Addison Wesley, 2005 Compile : g++ example1.cpp T. Budd, C++ for Java Programmers, Addison Wesley, 1999 S. Lipmann, J. Lajoie, C++ Primer, ATE&T, 1998 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 Liberty Jones, Teach yourself C++ in 21 days, SAMS, 2005 Run again: example.exe Other resources: practical guide on the website useful links to on-line tutorials, also on the website 8 Under Windows: use Microsoft Visual C++ steps Compile - Build - Execute Details can be found in the practical guide on the course website. 11 Procedural programming in C++ What happens to a C++ program? a simple C++ program C++ basics: data types flow of control functions input and output 9 12 2

FF ii! " #! $% & %" ' % ( ) % * +,+ # -. "/ 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 ; C-string: is an array of characters terminated in '\0 Examples: #include <cstring> char name [10] = "abcd" ; char name[] = "abcd" ; VXW+Y Z[ Z"\ ]_`a`+yhb`"cd Z"\^]_G`a"`+Y+b`"c d YYYY eflg ii j"g k kkkk 13 16 Pointer - the memory address of a variable. (Typical C, C++ data type) C++ string: lm nnnn oooo p q?rst!u7vv!w xt ssy pq x rz!r t~ t t ƒx " #include <string> string name ; string name ("abc"); string name = "abc"; \\ C++ string = C-string w xt sss ˆ r t sgs Š"! s Œ x ˆŒ w r Š s C++ accepts also this notation: int* p ; Arithmetics with pointers is possible, like p++ (in Java not) 14 s ˆŽ r? ˆ t s Gˆ r sx " "r s ˆ t y r Ls t x r z s ˆ Ž r w w z sgœ Š ˆr x x txr s ˆ vs ˆ wš wt t s s ˆ r s s ˆ s ˆ wš ƒtˆ s Šs ˆ r s s ˆ Œ r y s ˆ Œ r sts s ˆ r!r ts ˆ r 17 C++ basics: flow of control 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 ; if - else switch break while loop do-while loop for loop goto for examples see book Ammeraal 15 18 3

C++ basics: program style Functions: example2 Indenting Comments Naming constants The C++ compiler does not care, but the program readers do! 19 22 Functions Functions:plugging in parameters 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) C++ has 2 mechanisms for plugging in arguments: When called, the actual parameters of a function are plugged in its formal parameters. 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 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 23 Functions: example 1 Functions: by-value vs. by-reference 21 24 4

Functions: by-value vs by- reference example 3 #include <iostream> 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 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 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 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 Functions: by-value vs by- reference example 4.2 Input and output (I/O) 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 ; The C standard I/O library: printf, scanf, The C++ stream I/O library Standard I/O : cin, cout File I/O 27 30 5

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 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 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: 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: #include < iostream> standard I/O:useful functions 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 ; 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 ; 33 36 6

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. Example #include <fstream> //reads 3 numbers from the file infile.dat and sends the sum to the output file outfile.dat 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 A file has 2 names: an external name (SYSTEM name) = infile.dat the stream name (PROGRAM VARIABLE) = in_stream. 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) 38 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 Steps to read from a file infile.dat and write to a file outfile.dat: #include <fstream> ifstream in_stream ; ofstream out_stream ; 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> -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 in_stream.open( infile.dat ); out_stream.open( outfile.dat ); out_stream << somevariable <<endl; in_stream.close() ; out_stream.close(); 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 39 42 7

File I/O : useful functions Self test exercises 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 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 File I/O: eof () and fail () example Self test exercises #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 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 File I/O: eof () and fail () example Self test exercises 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 ; 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 ++ ; ins.close() ; cout << next << endl ; cout >> count ; The file list.dat contains the following three numbers: 1 2 3 45 48 8