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

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

Chapter 2: Basic Elements of C++

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

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

Objectives. In this chapter, you will:

Chapter 2 Basic Elements of C++

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

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

Full file at

Chapter 2: Introduction to C++

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

UNIT- 3 Introduction to C++

LECTURE 02 INTRODUCTION TO C++

The C++ Language. Arizona State University 1

BASIC ELEMENTS OF A COMPUTER PROGRAM

Chapter 2: Overview of C++

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

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

6.096 Introduction to C++ January (IAP) 2009

BITG 1233: Introduction to C++

1. In C++, reserved words are the same as predefined identifiers. a. True

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

CS242 COMPUTER PROGRAMMING

CHAPTER 3 BASIC INSTRUCTION OF C++

Programming. C++ Basics

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

Creating a C++ Program

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Lecture 3 Tao Wang 1

Topic 2: C++ Programming fundamentals

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

Operators. Java operators are classified into three categories:

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

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

Fundamentals of Programming CS-110. Lecture 2

Introduction to Programming EC-105. Lecture 2

Chapter 2. C++ Basics

Basics of Java Programming

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

UNIT-2 Introduction to C++

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Chapter 2. Lexical Elements & Operators

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

Visual C# Instructor s Manual Table of Contents

Differentiate Between Keywords and Identifiers

Chapter 2. Outline. Simple C++ Programs

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Introduction of C++ OOP forces us to think in terms of object and the interaction between objects.

Engineering Problem Solving with C++, Etter/Ingber

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

LECTURE 3 C++ Basics Part 2

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

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

CSI33 Data Structures

A First Program - Greeting.cpp

Full file at

Fundamental of Programming (C)

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

Exercise: Using Numbers

Programming for Engineers Introduction to C

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Chapter 2: Using Data

Computer Programming : C++

CSCE 110 PROGRAMMING FUNDAMENTALS

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

CSCI 1061U Programming Workshop 2. C++ Basics

Lecture 2 Tao Wang 1

Basics of Programming

C++ character set Letters:- A-Z, a-z Digits:- 0 to 9 Special Symbols:- space + - / ( ) [ ] =! = < >, $ # ; :? & White Spaces:- Blank Space, Horizontal

3. Java - Language Constructs I

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

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

Chapter 3: Operators, Expressions and Type Conversion

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

DEPARTMENT OF MATHS, MJ COLLEGE

CHAPTER-6 GETTING STARTED WITH C++

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

CS2141 Software Development using C/C++ C++ Basics

CS201 Some Important Definitions

Unit 3. Constants and Expressions

Chapter-8 DATA TYPES. Introduction. Variable:

C: How to Program. Week /Mar/05

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

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Chapter 1 INTRODUCTION

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Intro to Computer Programming (ICP) Rab Nawaz Jadoon

Homework #3 CS2255 Fall 2012

2. Distinguish between a unary, a binary and a ternary operator. Give examples of C++ operators for each one of them.

Fundamentals of Programming

2 nd Week Lecture Notes

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

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

CSc Introduction to Computing

Chapter 2 - Introduction to C Programming

JAVA Programming Fundamentals

Introduction to Programming

Transcription:

EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic operators and their evaluation Assignment statement Input and Output statements increment and decrement operators Preprocessor directives C++ structure; write a C++ program Assistant Prof. Dr. Turgay IBRIKCI Tuesday, September 07, 2010 2 Programming Computer program - a sequence of statements designed to accomplish some task Programming - a process of planning and creating a program Syntax - rules that tell us which statements (instructions) are legal Programming language - a set of rules, symbols, and special words Semantic rules - determine the meaning of the instructions Metalanguage - language used to write the syntax rules C++ Programs A C++ program is a collection of one or more subprograms, called functions A subprogram or a function is a collection of statements that when activated (executed) accomplishes something Every C++ program has a function called main The smallest individual unit of a program written in any language is called a token 3 4 Symbols Special symbols include: -+ -- -* -/ -. -; -? -, -<= -!= -== ->= Symbols Word symbols are called reserved words, or keywords include: int, float, double, char, void, return 5 6

