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