Basics of C++ C++ Overview Elements I / O Assignment and Comments Formatted Output 1
History of C and C++ BCPL 1967 By Martin Richards Lang. to write OS NO Data Type + B :By Ken Thompson Used to create early UNIX @ Bell lab's 1970 NO Data Type C :By Dennis Ritchie @ Bell lab s -UNIX written in C -HW Independent -many versions in late 1970 s OO Features + Standard ANSI C In 1980 was approved OO Features + + C++: By Bjarne Stroustrap Early 1980s @ Bell lab s Provides OO programming 2 Java: In 1995 by Sun Microsystems
Structure of C++ program Every C++ program must have a function named main. The programmer can choose to decompose the program into several parts (user-defined functions). Think of main as the master and the other functions are the servants. The execution always starts with main. Preprocessor Directive Type of returned value Marks the start of the main function (program) #include <iostream.h> int main( ) { Declarations ; Executable Statement_1 ; Executable Statement_2 ; : Executable Statement_n ; Header file facilitate I/O } return 0; Marks the end of the main function (program) 3 Returning 0 means every things is OK else(1,2,..) something went wrong (Exit Status)
1 // Fig. 1.2: fig01_02.cpp 2 // A first program in C++ 3 #include <iostream.h> 4 5 int main() 6 { 7 cout << "Welcome to C++!\n"; 8 Comments Written between /* and */ or following a //. Improve program readability and do not cause the computer to perform any action. preprocessor directive Message to the C++ preprocessor. Lines beginning with # are preprocessor directives. #include <iostream.h> tells the preprocessor to include the contents of the file <iostream.h>, which includes input/output operations (such as printing to the screen). 9 } Welcome to C++! C++ programs contain one or more functions, one of which must be main Parenthesis are used to indicate a function int means that main "returns" an integer value. 1. Comments 2. Load <iostream.h> 3. main 3.1 Print "Welcome to C++\n" 4 3.2 exit (return 0) Prints the string of characters contained between the quotation marks. The entire line, including cout, the << operator, the string "Welcome to C++!\n" and the semicolon (;), is called a statement. All statements must end with a semicolon. A left brace { begins the body of every function and a right brace } ends it.
Naming Identifiers First character must be letter a-z, A-Z or _ Other characters letters (a-z, A-Z, _ ) or digits 0-9 Cannot use C++ keywords (reserved words) Cannot have blank within identifies Keep length to 31 characters Older compiler restriction Declaring Variables Variables MUST be declared List name and data type Variables of same type may be declared in same statement (separate by comma) Causes C++ compiler to know size of space to be reserved for storing variable s value 5
Variable Names (Identifiers) Letter + {Letters and/or Digits and/or ( _ ) _ +Letter+{Letters and/or Digits and/or ( _ ) Underscore character ( _ ) Naming Convention(Style) Variables LengthInYard, hours Functions CalcAverage, Cube(27) Constant MAX_HOUR, LIMIT Invalid Explanation? Correction 40Hours Get Date Box-22 cost_in_$ int Begin with a digit Blanks not allowed The hyphen(-) is minus Special symbols not allowed Reserved word in C++ forty_hours, hours40 get_date, getdate box_22, box22 costinusdollar int_1 6
Data Types short int :Range of values ( ±32,767 ). long int :Range of values ( ±2,147,483,647 ). int : Integer numbers float: floating point used for working with real numbers. double: is a floating point type much like float, but it can store a value of much greater magnitude with greater precision. Bool*: is a boolean data type can take two value TRUE or FALSE. *Note:- bool data type is provided by ANSI/ISO C++ standard. It is undefined in Borland Turbo C++. char: character data type (alpha,digit,special-symbol or space). A single character with its value quoted with single-quotation egs. A, a, $,, 8 string: for working with multiple characters including letters, numbers, special symbols and spaces its value quoted with double- quotation. egs. C++, Computer Science,. 7 Letter S.Symbol Space Digit
Numeric data types Decimal numbers float 4 bytes of memory, 6 digit precision double 8 bytes of memory, 15 digits precision long double 10 bytes of memory, 19 digits precision Whole numbers int, signed int, short int, signed short int 2 bytes, range: -32768 to 32767 unsigned int, unsigned short int 2 bytes, range: 0 to 65535 long int, signed long int 4 bytes, range: -2147483648 to 2147483645 unsigned long int 4 bytes, range: 0 to 4294967295 8
Declaration of Variables Constant Variables Data Type Identifier1, Identifier2, ; const Data Type Identifier=value; Examples and preference: char Letter, middleint, ch; char Letter; char middleint; char ch; Examples: const string STARS= ***** ; const char ch= $ ; const float MAX_Hour=40.0 Use const qualifier const double PI = 3.14159; Cannot modify later in program 9
Assignment Statement Variable = Expression ; Store the value of the Expression into the variable, any previous value of the variable is destroyed. Example:Giving the declarations string firstname; char letter; int num; firstname= Sara ; num = 5; num=5*5-3; Letter= S Valid Assignment firstname=sara; firstname=; Letter=S Invalid Assignment Remark :Double or more assignment allowed and precedence from Right-to-Left eg. N1=n2=n3=5; 10
Output statement cout << \nwe can jump\n\ntwo lines. ; cout << endl<< we can jump ; cout << endl<< endl << two lines. ; Example: Given ch= 2 and firstname= Ali and lastname= Ahmad cout<<ch; The 2 Output cout<< ch= <<2; ch=2 cout<<firstname+ +lastname; Ali Ahmad cout<< Erorr# <<ch; Error#2 cout<< \ Hello!\ ; Hello! To print 2 words on separate lines use <<endl Example: cout<< He ; cout<< There ; Hi There 11 cout<< Hi <<endl; cout<< There <<endl; Hi There
Comments /*..Text... Text */ For Multiple Lines // Text For Single Line The compiler ignores comments (Not executable) C++ Preprocessor #include<iostream> :- This line known as Preprocessor Directive its not handled by C++ compiler but by a program known as Preprocessor. iostream :- Header file contains declarations of I/O facilities. Preprocessor program acts as a filter before compilation. Source program Preprocessor Expanded Source program C++ Compiler 12
A Simple Program: Printing a Line of Text Escape Sequence Description \n Newline. Position the screen cursor to the beginning of the next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line. \a Alert. Sound the system bell. \\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double quote character. There are multiple ways to print text Following are more examples 13
1 // Fig. 1.4: fig01_04.cpp 2 // Printing a line with multiple statements 3 #include <iostream.h> 4 5 int main() 6 { 7 cout << "Welcome "; 8 cout << "to C++!\n"; 9 10 return 0; // indicate that program ended successfully 11 } 1. Load <iostream.h> 2. main 2.1 Print "Welcome" 2.2 Print "to C++!" 2.3 newline 2.4 exit (return 0) Welcome to C++! Program Output Unless new line '\n' is specified, the text continues on the same line. 14
1 // Fig. 1.5: fig01_05.cpp 2 // Printing multiple lines with a single statement 3 #include <iostream.h> 4 5 int main() 6 { 7 cout << "Welcome\nto\n\nC++!\n"; 8 9 return 0; // indicate that program ended successfully 10 } 1. Load <iostream.h> 2. main 2.1 Print "Welcome" 2.2 newline 2.3 Print "to" 2.4 newline Welcome to C++! Multiple lines can be printed with one statement. 2.5 newline 2.6 Print "C++!" 2.7 newline 15 2.8 exit (return 0) Program Output
1 // Fig. 1.6: fig01_06.cpp 2 // Addition program 3 #include <iostream.h> 4 Notice how cin is used to get user input. 1. Load <iostream> 2. main 5 int main() 6 { 7 int integer1, integer2, sum; // declaration 8 9 cout << "Enter first integer\n"; // prompt 10 cin >> integer1; // read an integer 11 cout << "Enter second integer\n"; // prompt 12 cin >> integer2; // read an integer 13 sum = integer1 + integer2; // assignment of sum 14 cout << "Sum is " << sum << endl; // print sum 15 16 return 0; // indicate that program ended successfully 17 } Enter first integer 45 Enter second integer 72 Sum is 117 Variables can be output using cout << variablename. endl flushes the buffer and prints a newline. 2.1 Initialize variables integer1, integer2, and sum 2.2 Print "Enter first integer" 2.2.1 Get input 2.3 Print "Enter second integer" 2.3.1 Get input 2.4 Add variables and put result into sum 2.5 Print "Sum is" 2.5.1 Output sum 2.6 exit (return 0) Program Output 16
Formatted Output setw :can be used to specify the width of the field that the next value of output will be printed in. To use it, you must include <iomanip.h> header file. eg1:- int num=12; cout<< setw(4) << num; //num will be printed in a field width of 4 character. 1 2 eg2:- int n1=12; int n2=197; cout<<setw(5)<< n1 << setw(6) << n2; 1 2 1 9 7 eg3:- (if the value is more than the specified setw value the compiler ignores the setw effect and print it with the minimum number of positions required.) int num=1977; cout<<setw(3)<<num; 1 9 7 7 17
Formatted Output(cont 1) Setprecision(n) for printing formatted floating point values will output decimal numbers with up to n decimal places it can be done by either setprecision stream manipulator, or precision member function. eg. num = 5.3415; cout<< num = <<setprecision(3)<<num; num = 5.34 setfill( ) Specifies character for blank space in field Single quotes required around character enclosed in parentheses num = 5.34; cout<<setw(10)<<setfill( * )<<num; //******5.34 cout<<setw(10)<<setfill('*')<<left<<num; //5.34****** setiosflags(ios:: ) Perform number of different actions based on flag that is set Example: num = 5.34; cout<<setiosflags(ios::left) << setfill( * )<<setw(10)<<num; 5.34****** // right 18
Formatted Output (cont 2) cout<<setfill('@'); cout<<setw(5)<<left<<85<<"\n"; cout<<setw(5)<<right<<99<<"\n"; double a,b,c,pi; a=30.0; b=10000.4; pi=3.1416; cout.precision (7); cout <<showpoint << a << '\t' << b << '\t' << pi << endl; cout <<noshowpoint << a << '\t' << b << '\t' << pi << endl; */ 3.141600 10000.40 30.00000 3.1416 10000.4 30 /* x=8.123456789; y=99.987654321; z=444.555555555; cout << fixed; cout << x <<"\t"<< y <<"\t"<< z << endl; 8.123457 99.987654 444.555556 19
Input statement cin >> variable1 >> variable2 ; It needs #include<iostream> preprocessor directive that contain istream cin ostream cout. The Same Statement Data Contents after input cin>>i>>ch>>x; 25 A 16.9 i=25 ch= A x=16.9 3:- cin>>i>>j>>x; 12 8 i=12 j=8 (waits for the third number) Example:- 1:- cin>>length>>width; cin>>length; cin>>width; 2:- 4:- cin>>i>>x; 46 32.4 15 i=46 j=32.4 (15 is held for later input) 20 New line character \n is considered one character eg. cout<< Hello!\n ; cout<< Hello! <<endl; The Same
Input statement (cont.) char c1,c2,c3,c4,c5,c6,c7,c8; cin >> c1 >> c2 >> c3; cin >> c4 >> c5; cin >> c6; cin >> c7 >> c8; c1 c2 c3 c4 a f d 3 c5 c6 c7 c8 2 h j w Keyboard Input af d32(enter) hj(tab)w (enter) k Note: All whitespace characters are ignored! 21
Input statement(cont.) Note :- can t input SPACE character, the >> skips white space (blank) character. Get Function(Does not skips space characters) eg. cin.get(ch1) R cin>>ch1 cin.get(ch2) cin.get(ch2) cin.get(ch3) 1 cin>>ch3 Given input: R 1 22
Reading, Writing using files #include <iostream> #include <fstream> #include <string> using namespace std; main() { ifstream infile; ofstream outfile; double t1,t2,t3,av; string fname,lname; infile.open("f:\\test.txt"); outfile.open("f:\\testr.txt"); infile>>fname>>lname; outfile<<"std.name: "<<fname<<" "<<lname<<endl; infile>>t1>>t2>>t3; outfile<<"test SCORES: "<<t1<<" "<<t2<<" "<<t3<<endl; av=(t1+t2+t3)/3.0; outfile<<"average TEST SCORE: "<<av<<endl; infile.close(); outfile.close(); return 0;} 23
Built-in (Library) Function Function Exponentiation pow (x, y) x is raised to power y; (x y ) sqrt (x) Square-root of x sin (x) جا Sine of x cos (x) جتا Cosine of x tan (x) ظا Tangent of x exp (x) Exponentiation of x, ( e x ) fabs (x) Absolute Value of x, x log (x) Logarithm of x (base e) log10 (x) Logarithm of x (base 10) floor (x) Rounding-down x, Returns the largest integral value that is not greater than x. ceil (x) Rounding-up x, Returns the smallest integral value that is not less than x. etc. {there are more} Eg.1. floor (9.2) = 9.0 Eg.2. floor (-9.8) = -10.0 Remark:you need to include <math.h> to be able to use these functions. In newer versions it is #include<cmath> 24
Pre- and Post- Operators ++ or -- Place in front, incrementing or decrementing occurs BEFORE value assigned i = 2 and k = 1 k = ++i; i = i + 1; k = i; 3 3 k =--i; i = i - 1; k = i; 1 1 Place in back, occurs AFTER value assigned i = 2 and k = 1 k = i++; k = i; i = i + 1; 1 3 k = i--; k = i; i = i - 1; 2 1 25
Increment Decrement int k = 4; ++k; // k is 5 k++; // k is 6 cout << k << endl; int i = k++; // i is 6, k is 7 cout << i << " " << k << endl; int j = ++k; // j is 8, k is 8 cout << j << " " << k << endl; int d, t=10; d= -- t + --t; cout<<"d="<<d; ((((5 *15) + 4) == 13) && (12 < 19)) ((!false) == (5 < 24)) 26
Assignment Operators Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator Statements of the form variable = variable operator expression; can be rewritten as variable operator= expression; Examples of other assignment operators include: d -= 4 (d = d - 4) e *= 5 (e = e * 5) f /= 3 (f = f / 3) g %= 9 (g = g % 9) 27
Increment and Decrement Operators Increment operator (++) - can be used instead of c += 1 Decrement operator (--) - can be used instead of c -= 1 Preincrement When the operator is used before the variable (++c or --c) Variable is changed, then the expression it is in is evaluated. Postincrement When the operator is used after the variable (c++ or c--) Expression the variable is in executes, then the variable is changed. If c = 5, then cout << ++c; prints out 6 (c is changed before cout is executed) cout << c++; prints out 5 (cout is executed before the increment. c now has the value of 6) 28
Increment & Decrement Operators Examples int c; c=5; cout<<c<<endl; 5 cout<<c- -<<endl; 5 cout<<c<<endl; 4 cout<< ===\n ; === c=5; cout<<c<<endl; 5 cout<<- -c<<endl; 4 cout<<c<<endl; 4 29
Operators Precedence 3x+5y+2x 2 (3*x)+(5*y)+(2*pow(x,2)) y = 2 * 5 5 + 3 * 5 + 7 Total = 10 + 15 * 2 / 4 2 30
Operators Precedence update Operator(s) Operation(s) Order of evaluation (precedence) () Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), they are evaluated left to right.!, +, - Logical NOT, signs Evaluated second. If there are several, they are evaluated right to left. *, /, or % Multiplication Division Modulus + or - Addition Subtraction >>, << Input steam extraction and output stream insertion Evaluated third. If there are several, they are evaluated left to right. Evaluated fourth. If there are several, they are evaluated left to right. Evaluated fifth. If there are several, they are evaluated left to right. >, <, >=, <= Relational Operators Evaluated sixth. If there are several, they are evaluated left to right. ==,!= Equality Operators Evaluated seventh. If there are several, they are evaluated left to right. && Logical AND Evaluated eighth. If there are several, they are evaluated left to right. Logical OR Evaluated nineth. If there are several, they are evaluated left to right. = Assignment Evaluated tenth. If there are several, they are evaluated right to left. 31
getline function The extraction operator(>>) skips any leading whitespace characters and reading stops at a whitespace character It should not be used to read strings that contain blanks The function getline reads until it reaches the end of the current line It should be used to read strings that contain blanks #include <string> //Header string str; getline (cin,str); //Badee3 Maola azzaman cout << str ; //Badee3 Maola azzaman 32
String Functions #include <iostream> #include <string> using namespace std; int main () { string name = "HALA SAQER BESHIR"; cout<<name<<endl; string str2 = name + " BDOUR"; cout<<str2<<endl; cout<<name.length()<<endl; cout<<name.size()<<endl; cout<<name.find("q")<<endl; cout<<name.substr(5)<<endl; string st1 = "FIRST"; string st2 = "SECOND"; st1.swap(st2); cout<<st1<<" "<<st2<<endl; } 33