Identifiers Consist of letters, digits, and the underscore character (_) Must begin with a letter or underscore C++ is case sensitive uppercase and lower case letters are different Some of the predefined identifiers are cout and cin Unlike reserved words, predefined identifiers may be redefined, but it would not be wise to do so Legal and Illegal Identifiers The following are legal identifiers in C++: first conversion payrate 7 8 Simple Data Types Values and Memory Allocation Data Type - a set of values together with a set of operations is called a data type C++ simple data can be classified into three categories integral - deals with integers, or numbers without a decimal part floating-point - deals with decimal numbers enumeration type - user-defined data type 9 10 int Data Type Examples: -6728 0 78 Positive integers do not have to have a + sign in front of them No commas are used within an integer In C++ commas are reserved for separating items in a list bool Data Type The data type bool has two values, true and false The central purpose of this data type is to manipulate logical (Boolean) expressions True and false are called logical (Boolean) values In C++ bool, true, and false are reserved words 11 12

char Data Type The smallest integral data type Used to represent characters, that is letters, digits, and special symbols Each character is enclosed within single quote marks Some of the values belonging to char data type are: 'A', 'a', '0', '*', '+', '$', '&' A blank space is a character and is written ' ', with a space left between the single quotes Floating-Point Data Types To represent real numbers C++ uses scientific notation called floating-point notation 13 14 Floating-Point Data Types Float - used in C++ to represent any real number between - 3.4E+38 and 3.4E+38 The memory allocated for the float data type is 4 bytes Double - used in C++ to represent any real number between - 1.7E+308 and 1.7E+308 The memory allocated for the double data type is 8 bytes On most newer compilers, the data types double and long double are the same Floating-Point Data Types The maximum number of significant digits (decimal places) in float values is 6 or 7 Float values are called single precision The maximum number of significant digits in values belonging to the double type is 15 Double values are called double precision The maximum number of significant digits is called the precision 15 16 string Data Type Programmer-defined type supplied in the standard library Sequence of zero or more characters Enclosed in double quotation marks A string with no characters is called a null or empty string Every character has a relative position in the string The position of the first character is 0, the position of the second character is 1, and so on Length of a string is the number of characters in it M y C a T Arithmetic Operators C++ Operators + addition - subtraction * multiplication / division % remainder (mod operator) The operators +, -, *, and / can be used with both integral and floating-point data types The % is used only with the integral data type to find the remainder in ordinary division Unary operator - has only one operand Binary Operator - has two operands 0 1 2 3 4 5 17 18

Order of Precedence All operations inside of ( ) are evaluated first The operators *, /, and % are at the same level of precedence and are evaluated next The operators + and have the same level of precedence and are evaluated last When operators are all on the same level, they are performed from left to right Mixed Expressions Mixed expression - an expression that has operands of different data types Contains both integers and floating-point numbers Examples of mixed expressions: 2 + 3.5 6 / 4 + 3.9 5.4 * 2 13.6 + 18 / 2 Type Type Casting Casting Forms Forms 1. 1. static_cast<datatypename>(expression) 2. 2. datatype datatype (expression) 19 20 Evaluating Mixed Expressions If the operator has the same types of operands, it is evaluated according to the type of the operands If the operator has both types of operands, during calculation the integer is changed to a floating-point number with the decimal part of zero and the operator is evaluated the result is a floating-point number Evaluating Mixed Expressions The entire expression is evaluated according to the precedence rules the multiplication, division, and modulus operators are evaluated before the addition and subtraction operators operators having the same level of precedence are evaluated from left to right grouping is allowed for clarity 21 22 Assignment Statement The assignment statement takes the form: variable = expression; The expression is evaluated and its value is assigned to the variable on the left side In C++ = is called the assignment operator A C++ statement like: I = I + 2; Evaluates whatever is in I, adds two to it, and assigns the new value to the memory location I Declaring & Initializing Variables Variables can be initialized when they are declared For example: int first=13, second=10; char ch=' '; double x=12.6, y=123.456; This will declare first and second as integer and fill them with the values 13 and 10 respectively 23 24

