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

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

Chapter 12. Streams and File I/O

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

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

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

Simple File I/O.

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

Programming in C/C Lecture 2

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

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

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

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

Scientific Computing

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

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.

C++ for Python Programmers

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

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

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

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

WARM UP LESSONS BARE BASICS

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

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

CS3157: Advanced Programming. Outline

C++ Input/Output: Streams

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

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

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

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

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

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

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

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

Writing a Good Program. 7. Stream I/O

A SHORT COURSE ON C++

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

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

CMPS 221 Sample Final

Software Design & Programming I

Programming in C/C++ Lecture 1

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

Partha Sarathi Mandal

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

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

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

Objects and streams and files CS427: Elements of Software Engineering

C++ For Science and Engineering Lecture 12

COMP322 - Introduction to C++ Lecture 01 - Introduction

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

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

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

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

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.

6.096 Introduction to C++ January (IAP) 2009

Topics. bool and string types input/output library functions comments memory allocation templates classes

C++ Input/Output Chapter 4 Topics

CSCE 206: Structured Programming in C++

Chapter 3 - Notes Input/Output

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

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

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

Introduction to C++ Systems Programming

Programming. C++ Basics

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

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

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

Preview 8/28/2018. Review for COSC 120 (File Processing: Reading Data From a File)

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

Ch 6-2. File Input / Output

CS201 - Introduction to Programming FAQs By

C++ Programming Fundamentals

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

COMP322 - Introduction to C++

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

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

Fast Introduction to Object Oriented Programming and C++

Outline. 1 About the course

C++ Programming for Non-C Programmers. Supplement

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

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

Lab # 02. Basic Elements of C++ _ Part1

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

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

Object Oriented Programming

Summary of basic C++-commands

C++ Quick Guide. Advertisements

Introduction to C ++

Introduction to C++ Introduction to C++ 1

Getting started with C++ (Part 2)

C++ Programming for Non-C Programmers. Supplement

C++ 프로그래밍실습. Visual Studio Smart Computing Laboratory

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

SU2017. LAB 1 (May 4/9) Introduction to C, Function Declaration vs. Definition, Basic I/O (scanf/printf, getchar/putchar)

Transcription:

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 min) (40 min) (30 min) vrije Universiteit amsterdam 2 About C/C++ language C/C++ vs. Java First there was B. C is developed together with Unix by Kernighan and Ritchie 1970 s First C reference book 1978 (K&R 78) Standard ANSI C (89) C++ is a C descendant, developed by Stroustrup (86) C++ standard by ANSI/ISO (1997 ) C vs. C++ : Any C program is a legal C++ program. C legacy C is a language designed 30 ago for systems programming Advantage: economy of expression, compact code => FAST while (*p++ = *q++) ; ; Disadvantage: too concise for human understanding, lack of runtime checks Java appeared later, in a time of increasing processor speeds and decreasing memory costs. Advantage: SAFE Conclusion: C++ = efficiency of execution vs. Java = safety 3 4 C++ programming methodologies About this course procedural programming (input => processing =>output) object oriented programming (encapsulate data and functions in one class) Cat is a class. Tom, Felix are objects of type Cat Tom.Age = 4 ; 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. 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 classes learn and experiment with C++ specific features like template libraries 5 6 1

About this course How much time we should 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 (8hours) Total : 48 hours practicals 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 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. The assignments are found on the course website. 7 8 Procedural programming 1 A simple C++ program //example1.cpp /*Reads 3 numbers from the keyboard, sums the numbers and writes the sum on the screen*/ Explanation comments also comments a simple C++ program C++ data types flow control functions arrays strings input and output #include <iostream> include directive using namespace std; standard namespace int main() main() function int a,b,c ; declaration of variables a,b,c cout << Give 3 integer numbers: "; write to the screen (cout) cin >> a >> b >> c; read from the keyboard (cin) int sum = a + b + c; declare and assign variable sum cout << The sum is : " << sum << endl; return 0; endl inserts a blank line end program here 9 10 How to test a C++ program? How to test a C++ program? Under Unix:g++ is the GNU C/C++ compiler under Unix. Compile : g++ example1.cpp Run: a.out The default executable is named a.out Compile and specify another name for the executable : g++ example1.cpp o example.exe Run: example.exe Under Windows: C++ Visual : Compile - Build - Execute Details in the practical guide on the course website. 11 12 2

