Chapter 2. C++ Syntax and Semantics, and the Program Development Process. Dale/Weems 1

Size: px
Start display at page:

Download "Chapter 2. C++ Syntax and Semantics, and the Program Development Process. Dale/Weems 1"

Transcription

1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems 1

2 Chapter 2 Topics Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation Output Statements C++ Program Comments 2

3 An Important Problem Solving Technique Divide and conquer -- break up large problems into manageable units Functions 3

4 A C++ program is a collection of one or more functions There must be a function called main() Execution always begins with the first statement in function main() Any other functions in your program are subprograms and are not executed until they are called 4

5 Program With Several Functions main function square function cube function 5

6 Program With Three Functions #include <iostream> int Square(int); int Cube(int); // Declares these two // value-returning functions using namespace std; int main() { cout << The square of 27 is << Square(27)<< endl; // Function call } cout << The cube of 27 is << Cube(27)<< endl; // Function call return 0; 6

7 Rest of Program int Square(int n) { return n * n; } int Cube(int n) { return n * n * n; } 7

8 Output of program The square of 27 is 729 The cube of 27 is

9 Shortest C++ Program type of returned value name of function int main() { return 0; } 9

10 What is in a heading? type of returned value name of function says no parameters int main( ) 10

11 Block(Compound Statement) A block is a sequence of zero or more statements enclosed by a pair of curly braces { } SYNTAX { } Statement (optional)... 11

12 Every C++ function has 2 parts int main() { return 0; } heading body block 12

13 Syntax and Semantics syntax (grammar) rules that specify how valid instructions (constructs) are written semantics rules that specify the meaning of syntactically valid instructions The syntax of an assignment statement requires that you have: l-value = expression; where l-value is something, like a variable, whose value can be changed, and expression is a valid C++ expression. The semantic rule for an assignment statement specifies that the value of the expression on the right side is stored in the l-value on the left side. For example: const int totaldays = 25567; // NOT an l-value int dayspassed; // l-values int daysleft; dayspassed = 17094; daysleft = totaldays - dayspassed; 13

14 C++ Reserved Words The C++ Standard specifies certain symbols and words as the official "vocabulary" of the C++ language. These reserved words (and symbols) are preempted by the C++ language definition and may only be used in the manner the language rules specify. Fortunately the number of reserved words is relatively small (< 300). Here's a sample: bool const double for return break continue else if struct case default enum int switch char delete false long typedef class do float new while There is a complete list of C++ reserved words in Appendix A of the Dale book. Note that all the C++ reserved words are strictly lower-case. Your C++ code will be more readable if you choose mixedcase or upper-case identifiers. 14

15 Directives Directives provide instructions to the pre-processor, which "edits" your C++ language code before it is read by the C++ compiler. Directives are most commonly used to incorporate standard header files into your program: #include <iostream> // embed the file "iostream" here Directives may also be used to declare identifiers: #define NUMBER 100 // replace every occurrence of NUMBER // with the value

16 What is an Identifier? An identifier is the name used for a data object(a variable or a constant), or for a function, in a C++ program Beware: C++ is a case-sensitive language Using meaningful identifiers is a good programming practice 16

17 Identifiers An identifier must start with a letter or underscore, and be followed by zero or more letters (A-Z, a-z), digits(0-9), or underscores VALID age_of_dog PrintHeading taxratey2k ageofhorse NOT VALID (Why?) age# 2000TaxRate Age-Of-Cat 17

18 More About Identifiers Some C++ compilers recognize only the first 32 characters of an identifier as significant Then these identifiers are considered the same: age_of_this_old_rhinoceros_at_my_zoo age_of_this_old_rhinoceros_at_my_safari Consider these: Age_Of_This_Old_Rhinoceros_At_My_Zoo age_of_this_old_rhinoceros_at_my_zoo 18

19 C++ Data Types simple structured integral enum floating array struct union class char short int long bool float double long double address pointer reference 19