Allocating Memory Named Constant - memory location whose content is not allowed to change during program execution Variable - a memory location whose content may change during program execution The syntax to declare a named constant is: const datatype identifier = value; In C++, const is a reserved word Input (Read) Statement Syntax of cin together with >> is used to gather input cin>>variable>>variable...; The extraction operator is >> For example, if miles is a variable of the type double the statement: cin>>miles; It causes the computer to get a value of the type double and place it in the memory cell miles 25 26 Input Statement Using more than one variable in cin allows more than one value to be read at a time For example, if feet and inch are variables of the type int a statement like: cin>>feet>>inch; Inputs two integers that are entered at the keyboard and places them in the memory location feet and inch, respectively Increment & Decrement Operators Increment operator - increment the value of a variable by 1 Decrement operator - decrement the value of a variable by 1 Pre-increment: ++variable Post-increment: variable++ Pre-decrement: --variable Post-decrement: variable-- 27 28 Increment & Decrement Operators For example: ++count; or count++ increments the value of count by 1 --count; or count decrements the value of count by 1 If you have x = 5; and y = ++x; after the second statement both x and y are 6. If you have x = 5; and y = x++; after the second statement y is 5 and x is 6. Output The syntax of cout together with << is: cout<< <<expression or manipulator<< <<expression or manipulator...; This is called an output statement The << operator is called the insertion operator or the stream insertion operator Sometimes this is also called a cout statement 29 30

Output In the example: cout<< expression or manipulator << expression or manipulator...; Expression - is evaluated and its value is printed at the current cursor position on the screen Manipulator - manipulates the output endl - the simplest manipulator causes the cursor to move to the beginning of the next line Output Example The output of the C++ statement cout<<a; is meaningful provided the variable a has been given a value For example, the sequence of C++ statements, a = 45; cout<<a; will produce an output of 45 31 32 Program Example int a, b, c, d; a = 65 ; //Line 1 b = 78 ; //Line 2 OUTPUT cout<<29/4<<endl; //Line 3 7 cout<<3.0/2<<endl; //Line 4 1.5 cout<<"hello there.\n"; //Line 5 Hello there. cout<<7<<endl; //Line 6 7 cout<<3+5<<endl; //Line 7 8 cout<<"3+5"; //Line 8 3.5 cout<<endl; //Line 9 The New Line Character The new line character is \n Without this character the output is printed on one line This command tells the output to go to the next line When \n is encountered in the string, the cursor is positioned at the beginning of the next line A \n may appear anywhere in the string 33 34 Examples Common Escape Sequences 35 Without the new line character: cout<<"hello there."; cout<<"my name is Goofy."; Hello there.my name is is Goofy. With the new line character: cout<<"hello there.\n"; cout<<"my name is Goofy."; Hello there. My name is is Goofy. 36

Preprocessor Directives Only a small number of operations are explicitly defined in C++ 37 Many of the functions and symbols that are necessary to run a C++ program are provided as a collection of libraries Every library has a name and is referred to by a header file Preprocessor directives are commands supplied to the preprocessor All preprocessor commands begin with # There is no semicolon at the end of these commands Preprocessor Directive Syntax 38 The general syntax to include a header file (provided by the SDK) in a C++ program is: #include <headerfilename> The preprocessor directive causes the preprocessor to include the header file iostream in the program The syntax is: #include <iostream> Header Files In Standard C++, header files have the file extension.h The descriptions of the functions needed to perform I/O are contained in the header file iostream.h The syntax is: #include <iostream.h> #include <math.h> 39 40 Program Style and Form The Program Part every C++ program has a function main the basic parts of the function main are: - The heading - The body of the function The heading part has the following form typeoffunction main(argument list) Body and Syntax The body of the function is enclosed between { and } It has two types of statements declaration statements executable statements Syntax Errors in syntax are detected during compilation. int x; //Line 1 int y double z; //Line 3 //Line 2: syntax error y = w + x; //Line 4: syntax error 41 42

