SlideShare a Scribd company logo
Chapter  2 Introduction to C++ Programming C++, How to Program Deitel  &  Deitel
Learn C++ by Examples Five examples demonstrate How to display messages How to obtain information from the user How to perform arithmetic calculations
Important Parts of a C++ program Comments:  //, /* …. */ Preprocessor directives  :  #include Function  main Body of the function Return statement Other statements
Comments Explain programs to other programmers Improve program readability Ignored by compiler Single-line comment Begin with  // Example // allows program to output data to the screen . Multi-line comment Start with   /* End with  */
Preprocessor Directives Preprocessor directives Processed by preprocessor before compiling Begin with  # Example #include <iostream> Tells preprocessor to include the input/output stream  header file  <iostream> White space s Blank lines, space characters and tabs Delimiter, used to make programs easier to read Extra spaces are ignored by the compiler
Function  main A part of every C++ program Exactly  one  function in a program must be  main main  is a  Keyword. Keyword : A word in code that is reserved by C++ for a specific use. Header of function main :  int main(   ) Body is delimited by braces ( {   } )
Statements Instruct the program to perform an action All statements end with a semicolon ( ; ) Examples :  return 0;   std::cout << “Welcome to C++!\n ”;
return  Statement One of several means to exit a function When used at the end of  main The value  0  indicates the program terminated successfully Example return 0;
Output Statement (1) std::cout << “Welcome to C++!\n”; std::cout   Standard output stream object . Defined in input/output stream  header file  <iostream> We are using a name ( cout ) that belongs to “namespace”  std . Norm ally outputs to computer screen . Stream insertion operator   <<  Value to right (right operand) inserted into left operand . The string of characters contained between  “ ”  after the operator  <<  shows on computer screen.
Output Statement (2) Escape character  :   backslash :  &quot; \ &quot; Escape sequence :  A character preceded by  backslash  ( \ ) Indicates “special” character output Example s : &quot;\n&quot; Newline.  Cursor moves to beginning of next line on the screen “ \t” Horizontal tab. Move the screen cursor to the next tab stop.
Good Programming Practices Add comments Every program should begin with a comment that describes the purpose of the program, author, date and time. Use good indentation Indent the entire body of each function one level within the braces that delimit the body of the function. This makes a program’s functional structure stand out and helps make the program easier to read.
Run C++ Program Save the program with the right extension programOne.cpp Send the program in the right directory Compiling the program: g++ programOne.cpp –o programOne.out Run the executable file ./programOne.out
Modifying Our First C++ Program Print text on one line using multiple statements  Each stream insertion resumes printing where the previous one stopped Statements: Std::cout << “Welcome ”; Std::cout << “to C++!\n”;
Modifying Our First C++ Program Print text on several lines using a single statement . Each newline escape sequence positions the cursor to the beginning of the next line Two newline characters back to back outputs a blank line Example statement : Std::cout << “Welcome \n to \n\n C++! \n ”;
Variable Location in memory where value can be stored Common data types (fundamental, primitive or built-in) int  – integer numbers : 1, 2, 4,…. char  – characters : ‘a’, ‘c’, … float,  double  – floating point numbers: 2.5, 4.96 The value of a variable could be changed while the program is running.
Declaration of Variables (1) Declare variables with name and data type  before  they are  use d. A variable name is any valid identifier that is not a keyword. Series of characters  -  letters, digits, underscores  ( _ ) Cannot begin with digit Case sensitive Choosing meaningful identifiers helps make a program self-documenting .
Declaration of Variables (2) Can Declare each variable on a separate line. int integer1; int integer2; int sum; Can declare several variables of same type in one declaration . Comma-separated list int integer1, integer2, sum;
Assign Value to Variables Assignment operator  = Assigns value on  right  to variable on  left Binary operator (two operands) Assign a value after declaration int integer1;  //declaration integer1  = 10;   //assignment Declare and assign a value at the same time.  int  integer2  =  20;
Input stream object std::cin  from  <iostream> Usually connected to keyboard Stream extraction operator  >> Waits for user to input value, press  Enter  (Return) key Stores value in variable to right of operator Converts value to variable data type Example int number1; std::cin >> number1; Reads an integer typed at the keyboard Stores the integer in variable  number1
Constant variables Declared using the  const  qualifier Also called named constants or read-only variables Must be initialized with a constant expression when they are declared and cannot be modified thereafter Example:  const int size = 5;
Arithmetic (1) Arithmetic operators + :  Addition -  :  Subtraction *   :  Multiplication  /   :  Division Integer division truncates remainder 7 / 5  evaluates to 1 %  :  Modulus operator returns remainder  7 % 5  evaluates to 2 Attempting to use the modulus operator ( % ) with  non - integer operands is a compilation error.
Arithmetic operators
Arithmetic (2) Straight-line form Required for arithmetic expressions in C++ All constants, variables and operators appear in a straight line Grouping sub - expressions Parentheses are used in C++ expressions to group sub - expressions Same manner as in algebraic expressions Example a * ( b + c ) Multiple  a  times the quantity  b + c
Rules of operator precedence Operators in parentheses evaluated first Nested/embedded parentheses Operators in innermost pair first Multiplication, division, modulus applied next Operators applied from left to right Addition, subtraction applied last Operators applied from left to right
Precedence of Arithmetic Operators
Performing Arithmetic Calculation in C++ Program Adding two integers int number1, number2, sum; std::cin >> number1; std::cin >> number2; sum =  number 1 +  number 2; Add the values of  variable1  and  variable2 Store result in  sum
Question Question : int integerOne = 1; double doubleOne = 2.5; int sumOne = integerOne + doubleOne; //A double sumTwo = integerOne + doubleOne; //B Which statement is correct , A or B ?
Output Statement With Expression Variables or expressions could be inserted into output statement, its value is printed out. Long output statement could be broken into multiple lines. Example: std::cout << “sum is ” << sum    << “. bye-bye! \n”; std::cout << “sum is ”    << number1 + number2 ;
End of Line Stream manipulator  std::endl Outputs a newline Flushes the output buffer
Memory Concepts Variable names Correspond to actual locations in computer's memory Every variable has name, type, size and value When new value placed into variable, overwrites old value Writing to memory is destructive Reading variables from memory nondestructive Example sum = number1 + number2; Value of  sum  is overwritten Values of  number1  and  number2  remain intact
Fig. 2.6   | Memory location showing the name and value of variable number1.
Fig. 2.7   | Memory locations after storing values for number1 and number2.
Fig. 2.8   | Memory locations after calculating and storing the sum of number1 and number2.
Type Sizes and Ranges The size and range of any data type is compiler and architecture dependent.  M any architectures implement data types of a standard size.  ints  and  floats  are often 32-bit,  chars  8-bit, and  doubles  are usually 64-bit.
Reference Reproduced from the Cyber Classroom for C++, How to Program , 5/e by Deitel & Deitel.  Reproduced by permission of Pearson Education, Inc.