20 C++ Simple Data Types simple types integral floating char short int long bool enum float double long double unsigned 20

21 Standard Data Types in C++ Integral Types represent whole numbers and their negatives declared as int, short, or long Floating Types represent real numbers with a decimal point declared as float, or double Character Types represent single characters declared as char 21

22 The Simple Data Types C++ has only four simple data types (classes of data): integer - positive or negative whole number: 5280, -47, 0, three subtypes: int, short, long real - positive or negative decimal number: , 98.6, -3.45E04 - three subtypes: float, double, long double character - letter, digit, punctuation, special symbols: 'x', ' ', '!', '\n' - one subtype: char Boolean* - logical value (true or false) - one subtype: bool 22

23 More on the Simple Data Types Integer representation: - short is typically 2 bytes, int and long are typically 4 bytes. - int values range roughly from 2 billion to 2 billion. Decimal number representation: - float is typically 4 bytes, double is typically 8 bytes. - double stores (at best) approximately 15 significant digits, float about 7 - normally use double for increased accuracy of computed results. - double values range roughly from to most decimal values cannot be stored EXACTLY, even as a double, so use integer types when possible. - decimal values are stored in a different way than integer values (even 1.0!). Character representation: - char variable holds a single character at a time. - stored value is a binary code representing the character, usually ASCII. - char variables occupy 1 byte. Boolean value representation: - bool variables typically occupy 1 byte. 23

24 What is a Variable? A variable is a location in memory that can be referred to by an identifier and in which a data value that can be changed is stored Declaring a variable means specifying both its name and its data type 24

25 What Does a Variable Declaration Do? int ageofdog; float taxrate; char middleinitial; A declaration tells the compiler to allocate enough memory to hold a value of this data type and to associate the identifier with this location 4 bytes for taxratey2k 1 byte for middleinitial 25

26 Initialization Declaring a variable does not (usually) automatically provide it with a specific starting value. A variable is just a name for a location in the computer's memory. Memory cannot be "empty", it always stores some value. For all practical purposes, the variable declarations on the previous slide create variables whose initial values are random garbage, whatever happens to be at the corresponding location in memory when the program is executed. Using the value of a variable that has not yet been properly set is one of the most common sources of errors in programs. Therefore, it is good practice to always give every newly declared variable a specific initial value. This can be combined with the declaration or accomplished via a later assignment: int Weight = 0, Height = 0, Length = 0; double ClassAverage = 0.0, GPA = 0.0; string Major; 26 Major = "Computer Science";

27 C++ Data Type String A string is a sequence of characters enclosed in double quotes Sample string values Hello Year The empty string(null string)contains no characters and is written as 27

28 More About Type String A string is not a built-in(standard)type It is a programmer-defined data type It is provided in the C++ standard library String operations include Comparing 2 string values Searching a string for a particular character Joining one string to another 28

29 What is a Named Constant? A named constant is a location in memory that can be referred to by an identifier and in which a data value that cannot be changed is stored Valid constant declarations const string STARS = **** ; const float NORMAL_TEMP = 98.6; const char BLANK = ; const int VOTING_AGE = 18; const float MAX_HOURS = 40.0; 29

30 Giving a Value to a Variable Assign(give)a value to a variable by using the assignment operator = Variable declarations string firstname; char middleinitial; char letter; int ageofdog; Valid assignment statements firstname = Fido ; middleinitial = X ; letter = middleinitial; ageofdog = 12; 30

31 What is an Expression in C++? An expression is a valid arrangement of variables, constants, and operators In C++ each expression can be evaluated to compute a value of a given type The value of the expression is 14 31

32 Assignment Operator Syntax Variable = Expression Done second Result is stored in variable Expression is evaluated Done first 32

33 String Concatenation(+) Concatenation is a binary operation that uses the + operator At least one of the operands must be a string variable or named string constant-- the other operand can be a string literal or a char variable, literal, or constant 33