Statements Declaration Statements int a, b, c; double x, y; Variables can be declared anywhere in the program, but they must be declared before they can be used Executable Statements have three forms: a = 4; cin>>b; cout<<a<<endl<<b<<endl; //assignment statement //input statement //output statement Special Characters Use of Blanks one or more blanks are used to separate numbers when data is input blanks are also used to separate reserved words and identifiers from each other and other symbols The blanks between the identifiers in the second statement are meaningless: int a,b,c; int a, b, c; In the statement: inta,b,c; no blank between the t and a changes the reserved word int and the identifier a into a new identifier, inta. 43 44 Example: hourly_pay or or hourlypay Semicolons, Brackets, & Commas Commas are used to separate items in a list All C++ statements terminate with a semicolon The semicolon is also called a statement terminator { and } are not C++ statements Semantics It is possible to eradicate all syntax errors in a program and still not have it run It is also possible that if it runs it still may not do what you meant it to do For example, 2 + 3 * 5 and (2 + 3) * 5 are both syntactically correct expressions, but have different meanings 45 46 Form and Style Consider the following two ways of declaring variables: Method 1 int feet, inch; double x, y; Method 2 int a,b;double x,y; Both are correct, however, the second declares all of the variables on one line Documentation Comments can be used to document the code Single line comments begin with // anywhere in the line Multiple line comments are enclosed between /* and */ Name identifiers with meaningful names Run-together-words can be handled either by using CAPS for the beginning of each new word or an underscore just before the new word 47 48

Programming Example Write a program that takes as input a given length expressed in feet and inches. It then converts and outputs the length in centimeters. Input: Length in feet and inches. Output: Equivalent length in centimeters. The lengths are given in feet and inches The program will need to find the equivalent length in centimeters One inch is equal to 2.54 centimeters Programming Example The first thing the program needs to do is convert the length given in feet and inches to all inches Next, use the conversion formula, 1 inch = 2.54 centimeters, to find the equivalent length in centimeters To convert the length from feet and inches to inches, multiply the number of feet by 12, as 1 foot is equal to 12 inches, and add the given inches Then apply the conversion formula, that is, 1 inch = 2.54 centimeters, to find the length in centimeters 49 50 Programming Example The algorithm is as follows: get the length in feet and inches convert the length into total inches convert total inches into centimeters output centimeters Variables and Constants Variables int feet; int inches; int totalinches; double centimeters; Named Constant //holds given feet //holds given inch const double conversion = 2.54; const int inchesperfoot = 12; //holds total inches // holds length in centimeters 51 52 Main Algorithm Prompt the user for the input Without the prompt, the user will have a blank screen Get the data Echo the input output what the program read as input without this step the input would not be seen once the program is run Find the length in inches Output the length in inches Convert the length to centimeters Output the length in centimeters Putting It Together The program will begin with comments that document its purpose and functionality The system resources will be used for input/output The program will use input statements to get data into the program and output statements to print the results The data will be entered from the keyboard and the output will be displayed on the screen, the program must include the header file iostream The first statement of the program, after the comments as described above, will be the preprocessor directive to include this header file 53 54

Putting It Together This program requires two types of memory locations for data manipulation: named constants and variables. Named constants are usually placed before the function main so that they can be used throughout the program. This program has only one function, the function main, which will contain all of the programming instructions in its body. The program needs variables to manipulate data, and these variables will be declared in the body of the function main. Body of the Function The body of the function main has the following form: int main () { } declare variables statements return 0; 55 56 Writing a Complete Program Begin the program with comments for documentation Include header files, if any are used in the program Declare named constants, if any Write the definition of the function main KEY TERMS Increment/decrement operator ++ or --: increases or decreases the value of a variable by 1 Identifiers: names of things that appear in programs; I.e. variables, constants, and functions Named constant: a memory location whose content is not allowed to change during program execution Order of precedence: the order of evaluation in an expression Semantic rules: determine the meaning of the instructions Syntax rules: tell which statements (instructions) are legal, or accepted by the programming language, and which are not Variable: a memory location whose content may change during program execution Word symbols or Reserved words or keywords: have a specific meaning and cannot be redefined within any program 57 58 DONT FORGET TO CHECK THE HOMEWORK01 OUT 59 60