Basics of C++ C++ Overview Elements I / O Assignment and Comments Formatted Output. Dr.Hamed Bdour

Similar documents
Chapter 1 Introduction to Computers and C++ Programming

Introduction to Programming

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

BITG 1233: Introduction to C++

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Engineering Problem Solving with C++, Etter/Ingber

Objectives. In this chapter, you will:

Chapter 3 - Notes Input/Output

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2. Outline. Simple C++ Programs

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

C: How to Program. Week /Mar/05

Chapter 2: Basic Elements of C++

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

UNIT- 3 Introduction to C++

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

Chapter 2 - Introduction to C Programming

Chapter 1 & 2 Introduction to C Language

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

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

6.096 Introduction to C++ January (IAP) 2009

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

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

CSCE 110 PROGRAMMING FUNDAMENTALS

The C++ Language. Arizona State University 1

LECTURE 02 INTRODUCTION TO C++

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Creating a C++ Program

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Programming. C++ Basics

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

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

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSI33 Data Structures

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

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

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

A First Program - Greeting.cpp

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Software Design & Programming I

CS242 COMPUTER PROGRAMMING

CHAPTER 3 BASIC INSTRUCTION OF C++

C++ Input/Output: Streams

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

Chapter 3 - Functions

Introduction to C# Applications

Intro to Computer Programming (ICP) Rab Nawaz Jadoon

Data types, variables, constants

C++ Programming: From Problem Analysis to Program. Design, Fifth Edition. Chapter 1: An Overview of Computers and Programming Languages

CSc Introduction to Computing

Understanding main() function Input/Output Streams

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

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

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Chapter 1 INTRODUCTION

Computer Programming : C++

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

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

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

IS 0020 Program Design and Software Tools

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

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

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

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Chapter 2: Overview of C++

Lecture 3 The character, string data Types Files

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

Getting started with C++ (Part 2)

Definition Matching (10 Points)

Chapter 2, Part I Introduction to C Programming

Lecture 2 Tao Wang 1

2 nd Week Lecture Notes

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

CS 241 Computer Programming. Introduction. Teacher Assistant. Hadeel Al-Ateeq

Introduction to C Language

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

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

Fundamentals of Programming CS-110. Lecture 2

Chapter 4 - Notes Control Structures I (Selection)

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

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

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

CSCI 1061U Programming Workshop 2. C++ Basics

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

Programming for Engineers Introduction to C

Full file at C How to Program, 6/e Multiple Choice Test Bank

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

Transcription:

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