34 Concatenation Example const string WHEN = Tomorrow ; const char EXCLAMATION =! ; string message1; string message2; message1 = Yesterday ; message2 = and ; message1 = message1 + message2 + WHEN + EXCLAMATION; 34

35 Insertion Operator(<<) Variable cout is predefined to denote an output stream that goes to the standard output device(display screen) The insertion operator << called put to takes 2 operands The left operand is a stream expression, such as cout The right operand is an expression of a simple type or a string constant 35

36 Output Statements SYNTAX cout << Expression << Expression...; These examples yield the same output: cout << The answer is ; cout << 3 * 4; cout << The answer is << 3 * 4; 36

37 Is compilation the first step? No; before your source program is compiled, it is first examined by the preprocessor that removes all comments from source code handles all preprocessor directives--they begin with the # character such as #include <iostream> This include tells the preprocessor to look in the standard include directory for the header file called iostream and insert its contents into your source code 37

38 No I/O is built into C++ Instead, a library provides an output stream executing program ostream Screen 38

39 Using Libraries A library has 2 parts Interface(stored in a header file)tells what items are in the library and how to use them Implementation(stored in another file)contains the definitions of the items in the library #include <iostream> Refers to the header file for the iostream library needed for use of cout and endl. 39

40 Function Concept in Math f(x) = 5 x - 3 Function definition Name of function Parameter of function When x = 1, f(x)= 2 is the returned value When x = 4, f(x)= 17 is the returned value Returned value is determined by the function definition and by the values of any parameters 40

41 C++ Program // ****************************************************** // PrintName program // This program prints a name in two different formats // ****************************************************** #include <iostream> #include <string> // for cout and endl // for data type string using namespace std; const string FIRST = Herman ; // Person s first name const string LAST = Smith ; // Person s last name const char MIDDLE = G ; // Person s middle initial 41