More Related Content

PPT
Chap02
PDF
Solutions manual for c++ programming from problem analysis to program design ...
PPT
Chapter 4 5
DOCX
C notes
DOCX
PDF
Problem solving methodology
DOC
Programming in c notes
DOC
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
Chap02
Solutions manual for c++ programming from problem analysis to program design ...
Chapter 4 5
C notes
Problem solving methodology
Programming in c notes
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order

What's hot (20)

PDF
best notes in c language
PPSX
C basics 4 std11(GujBoard)
DOC
Notes of c programming 1st unit BCA I SEM
PDF
Programming in c
PPTX
OOP Poster Presentation
PDF
Handout#05
PDF
Handout#02
PPTX
C language
PDF
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
PPTX
C programming
PDF
Handout#11
PDF
Assignment11
PPT
Programming In C++
PDF
Handout#07
PPT
Unit 4 Foc
DOCX
Uniti classnotes
PPTX
PPT
Chapter3
best notes in c language
C basics 4 std11(GujBoard)
Notes of c programming 1st unit BCA I SEM
Programming in c
OOP Poster Presentation
Handout#05
Handout#02
C language
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming
Handout#11
Assignment11
Programming In C++
Handout#07
Unit 4 Foc
Uniti classnotes
Chapter3
Ad

Similar to Chapter2 (20)

