Chapter 2: Basic Elements of C++

Slides:



Advertisements
Similar presentations
Chapter 2: Basic Elements of C++
Advertisements

© 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5/e Starting Out with C++: Early Objects 5 th Edition Chapter 2 Introduction.
Data types and variables
Chapter 2: Basic Elements of C++
Chapter 2 Data Types, Declarations, and Displays
Chapter 2: Basic Elements of C++
Chapter 2: Introduction to C++.
Chapter 2: Basic Elements of C++
Basic Elements of C++ Chapter 2.
CHAPTER 2 BASIC ELEMENTS OF C++. In this chapter, you will:  Become familiar with the basic components of a C++ program, including functions, special.
Objectives You should be able to describe: Data Types
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Seventh.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 2 Introduction to C++
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
Week 1 Algorithmization and Programming Languages.
C++ Programming: Basic Elements of C++.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
Introduction to C++ Basic Elements of C++. C++ Programming: From Problem Analysis to Program Design, Fourth Edition2 The Basics of a C++ Program Function:
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Sixth.
CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Basic Elements of C++
Chapter 2: Introduction to C++. Outline Basic “Hello World!!” Variables Data Types Illustration.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 2: Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Chapter 2: Basic Elements of C++. Introduction Computer program – Sequence of statements whose objective is to accomplish a task Programming – Process.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 2: Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++. Objectives In this chapter, you will: – Become familiar with the basic components of a C++ program, including functions,
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Bill Tucker Austin Community College COSC 1315
TK1913 C++ Programming Basic Elements of C++.
Chapter 2: Basic Elements of C++
Chapter Topics The Basics of a C++ Program Data Types
Computer Programming BCT 1113
Chapter 2: Introduction to C++
BASIC ELEMENTS OF A COMPUTER PROGRAM
Basic Elements of C++.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2: Basic Elements of C++
Chapter 2: Introduction to C++
Basic Elements of C++ Chapter 2.
Chapter 2: Introduction to C++
2.1 Parts of a C++ Program.
Chapter 2: Basic Elements of Java
elementary programming
Chapter 2: Introduction to C++.
Engineering Problem Solving with C++ An Object Based Approach
Engineering Problem Solving with C++ An Object Based Approach
Programming Fundamental-1
Presentation transcript:

Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++ Slides borrowed from Instructor: Wajih Alouini

Objectives In this chapter, you will: Become familiar with the basic components of a C++ program, including functions, special symbols, and identifiers Explore simple data types Discover how to use arithmetic operators Examine how a program evaluates arithmetic expressions

Objectives (continued) Learn what an assignment statement is and what it does Become familiar with the string data type Become familiar with the use of increment and decrement operators

What Is a Program Made Of? Common elements in programming languages: Keywords Programmer-Defined Identifiers Operators Punctuation Syntax Slide 1- 4

The Basics of a C++ Program Function: collection of statements; when executed, accomplishes something May be predefined or standard Syntax: The rules of grammar that must be followed when writing a program (keywords, operators, symbols, and punctuation) Programming language: a set of rules, symbols, and special words Semantic rule: meaning of the instruction

Structure of a C program Statement = Command or instruction

Parts of a C++ Program // sample C++ program #include <iostream> comment // sample C++ program #include <iostream> using namespace std; int main() { cout << "Hello, there!"; return 0; } preprocessor directive which namespace to use beginning of function named main beginning of block for main output statement - Return 0 means program has executed main function (int ) successfully string literal send 0 to operating system end of block for main

Comments Single line Multiple line Comment is a statement that is not executed. This helps reader and also yourself to understand your codes and document parts of the program. Two types: Single line // This is a C++ program. It prints the sentence: // Welcome to C++ Programming. Multiple line /* You can include comments that can occupy several lines. */

Special Symbols Special symbols + - * / . ; ? , <= != == >=

Punctuation Characters that mark the end of a statement, or that separate items in a list Example: , and ;

Reserved Words (Keywords) Have a special meaning in C++ Can not be used for any other purpose Include: int, float, double, char, const, void, return, main, etc.

Identifiers Names made up by the programmer Not part of the C++ language Used to represent various things: variables (memory locations), functions, etc. - How to write identifiers

Naming Identifiers Identifiers can be self-documenting: CENTIMETERS_PER_INCH Avoid run-together words : annualsale Solution: Capitalize the beginning of each new word annualSale Inserting an underscore just before a new word annual_sale