42 C++ Code Continued int main() { string firstlast; // Name in first-last format string lastfirst; // Name in last-first format firstlast = FIRST + + LAST; cout << Name in first-last format is << endl << firstlast << endl; lastfirst = LAST +, + FIRST + ; cout << Name in first-last format is << endl << lastfirst << MIDDLE <<. << endl; } return 0; 42

43 Output of Program Name in first-last format is Herman Smith Name in last-first-initial format is Smith, Herman G. 43

44 Categories of Programming Errors Language syntax (compilation) errors: - Error is in the form of the statement: misspelled word, unmatched parenthesis, comma out of place, etc. - Error is detected by the compiler (at compile time). - Compiler cannot correct error, so no object file is generated. - Compiler prints error messages, but usually continues to compile. 44

45 Categories of Programming Errors Linking errors: - Error is typically in the form of the declaration or implementation or call of a function. - Error may also result from including the wrong header file. - Error is detected by the linker (after the compiler has produced an object file). - Linker cannot correct error, so no executable file is generated. - Linker prints error messages, but usually 45 continues link analysis.

46 Categories of Programming Errors Execution (runtime) errors: - Error occurs while the program is running, causing the program to "crash" (terminate abnormally) and usually producing an error message from the operating system. - Error is frequently an illegal operation of some sort. The most common are arithmetic errors like an attempt to divide by zero, and access violations when the program tries to use some resource like a memory address that is not allocated to it. - Program source code compiles and links without errors no help there. - Unfortunately, some operating systems do not reliably detect and respond to some kinds of execution errors. In that case, an incorrect program may appear to function correctly on one 46 computer but not on another.

47 Categories of Programming Errors Logic errors: - Error occurs while the program is running, causing the production of incorrect results, but not necessarily a runtime "crash". - Program source code compiles and links without errors no help there. - Logic errors are detected by checking results computed by the program. - The cause(s) of the error must be determined by a logical analysis of the error and the source code. This must be done by the developer. This is the hardest type of error to deal with. 47

48 Analyze the problem statement Design a solution Enter/edit source code Find error in source code check syntax Compile/link source code Compiler/Linker errors? no yes Find cause of runtime error check code check input data rethink analysis/design or Test the program Execution errors? no Results incorrect? yes yes no Find cause of logic error check code check input data rethink analysis/design Success! At least with this input. or 48

49 Creating a Chessboard Problem Your college is hosting a chess tournament, and the people running the tournament want to record the final positions of the pieces in each game on a sheet of paper with a chessboard preprinted on it. Your job is to write a program to preprint these pieces of paper. The chessboard is an eight-by-eight pattern of squares that alternate between black and white, with the upper left square being white. You need to print out squares of light characters(spaces)and dark characters(such as *)in this pattern to form the chessboard. 49

50 Chessboard Constants NameValue Function BLACK '********' Characters forming one line of a black square WHITE ' ' Characters forming one line of a white square Variables Name Data Type Description whiterow string A row beginning with a white square blackrow string A row beginning with a black square 50

51 Algorithm Repeat four times Output five whiterows Output five blackrows 51

52 C++ Program //***************************************************** // Chessboard program // This program prints a chessboard pattern that is // built up from basic strings of white and black // characters. //***************************************************** #include <iostream> #include <string> using namespace std; const string BLACK = "********"; // Define black square line const string WHITE = " "; // Define white square line 52

53 C++ Program int main() { string whiterow; // White square beginning row string blackrow; // Black square beginning row // Create a white-black row whiterow = WHITE + BLACK + WHITE + BLACK + WHITE + BLACK + WHITE + BLACK; // Create a black-white row blackrow = BLACK + WHITE + BLACK + WHITE + BLACK + WHITE + BLACK + WHITE; 53

54 C++ Program } // Print five white-black rows cout << whiterow << endl; cout << whiterow << endl; cout << whiterow << endl; cout << whiterow << endl; cout << whiterow << endl; // Print five black-white rows cout << blackrow << endl; cout << blackrow << endl; cout << blackrow << endl; cout << blackrow << endl; cout << blackrow << endl; // Print rest of the rows... return 0; 54

Chapter 2. C++ Syntax and Semantics, and the Program Development Process. Dale/Weems 1

Chapter 2. C++ Syntax and Semantics, and the Program Development Process. Dale/Weems 1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems 1 Chapter 2 Topics Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables

More information

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

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

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

- Developed by Bjarne Stroustrup at AT&T Bell Laboratories

- Developed by Bjarne Stroustrup at AT&T Bell Laboratories Background 1 C++ is based on C; in fact, C is almost a subset of C++ - Developed by Bjarne Stroustrup at AT&T Bell Laboratories Standard C++ - Was formally adopted by American National Standards Institute

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

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

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018 C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing

More information

LECTURE 02 INTRODUCTION TO C++

LECTURE 02 INTRODUCTION TO C++ PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

Creating a C++ Program

Creating a C++ Program Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer. 1 Creating a C++ Program created using an

More information

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

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program? Intro to Programming & C++ Unit 1 Sections 1.1-4 and 2.1-10, 2.12-13, 2.15-17 CS 1428 Spring 2019 Jill Seaman 1.1 Why Program? Computer programmable machine designed to follow instructions Program a set

More information

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

Lab # 02. Basic Elements of C++ _ Part1 Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

III. Check if the divisors add up to the number. Now we may consider each of these tasks separately, assuming the others will be taken care of

III. Check if the divisors add up to the number. Now we may consider each of these tasks separately, assuming the others will be taken care of Top-Down Design 1 Top-Down Design: A solution method where the problem is broken down into smaller sub-problems, which in turn are broken down into smaller subproblems, continuing until each sub-problem

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

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

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space. Chapter 2: Problem Solving Using C++ TRUE/FALSE 1. Modular programs are easier to develop, correct, and modify than programs constructed in some other manner. ANS: T PTS: 1 REF: 45 2. One important requirement

More information

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

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

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

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols. 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

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

More information

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

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc. Week 1: Introduction to C++ Gaddis: Chapter 2 (excluding 2.1, 2.11, 2.14) CS 1428 Fall 2014 Jill Seaman Literals A literal represents a constant value used in a program statement. Numbers: 0, 34, 3.14159,

More information

CSc Introduction to Computing

CSc Introduction to Computing CSc 10200 Introduction to Computing Lecture 2 Edgardo Molina Fall 2011 - City College of New York Thursday, September 1, 2011 Introduction to C++ Modular program: A program consisting of interrelated segments

More information

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

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

Chapter 2 C++ Fundamentals

Chapter 2 C++ Fundamentals Chapter 2 C++ Fundamentals 3rd Edition Computing Fundamentals with C++ Rick Mercer Franklin, Beedle & Associates Goals Reuse existing code in your programs with #include Obtain input data from the user

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

Lecture 2 Tao Wang 1

Lecture 2 Tao Wang 1 Lecture 2 Tao Wang 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common programming errors

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

Variables and numeric types

Variables and numeric types s s and numeric types Comp Sci 1570 to C++ types Outline s types 1 2 s 3 4 types 5 6 Outline s types 1 2 s 3 4 types 5 6 s types Most programs need to manipulate data: input values, output values, store

More information

BTE2313. Chapter 2: Introduction to C++ Programming

BTE2313. Chapter 2: Introduction to C++ Programming For updated version, please click on http://ocw.ump.edu.my BTE2313 Chapter 2: Introduction to C++ Programming by Sulastri Abdul Manap Faculty of Engineering Technology sulastri@ump.edu.my Objectives In

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

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

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING KEY CONCEPTS COMP 10 EXPLORING COMPUTER SCIENCE Lecture 2 Variables, Types, and Programs Problem Definition of task to be performed (by a computer) Algorithm A particular sequence of steps that will solve

More information

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

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program Overview - General Data Types - Categories of Words - The Three S s - Define Before Use - End of Statement - My First Program a description of data, defining a set of valid values and operations List of

More information

DEPARTMENT OF MATHS, MJ COLLEGE

DEPARTMENT OF MATHS, MJ COLLEGE T. Y. B.Sc. Mathematics MTH- 356 (A) : Programming in C Unit 1 : Basic Concepts Syllabus : Introduction, Character set, C token, Keywords, Constants, Variables, Data types, Symbolic constants, Over flow,

More information

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

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

REVIEW. The C++ Programming Language. CS 151 Review #2

REVIEW. The C++ Programming Language. CS 151 Review #2 REVIEW The C++ Programming Language Computer programming courses generally concentrate on program design that can be applied to any number of programming languages on the market. It is imperative, however,

More information

A First Program - Greeting.cpp

A First Program - Greeting.cpp C++ Basics A First Program - Greeting.cpp Preprocessor directives Function named main() indicates start of program // Program: Display greetings #include using namespace std; int main() { cout

More information

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

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

UNIT-2 Introduction to C++

UNIT-2 Introduction to C++ UNIT-2 Introduction to C++ C++ CHARACTER SET Character set is asset of valid characters that a language can recognize. A character can represents any letter, digit, or any other sign. Following are some

More information

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

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

Fundamentals of Programming CS-110. Lecture 2

Fundamentals of Programming CS-110. Lecture 2 Fundamentals of Programming CS-110 Lecture 2 Last Lab // Example program #include using namespace std; int main() { cout

More information

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Second week Variables Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable.

More information

Introduction to Programming EC-105. Lecture 2

Introduction to Programming EC-105. Lecture 2 Introduction to Programming EC-105 Lecture 2 Input and Output A data stream is a sequence of data - Typically in the form of characters or numbers An input stream is data for the program to use - Typically

More information

UEE1302 (1102) F10: Introduction to Computers and Programming

UEE1302 (1102) F10: Introduction to Computers and Programming Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,

More information

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

PART I.   Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++. Unit - III CHAPTER - 9 INTRODUCTION TO C++ Choose the correct answer. PART I 1. Who developed C++? (a) Charles Babbage (b) Bjarne Stroustrup (c) Bill Gates (d) Sundar Pichai 2. What was the original name

More information

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

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char Week 1 Operators, Data Types & I/O Gaddis: Chapters 1, 2, 3 CS 5301 Fall 2016 Jill Seaman Programming A program is a set of instructions that the computer follows to perform a task It must be translated

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

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

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9 Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

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

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ 10 Stacks of Coins You have 10 stacks with 10 coins each that look and feel

More information

Chapter 2: Overview of C++

Chapter 2: Overview of C++ Chapter 2: Overview of C++ Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman C++ Background Introduced by Bjarne Stroustrup of AT&T s Bell Laboratories in

More information

Types, Values, Variables & Assignment. EECS 211 Winter 2018

Types, Values, Variables & Assignment. EECS 211 Winter 2018 Types, Values, Variables & Assignment EECS 211 Winter 2018 2 Road map Strings and string I/O Integers and integer I/O Types and objects * Type safety * Not as in object orientation we ll get to that much

More information

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

1. In C++, reserved words are the same as predefined identifiers. a. True C++ Programming From Problem Analysis to Program Design 8th Edition Malik TEST BANK Full clear download (no formatting errors) at: https://testbankreal.com/download/c-programming-problem-analysis-program-design-8thedition-malik-test-bank/

More information

Exercise: Inventing Language

Exercise: Inventing Language Memory Computers get their powerful flexibility from the ability to store and retrieve data Data is stored in main memory, also known as Random Access Memory (RAM) Exercise: Inventing Language Get a separate

More information

Programming in C++ 4. The lexical basis of C++

Programming in C++ 4. The lexical basis of C++ Programming in C++ 4. The lexical basis of C++! Characters and tokens! Permissible characters! Comments & white spaces! Identifiers! Keywords! Constants! Operators! Summary 1 Characters and tokens A C++

More information

Exercise: Using Numbers

Exercise: Using Numbers Exercise: Using Numbers Problem: You are a spy going into an evil party to find the super-secret code phrase (made up of letters and spaces), which you will immediately send via text message to your team

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

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

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

C Language, Token, Keywords, Constant, variable

C Language, Token, Keywords, Constant, variable C Language, Token, Keywords, Constant, variable A language written by Brian Kernighan and Dennis Ritchie. This was to be the language that UNIX was written in to become the first "portable" language. C

More information

CHAPTER 3 BASIC INSTRUCTION OF C++

CHAPTER 3 BASIC INSTRUCTION OF C++ CHAPTER 3 BASIC INSTRUCTION OF C++ MOHD HATTA BIN HJ MOHAMED ALI Computer programming (BFC 20802) Subtopics 2 Parts of a C++ Program Classes and Objects The #include Directive Variables and Literals Identifiers

More information

Review of Important Topics in CS1600. Functions Arrays C-strings

Review of Important Topics in CS1600. Functions Arrays C-strings Review of Important Topics in CS1600 Functions Arrays C-strings Array Basics Arrays An array is used to process a collection of data of the same type Examples: A list of names A list of temperatures Why

More information

Input And Output of C++

Input And Output of C++ Input And Output of C++ Input And Output of C++ Seperating Lines of Output New lines in output Recall: "\n" "newline" A second method: object endl Examples: cout

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

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

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 1 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 variables. Apply C++ syntax rules to declare variables, initialize

More information

Differentiate Between Keywords and Identifiers

Differentiate Between Keywords and Identifiers History of C? Why we use C programming language Martin Richards developed a high-level computer language called BCPL in the year 1967. The intention was to develop a language for writing an operating system(os)

More information

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Unit 3. Constants and Expressions

Unit 3. Constants and Expressions 1 Unit 3 Constants and Expressions 2 Review C Integer Data Types Integer Types (signed by default unsigned with optional leading keyword) C Type Bytes Bits Signed Range Unsigned Range [unsigned] char 1

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 1 Monday, February 13, 2017 Total - 100 Points B Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 1 Monday, February 13, 2017 Total - 100 Points A Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

More information

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words. , ean, arithmetic s s on acters Comp Sci 1570 Introduction to C++ Outline s s on acters 1 2 3 4 s s on acters Outline s s on acters 1 2 3 4 s s on acters ASCII s s on acters ASCII s s on acters Type: acter

More information

CSCI 123 Introduction to Programming Concepts in C++

CSCI 123 Introduction to Programming Concepts in C++ CSCI 123 Introduction to Programming Concepts in C++ Brad Rippe C++ Basics C++ layout Include directive #include using namespace std; int main() { } statement1; statement; return 0; Every program

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,

More information

CSCI 1061U Programming Workshop 2. C++ Basics

CSCI 1061U Programming Workshop 2. C++ Basics CSCI 1061U Programming Workshop 2 C++ Basics 1 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output

More information

Chapter 8 - Notes User-Defined Simple Data Types, Namespaces, and the string Type

Chapter 8 - Notes User-Defined Simple Data Types, Namespaces, and the string Type Chapter 8 - Notes User-Defined Simple Data Types, Namespaces, and the string Type I. Enumeration Type A. Data Type: A set of values together with a set of operations on those values. 1. C++ provides the

More information

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program Syntax What the Compiler needs to understand your program 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line Possibly replacing it with other

More information

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

Syntax and Variables

Syntax and Variables Syntax and Variables What the Compiler needs to understand your program, and managing data 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line

More information

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

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

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

Your first C++ program

Your first C++ program Your first C++ program #include using namespace std; int main () cout

More information

Exercise 1.1 Hello world

Exercise 1.1 Hello world Exercise 1.1 Hello world The goal of this exercise is to verify that computer and compiler setup are functioning correctly. To verify that your setup runs fine, compile and run the hello world example

More information

8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017

8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017 8. The C++ language, 1 Programming and Algorithms II Degree in Bioinformatics Fall 2017 Hello world #include using namespace std; int main() { } cout

More information

Chapter 3. Numeric Types, Expressions, and Output

Chapter 3. Numeric Types, Expressions, and Output Chapter 3 Numeric Types, Expressions, and Output 1 Chapter 3 Topics Constants of Type int and float Evaluating Arithmetic Expressions Implicit Type Coercion and Explicit Type Conversion Calling a Value-Returning

More information

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski) THE INTEGER DATA TYPES STORAGE OF INTEGER TYPES IN MEMORY All data types are stored in binary in memory. The type that you give a value indicates to the machine what encoding to use to store the data in

More information

VARIABLES AND CONSTANTS

VARIABLES AND CONSTANTS UNIT 3 Structure VARIABLES AND CONSTANTS Variables and Constants 3.0 Introduction 3.1 Objectives 3.2 Character Set 3.3 Identifiers and Keywords 3.3.1 Rules for Forming Identifiers 3.3.2 Keywords 3.4 Data

More information

Integer Data Types. Data Type. Data Types. int, short int, long int

Integer Data Types. Data Type. Data Types. int, short int, long int Data Types Variables are classified according to their data type. The data type determines the kind of information that may be stored in the variable. A data type is a set of values. Generally two main

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1 300580 Programming Fundamentals 3 With C++ Variable Declaration, Evaluation and Assignment 1 Today s Topics Variable declaration Assignment to variables Typecasting Counting Mathematical functions Keyboard

More information

Chapter 2. Outline. Simple C++ Programs

Chapter 2. Outline. Simple C++ Programs Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.

More information