I L L C++ Data types!" #"$ % "!& '"(! )*)+ +!,.- $/ 01010 + "$((! $ +(!2 - " & 34 5 678 9 :; 67$8 98<+= 3!4 >$ 9?? 6?< *+ + " 3 " " "( 3& + + / > " @ + A +! = 2 B) =(C5$ 0! "$( 3+ " D = (C+ +$E 3@ + " @ F G = 5" " "+ + +3 " "/ & + H @ " "+ 0 3 " "2 struct Date int month; int day; int year ; struct PersonInfo double height ; int age ; Date birthday ; Flow control If - else Switch - break While Do-while For loop goto see book Ammeraal 13 14 Arrays " " + D + 4?< J/ + 3 +!" + " 0! 0K " #"2 ( D + 4 >< @ + 4 M < +$ 4 N< - " A" + D $ 3 4 6< OE 7@?@ M6 FPJ QSRT UVW XX!YZ [U\]RU^ ^ R^Z _Z ]` U az \ RbTR_^ c] Y U)d - 3'3 #" "& $D +$ e4 6<)J - 3' #" "& " & + (" " "$( +"! = + $D"33/ + 4 6< 2 J " f" & + ( " " "( + = + O" " " "( Array parameters " " ( (" " 3" = + " array parameters are not quite a call by reference During call the function gets the address of the first element but not the array length. Another parameter to tell the length is always required. B'"(! $D #+ 3 g" " / "4 < @ A$2 E +=$hhi B) $i)hh A!h$hi =(& i D j i 2 J +$/ $O>;Jh! A;J $ 2!kk!"4 < J F = + " D g" " / + $@?2)J 15 16 C-Strings C++ strings #include <cstring> C- string is an array of characters terminated in \0 char name [10] = "abcd" ; char name[] = "abcd" ; z$ =3!h k " S $ " "( vj "( $/ i "&i 2 J "( Oi "& i J j j$ 1! O 15 = = ( (& = + D 4 <5) " 3 0 ( " / 2 5"$( 4 < @& = +$ " 3 ' l m$nm)osp$m$q r o stvuw xu y y M 7 M h 7 3/ M2 17 18 3

Functions Functions:pluging in arguments C++ has 2 mechanisms for pluging in arguments: Call by value : int max (int i, int j) ; only the value is passed Call by reference : void do_stuff (int& a, int& b) ; the address is also passed Call by ref: arguments are changed by the functions and remain changed also after the function call 19 20 Call-by-value vs call-by- reference When to use call by reference? #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 21 If you want the arguments to remain changed also after the function call If you want your function to return more than one value If the argument you want to pass to the function is a large structure 22 Input and output (I/O) The C standard I/O library C++ stream I/O library File streams C standard I/O library <stdio> #include <stdio> Standard I/O library inherited from original C Read/write a character: c = getchar(); putchar ( x ) ; Read/write a C-string: gets and puts Formatted output printf uses conversion characters: %d integer decimal %f floating point %s C-string : int i = 5 ; int j = 7 ; double d = i / (double) j ; printf ("the value of %d over %d is %f", i,j,d); 23 24 4

C++ stream I/O Cin, cout, #include <iostream> Stream = flow of characters (~river). Stream is a C++ object with member functions: open(), close(),fail(),get(),put() Libraries: #include <iostream> for cin, cout #include <fstream> for file I/O (types: ifstream = input file stream and ofstream =output file stream) cin is an input stream standard connected to the keyboard. No need to declare cin >> number ; // cin reads next non-white character cout is an output stream standard connected to the screen. No need to declare cout << the number is << number ; Formatted output: use setf member function to set flags cout.setf(ios::fixed) cout.setf(ios::showpoint) cout.precision(2) cout.width (7) or cout << setw(7) << number ; 25 26 File I/O #include <fstream> File I/O using streams. Example 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 -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 ); in_stream >> some_variable; out_stream << somevariable << endl; in_stream.close() ; out_stream.close(); 27 #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 ; 28 File I/O: useful functions How to read characters? cin.get (char_variable). Reads any next character. How to write characters? cout.put (char_expression) How to read C++ strings? getline (cin, line) reads a string until end of line \n or getline (cin, line, ch) reads a string until ch. How to read C-strings? cin.getline (name,20); Note: instead of cin can be any other input stream and instead of cout can be any other output stream. File I/O: useful functions How to check for file opening succes? Use fail(). #include <cstdlib>.. if (in_stream.fail()) cout << input file opening failed. \n ; exit (1) ; \\end program here 29 30 5

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 31 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; 32 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. 33 6