Identifiers (cont) Cannot duplicate a reserved word Consist only of letters, digits, or the underscore character (_) First character must be alphabetic character or underscore C++ is case sensitive NUMBER is not the same as number Two predefined identifiers are cout and cin

Identifiers (cont) The following are legal identifiers in C++: first conversion payRate

Identifiers (cont) Valid OR Invalid ? A $a Student8 3name student_name person name _person_name int TRUE what? FALSE

Whitespaces Every C++ program contains whitespaces Include blanks, tabs, and newline characters Used to separate special symbols, reserved words, and identifiers Proper utilization of whitespaces is important Can be used to make the program readable

Arithmetic Operators and Operator Precedence C++ arithmetic operators used for performing numeric calculations : + addition - subtraction * multiplication / division % modulus operator +, -, *, and / can be used with integral and floating-point data types - integral: no decimal part

Binary Arithmetic Operators C++ has unary, binary, and ternary operators: unary (1 operand) -5 binary (2 operands) 13 - 7 ternary (3 operands) exp1 ? exp2 : exp3 SYMBOL OPERATION EXAMPLE VALUE OF ans + addition ans = 7 + 3; 10 - subtraction ans = 7 - 3; 4 * multiplication ans = 7 * 3; 21 / division ans = 7 / 3; 2 % modulus ans = 7 % 3; 1 - Modulo is the reminder of the division after getting the result 1-19

Scope The scope of a variable: the part of the program in which the variable can be accessed A variable cannot be used before it is defined

A Closer Look at the / Operator / (division) operator performs integer division if both operands are integers cout << 13 / 5; // displays 2 cout << 91 / 7; // displays 13 If either operand is floating point, the result is floating point cout << 13 / 5.0; // displays 2.6 cout << 91.0 / 7; // displays 13.0

A Closer Look at the % Operator % (modulus) operator computes the remainder resulting from integer division cout << 13 % 5; // displays 3 % requires integers for both operands cout << 13 % 5.0; // error

Order of Precedence All operations inside of () are evaluated first *, /, and % are at the same level of precedence and are evaluated next + and – have the same level of precedence and are evaluated last When operators are on the same level Performed from left to right (associativity) 3 * 7 - 6 + 2 * 5 / 4 + 6 means (((3 * 7) – 6) + ((2 * 5) / 4 )) + 6

Expressions If all operands are integers Expression is called an integral expression Yields an integral result Example: 2 + 3 * 5 If all operands are floating-point Expression is called a floating-point expression Yields a floating-point result Example: 12.8 * 17.5 - 34.50

Mixed Expressions Mixed expression: Examples of mixed expressions: Has operands of different data types Contains integers and floating-point Examples of mixed expressions: 2 + 3.5 6 / 4 + 3.9 5.4 * 2 – 13.6 + 18 / 2

Mixed Expressions (continued) Evaluation rules: If operator has same types of operands Evaluated according to the type of the operands If operator has both types of operands Integer is changed to floating-point Operator is evaluated Result is floating-point Entire expression is evaluated according to precedence rules

string Type Programmer-defined type supplied in ANSI/ISO Standard C++ library A series of zero or more characters in consecutive memory locations: "Hello" Stored with the null terminator, \0, at the end Enclosed in double quotation marks Null: a string with no characters Each character has relative position in string Position of first character is 0 - Location for string start from 0 to …etc whit spaces should be included

Input Data must be loaded into main memory before it can be manipulated Storing data in memory is a two-step process: Instruct computer to allocate memory Include statements to put data into memory

Allocating Memory with Constants and Variables Named constant: memory location whose content can’t change during execution The syntax to declare a named constant is: In C++, const is a reserved word

Allocating Memory with Constants and Variables (continued) Constant = named memory location that holds a non-changeable value Must be declared A variable name should represent the purpose of the variable. Re-usable MUST be initialized Can not be modified after initialization int main () { const double pi = 3.14; double area, radius; radius = 12; area = pi * radius * radius; pi = 3.14159; /* but, this is wrong */ return 0; }

Allocating Memory with Constants and Variables Variable: memory named storage location in the computer’s memory for holding a piece of data whose content may change during execution The syntax to declare a named constant is:

Allocating Memory with Constants and Variables (continued) In order to use a variable in our program we must first declare it. HOW? A declaration statement has the format: type variable_name; type : what kind of data will be stored in that location (integer? character? floating point?) variable_name : what is the name of the variable? semi-colon : indicates this is a statement!

Variable types There are four basic data types in C Type Integer Floating point Character C keyword to use: int float double char