PPT
C++ Overview
PPT
intro to programming languge c++ for computer department
PPT
C chap02
PPT
C chap02
PPT
Ch2 introduction to c
PPTX
C++ AND CATEGORIES OF SOFTWARE
PPTX
Basics Of C++.pptx
PPTX
C Programming Unit-1
PDF
Chap 2 c++
PPT
keyword
PPT
keyword
PPT
C++ programming
PPTX
C++ lecture 01
PPTX
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
PPT
Introduction to Procedural Programming in C++
PDF
Introduction to cpp
PPTX
Fundamental of programming Fundamental of programming
PPS
basics of C and c++ by eteaching
PPTX
#Code2 create c++ for beginners
C++ Overview
intro to programming languge c++ for computer department
C chap02
C chap02
Ch2 introduction to c
C++ AND CATEGORIES OF SOFTWARE
Basics Of C++.pptx
C Programming Unit-1
Chap 2 c++
keyword
keyword
C++ programming
C++ lecture 01
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
Introduction to Procedural Programming in C++
Introduction to cpp
Fundamental of programming Fundamental of programming
basics of C and c++ by eteaching
#Code2 create c++ for beginners
Ad

Recently uploaded (20)

PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Basic Mud Logging Guide for educational purpose
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
Insiders guide to clinical Medicine.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
master seminar digital applications in india
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Cell Structure & Organelles in detailed.
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
human mycosis Human fungal infections are called human mycosis..pptx
Final Presentation General Medicine 03-08-2024.pptx
Basic Mud Logging Guide for educational purpose
O7-L3 Supply Chain Operations - ICLT Program
Week 4 Term 3 Study Techniques revisited.pptx
Insiders guide to clinical Medicine.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
master seminar digital applications in india
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Supply Chain Operations Speaking Notes -ICLT Program
Cell Structure & Organelles in detailed.
FourierSeries-QuestionsWithAnswers(Part-A).pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
2.FourierTransform-ShortQuestionswithAnswers.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
TR - Agricultural Crops Production NC III.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student