Variable types int Integer variables hold signed whole numbers (i.e. with no fractional part), such as 10, – 4353, etc. Integers typically take up 4 bytes ( = 32 bits, 1 for the sign, 31 for the number). The range of integers is typically from – 231 (approx –109) to + 231 (approx. 109)

Variable types float and double floating point variables hold signed floating point numbers (i.e. with a fractional part), such as 10.432, – 33.335, etc. double provides twice the precision of float. floats typically take up 4 bytes doubles take up 8 bytes The range of floats is approximately ±2127 (±1038) The range of doubles is approximately ±21023 (±10308)

Variable types char character variables hold single characters, such as 'a', '\n', ' ', etc. characters usually take 1 byte (8 bits). IMPORTANT : Note that the value of a character is enclosed in single quotes.

Variable types char (continued) ASCII (American Standard Code for Information Exchange) is used to represent the characters A to Z (both upper and lower case) the digits 0 to 9 special characters (e.g. @, <, etc) special control codes For example, the character 'A' is represented by the code 65 the character '1' is represented by the code 49 IMPORTANT: the integer 1, the character '1' and the ASCII code 1 represent three different things!

Variable values After a variable has been declared, its memory location does not contain valid data. Variables can be initialized when declared: All variables must be initialized before they are used in any computations. But not necessarily during declaration There are two ways to initialize a variable: by assigning a value using an assignment statement by reading its value from the keyboard

Variable Initialization Variable values Variable Initialization To initialize a variable means to assign it a value when it is defined: int length = 12; Can initialize some or all variables: int length = 12, width = 5, area;

Variable values The basic syntax of an assignment statement is Example Assign the value on the right hand side to the variable on the left hand side Expression is evaluated and its value is assigned to the variable on the left side In C++, = is called the assignment operator int num_students; // declare num_students = 22; // initialize

Variable values

Literals Literals are fixed values written into a program. Example: Not declared, no memory location assigned Not re-usable; just written directly into each statement Example: char keypressed; keypressed = ‘y’; /* ‘y’ is a character literal */ double pi; pi = 3.14; /* 3.14 is a floating-point literal. */ int index; index = 17; /* 17 is an integer literal */

Example /* sample program that demonstrates variable declaration and initialization. */ #include <stdio.h> int main () { int num_students; num_students = 22; return 0; }

Example /* sample program that demonstrates variable declaration and initialization. */ #include <stdio.h> int main () { double rate, amount; /* declare two double variables */ amount = 12.50; rate = 0.05; return 0; }

Example /* sample program that demonstrates how to declare and initialize a variable at the same time */ #include <stdio.h> int main () { char grade = ‘A’; return 0; }

Example /* sample program that demonstrates how to declare and initialize a variable at the same time */ #include <stdio.h> int main () { char pass_grade = ‘A’, fail_grade = ‘F’; return 0; }

Increment & Decrement Operators Increment operator: increment variable by 1 Pre-increment: ++variable Post-increment: variable++ Decrement operator: decrement variable by 1 Pre-decrement: --variable Post-decrement: variable — — What is the difference between the following? x = 5; y = ++x; x = 5; y = x++;

Increment & Decrement Operators (Continued) postincrement operator n++; can be used instead of n = n + 1;  postdecrement operator n--; can be used instead of n = n - 1; preincrement operator ++n; can be used instead of n = n + 1;  predecrement operator --n; can be used instead of n = n - 1;

Increment & Decrement Operators (Continued) n++;++n and n--;--n are not equivalent in all cases These operators as well as incrementing or decrementing the variable also return a value. i = n++; Value of i ? Is it the old value of n before it is incremented or the new value after it is incremented?

Increment & Decrement Operators (Continued) Rule : postincrement or postdecrement operator delivers the old value of the variable before incrementing or decrementing the variable. A preincrement or predecrement operator carries out the incrementation first and then delivers the new value. n = 5 ; i = n++;  Give 5 to i and 6 to n n = 5 ; i = ++n;  Give 6 to i and 6 to n.

Specialised Assignment Statements sum = sum + x; can be represented in C++ by: sum += x; This notation can be used with the arithmetic operators +, -, *, / and %.  General form : variable op= expression which is interpreted as being equivalent to: variable = variable op ( expression )

Specialised Assignment Statements (Continued) total += value; or total = total + value; prod *= 10; prod = prod * 10; x /= y + 1; x = x/(y + 1); n %= 2; n = n % 2;