Chapter2

  • 1. Chapter 2 Introduction to C++ Programming C++, How to Program Deitel & Deitel
  • 2. Learn C++ by Examples Five examples demonstrate How to display messages How to obtain information from the user How to perform arithmetic calculations
  • 3. Important Parts of a C++ program Comments: //, /* …. */ Preprocessor directives : #include Function main Body of the function Return statement Other statements
  • 4. Comments Explain programs to other programmers Improve program readability Ignored by compiler Single-line comment Begin with // Example // allows program to output data to the screen . Multi-line comment Start with /* End with */
  • 5. Preprocessor Directives Preprocessor directives Processed by preprocessor before compiling Begin with # Example #include <iostream> Tells preprocessor to include the input/output stream header file <iostream> White space s Blank lines, space characters and tabs Delimiter, used to make programs easier to read Extra spaces are ignored by the compiler
  • 6. Function main A part of every C++ program Exactly one function in a program must be main main is a Keyword. Keyword : A word in code that is reserved by C++ for a specific use. Header of function main : int main( ) Body is delimited by braces ( { } )
  • 7. Statements Instruct the program to perform an action All statements end with a semicolon ( ; ) Examples : return 0; std::cout << “Welcome to C++!\n ”;
  • 8. return Statement One of several means to exit a function When used at the end of main The value 0 indicates the program terminated successfully Example return 0;
  • 9. Output Statement (1) std::cout << “Welcome to C++!\n”; std::cout Standard output stream object . Defined in input/output stream header file <iostream> We are using a name ( cout ) that belongs to “namespace” std . Norm ally outputs to computer screen . Stream insertion operator << Value to right (right operand) inserted into left operand . The string of characters contained between “ ” after the operator << shows on computer screen.
  • 10. Output Statement (2) Escape character : backslash : &quot; \ &quot; Escape sequence : A character preceded by backslash ( \ ) Indicates “special” character output Example s : &quot;\n&quot; Newline. Cursor moves to beginning of next line on the screen “ \t” Horizontal tab. Move the screen cursor to the next tab stop.
  • 11. Good Programming Practices Add comments Every program should begin with a comment that describes the purpose of the program, author, date and time. Use good indentation Indent the entire body of each function one level within the braces that delimit the body of the function. This makes a program’s functional structure stand out and helps make the program easier to read.
  • 12. Run C++ Program Save the program with the right extension programOne.cpp Send the program in the right directory Compiling the program: g++ programOne.cpp –o programOne.out Run the executable file ./programOne.out
  • 13. Modifying Our First C++ Program Print text on one line using multiple statements Each stream insertion resumes printing where the previous one stopped Statements: Std::cout << “Welcome ”; Std::cout << “to C++!\n”;
  • 14. Modifying Our First C++ Program Print text on several lines using a single statement . Each newline escape sequence positions the cursor to the beginning of the next line Two newline characters back to back outputs a blank line Example statement : Std::cout << “Welcome \n to \n\n C++! \n ”;
  • 15. Variable Location in memory where value can be stored Common data types (fundamental, primitive or built-in) int – integer numbers : 1, 2, 4,…. char – characters : ‘a’, ‘c’, … float, double – floating point numbers: 2.5, 4.96 The value of a variable could be changed while the program is running.
  • 16. Declaration of Variables (1) Declare variables with name and data type before they are use d. A variable name is any valid identifier that is not a keyword. Series of characters - letters, digits, underscores ( _ ) Cannot begin with digit Case sensitive Choosing meaningful identifiers helps make a program self-documenting .
  • 17. Declaration of Variables (2) Can Declare each variable on a separate line. int integer1; int integer2; int sum; Can declare several variables of same type in one declaration . Comma-separated list int integer1, integer2, sum;
  • 18. Assign Value to Variables Assignment operator = Assigns value on right to variable on left Binary operator (two operands) Assign a value after declaration int integer1; //declaration integer1 = 10; //assignment Declare and assign a value at the same time. int integer2 = 20;
  • 19. Input stream object std::cin from <iostream> Usually connected to keyboard Stream extraction operator >> Waits for user to input value, press Enter (Return) key Stores value in variable to right of operator Converts value to variable data type Example int number1; std::cin >> number1; Reads an integer typed at the keyboard Stores the integer in variable number1
  • 20. Constant variables Declared using the const qualifier Also called named constants or read-only variables Must be initialized with a constant expression when they are declared and cannot be modified thereafter Example: const int size = 5;
  • 21. Arithmetic (1) Arithmetic operators + : Addition - : Subtraction * : Multiplication / : Division Integer division truncates remainder 7 / 5 evaluates to 1 % : Modulus operator returns remainder 7 % 5 evaluates to 2 Attempting to use the modulus operator ( % ) with non - integer operands is a compilation error.
  • 23. Arithmetic (2) Straight-line form Required for arithmetic expressions in C++ All constants, variables and operators appear in a straight line Grouping sub - expressions Parentheses are used in C++ expressions to group sub - expressions Same manner as in algebraic expressions Example a * ( b + c ) Multiple a times the quantity b + c
  • 24. Rules of operator precedence Operators in parentheses evaluated first Nested/embedded parentheses Operators in innermost pair first Multiplication, division, modulus applied next Operators applied from left to right Addition, subtraction applied last Operators applied from left to right
  • 26. Performing Arithmetic Calculation in C++ Program Adding two integers int number1, number2, sum; std::cin >> number1; std::cin >> number2; sum = number 1 + number 2; Add the values of variable1 and variable2 Store result in sum
  • 27. Question Question : int integerOne = 1; double doubleOne = 2.5; int sumOne = integerOne + doubleOne; //A double sumTwo = integerOne + doubleOne; //B Which statement is correct , A or B ?
  • 28. Output Statement With Expression Variables or expressions could be inserted into output statement, its value is printed out. Long output statement could be broken into multiple lines. Example: std::cout << “sum is ” << sum << “. bye-bye! \n”; std::cout << “sum is ” << number1 + number2 ;
  • 29. End of Line Stream manipulator std::endl Outputs a newline Flushes the output buffer
  • 30. Memory Concepts Variable names Correspond to actual locations in computer's memory Every variable has name, type, size and value When new value placed into variable, overwrites old value Writing to memory is destructive Reading variables from memory nondestructive Example sum = number1 + number2; Value of sum is overwritten Values of number1 and number2 remain intact
  • 31. Fig. 2.6 | Memory location showing the name and value of variable number1.
  • 32. Fig. 2.7 | Memory locations after storing values for number1 and number2.
  • 33. Fig. 2.8 | Memory locations after calculating and storing the sum of number1 and number2.
  • 34. Type Sizes and Ranges The size and range of any data type is compiler and architecture dependent. M any architectures implement data types of a standard size. ints and floats are often 32-bit, chars 8-bit, and doubles are usually 64-bit.
  • 35. Reference Reproduced from the Cyber Classroom for C++, How to Program , 5/e by Deitel & Deitel. Reproduced by permission of Pearson Education, Inc.