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

Similar documents
Basics of Java Programming

BITG 1233: Introduction to C++

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

Chapter 2. C++ Basics

LECTURE 02 INTRODUCTION TO C++

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

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

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

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

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

Understanding main() function Input/Output Streams

The C++ Language. Arizona State University 1

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 2: Introduction to C++

This watermark does not appear in the registered version - Slide 1

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

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

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

UNIT- 3 Introduction to C++

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

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

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

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

Programming with C++ as a Second Language

Getting started with C++ (Part 2)

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

Lecture 2 Tao Wang 1

Maciej Sobieraj. Lecture 1

Introduction to C++ (Extensions to C)

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

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++

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

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

2 nd Week Lecture Notes

CSc Introduction to Computing

Computer Programming : C++

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

Chapter 2 Basic Elements of C++

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

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

Objectives. In this chapter, you will:

UEE1302 (1102) F10: Introduction to Computers and Programming

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

6.096 Introduction to C++ January (IAP) 2009

CHAPTER 3 BASIC INSTRUCTION OF C++

Creating a C++ Program

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

Chapter 3 - Notes Input/Output

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

Programming. C++ Basics

Introduction to Programming EC-105. Lecture 2

Today. o main function. o cout object. o Allocate space for data to be used in the program. o The data can be changed

CS149: Elements of Computer Science. Fundamental C++ objects

CHAPTER-6 GETTING STARTED WITH C++

Lecture 4 Tao Wang 1

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

CSCI 1061U Programming Workshop 2. C++ Basics

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

Fundamentals of Programming CS-110. Lecture 2

A First Program - Greeting.cpp

Chapter 2. Outline. Simple C++ Programs

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

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

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

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

Full file at

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

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

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

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

Ch 1. Algorithms and Basic C++ Programming

C++ Programming Basics

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

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

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

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

Chapter 2: Overview of C++

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

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

Fundamentals of Structured Programming

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

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

BTE2313. Chapter 2: Introduction to C++ Programming

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

INTRODUCTION 1 AND REVIEW

Engineering Problem Solving with C++, Etter/Ingber

.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar..

Unit 3. Constants and Expressions

CS242 COMPUTER PROGRAMMING

Syntax and Variables

Manual. Subject Code: CS593. Computer Science and Engineering

Operations. Making Things Happen

3. Simple Types, Variables, and Constants

Your First C++ Program. September 1, 2010

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

Chapter 1 Introduction to Computers and C++ Programming

printf( Please enter another number: ); scanf( %d, &num2);

CSI33 Data Structures

Transcription:

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 a specific task. Every function body is defined inside a block. For a C++ executable, exactly one function called main() Can consist of multiple files and typically use libraries. Statement: smallest complete executable unit of a program. Declaration statement Execution statement Compound statement any set of statements enclosed in set braces { } (often called a block) Simple C++ statments end with a semi-colon. (A block does not typically need a semi-colon after it, except in special circumstances).

Libraries

Libraries Usually pre-compiled code available to the programmer to perform common tasks Compilers come with many libraries. Some are standard for all compilers, and some may be system specific. Two parts Interface: header file, which contains names and declarations of items available for use Implementation: pre-compiled definitions, or implementation code. In a separate file, location known to compiler Use the #include directive to make a library part of a program (satisfies declare-before-use rule)

Building and Running a C++ Program Starts with source code, like the first sample program Pre-processing The #include directive is an example of a pre-processor directive (anything starting with #). #include <iostream>tells the preprocessor to copy the standard I/O stream library header file into the program Compiling Syntax checking, translation of source code into object code (i.e. machine language). Not yet an executable program. Linking Puts together any object code files that make up a program, as well as attaching pre-compiled library implementation code (like the standard I/O library implementation, in this example) End result is a final target like an executable program Run it!

Typical Code Elements Comments - Ignored by the Compiler Directives - For preprocessing Literals - Hardcoded values. Eg: 10 Keywords - Words with special meaning to the compiler. Eg: int Identifiers - Names for variables, functions, etc. Operators - Symbols that perform certain operations. Eg: +

Comments Comments are for documenting programs. They are ignored by the compiler. Block style (like C) /* This is a comment. It can span multiple lines */ Line comments use the double-slash // int x; // This is a comment x = 3; // This is a comment

Data Types Atomic data types are the built-in types defined by the C++ language. bool: has two possible values, true or false integer types char - 1 byte on most systems. Typically used for representing characters Stored with an integer code underneath (ASCII on most computers today) short - (usually at least 2 bytes) int - (4 bytes on most systems) long - (usually 4 or more bytes) The integer types have regular and unsigned versions floating point types - for storage of decimal numbers (i.e. a fractional part after the decimal) float double long double

Identifiers Identifiers are the names for things (variables, functions, etc) in the language. Some identifiers are built-in, and others can be created by the programmer. User-defined identifiers can consist of letters, digits, and underscores Must start with a non-digit Identifiers are case sensitive (count and Count are different variables) Reserved words (keywords) cannot be used as identifiers

Style Conventions for Identifiers Don t re-use common identifiers from standard libraries (like cout, cin) Start names with a letter, not an underscore. System identifiers and symbols in preprocessor directives often start with the underscore. Pick meaningful identifiers self-documenting numstudents, firstname // good a, ns, fn // bad a couple common conventions for multiple word identifiers numberofmathstudents number of math students

Declaring Variables Declare Before Use: Variables must be declared before they can be used in any other statements Declaration format: typename variablename1, variablename2,...; int numstudents; double weight; char letter; // variable of type integer // variable of type double // variable of type character //Examples of multiple variables of the same type //in single declaration statements int test1, test2, finalexam; double average, gpa;

Initializing Variables To declare a variable is to tell the compiler it exists, and to reserve memory for it To initialize a variable is to load a value into it for the first time If a variable has not been initialized, it contains whatever bits are already in memory at the variable s location (i.e. a garbage value) One common way to initialize variables is with an assignment statement. Examples: int numstudents; double weight; char letter; numstudents = 10; weight = 160.35; letter = A ;

Initializing Variables Variables of built-in types can be declared and initialized on the same line, as well int numstudents = 10; double weight = 160.35; char letter = A ; int test1 = 96, test2 = 83, finalexam = 91; double x = 1.2, y = 2.4, z = 12.9;

Initializing Variables An alternate form of initializing and declaring at once: // these are equivalent to the ones above int numstudents(10); double weight(160.35); char letter( A ); int test1(96), test2(83), finalexam(91); double x(1.2), y(2.4), z(12.9);

Constants

Constants A variable can be declared to be constant. This means it cannot change once it s declared and initialized Use the keyword const MUST declare and initialize on the same line const int SIZE = 10; const double PI = 3.1415; // this one is illegal, because it s not // initialized on the same line const int LIMIT; // BAD!!! LIMIT = 20; A common convention is to name constants with all-caps (not required)

Symbolic Constants (an alternative) A symbolic constant is created with a preprocessor directive, #define. (This directive is also used to create macros). Examples: #define PI 3.14159 #define DOLLAR $ #define MAXSTUDENTS 100 The preprocessor replaces all occurrences of the symbol in code with the value following it. (like find/replace in MS Word). This happens before the actual compilation stage begins

Literals Literals are also constants. They are literal values written in code. integer literal an actual integer number written in code (4, -10, 18) If an integer literal is written with a leading 0, it s interpreted as an octal value (base 8). If an integer literal is written with a leading 0x, it s interpreted as a hexadecimal value (base 16) Example: int x = 26; // integer value 26 int y = 032; // octal 32 = decimal value 26 int z = 0x1A; // hex 1A = decimal value 26

More Literals floating point literal an actual decimal number written in code (4.5, -12.9, 5.0) These are interpreted as type double by standard C++ compilers Can also be written in exponential (scientific) notation: (3.12e5, 1.23e-10) character literal a character in single quotes: ( F, a, \n ) string literal a string in double quotes: ( Hello, Bye, Wow!\n ) boolean literals - true or false

Escape Sequences String and character literals can contain special escape sequences They represent single characters that cannot be represented with a single character from the keyboard in your code The backslash \is the indicator of an escape sequence. The backslash and the next character are together considered ONE item (one char) Some common escape sequences are listed in the table below Escape Sequence Meaning \n newline \t tab \ double quote \ single quote \\ backslash

Input and Output Streams In C++ we use do I/O with stream objects, which are tied to various input/output devices. These stream objects are predefined in the iostream library. cout standard output stream Of class type ostream (to be discussed later) Usually defaults to the monitor cin standard input stream Of class type istream (to be discussed later) Usually defaults to the keyboard cerr standard error stream Of class type ostream Usually defaults to the monitor, but allows error messages to be directed elsewhere (like a log file) than normal output

Using Streams To use these streams, we need to include the iostream library into our programs. #include <iostream> using namespace std; The using statement tells the compiler that all uses of these names (cout, cin, etc) will come from the standard namespace.

Using the Output Stream output streams are frequently used with the insertion operator << Format: outputstreamdestination <<itemtobeprinted The right side of the insertion operator can be a variable, a constant, a value, or the result of a computation or operation Examples: cout << Hello World"; // string literal cout << a ; // character literal cout <<numstudents; // contents of a variable cout <<x + y - z; // result of a computation cerr << Error occurred"; // string literal printed to standard error

Cascading Output When printing multiple items, the insertion operator can be cascaded. Cascading is placing another operator after an output item to insert a new output item. cout << Average = " <<avg << \n ; cout <<var1 << \t <<var2 << \t <<var3; We won t utilize cerr in this course. It s less common than cout esp. in intro programming, but here for completeness.

Input Streams input streams are frequently used with the extraction operator >> Format: inputstreamsource >>locationtostoredata The right side of the extraction operator MUST be a memory location. For now, this means a single variable! By default, all built-in versions of the extraction operator will ignore any leading white-space characters (spaces, tabs, newlines, etc) In case if strings, the extraction operator will keep reading until it encounters a white space character.

Examples int numstudents; cin >>numstudents; // read an integer double weight; cin >>weight; // read a double cin >> \n ; // ILLEGAL. Right side must be a variable cin >>x + y; // ILLEGAL. x + y is a computation, not a variable The extraction operator can be cascaded, as well: int x, y; double a; cin >>x >>y >>a; // read two integers and a double from input

Some special formatting for decimal numbers You will need the iomanip library for this. By default, decimal (floating-point) numbers will print in standard notation while possible, using scientific notation only when the numbers are too small or too large. Usually, cout prints out floats only as far as needed, up to a certain preset number of decimal places (before rounding the printed result). double x = 4.5, y = 12.666666666666, z = 5.0; cout <<x; // will likely print 4.5 cout <<y; // will likely print 12.6667 cout <<z; // will likely print 5

Magic Formula A special magic formula for controlling how many decimal places are printed: cout.setf(ios::fixed); //fixed point notation cout.setf(ios::showpoint); // so that decimal point will always be shown cout.precision(2); // sets floating point types to print to 2 decimal places (or use your desired number) cout.setf(ios::scientific); // float types formatted in exponential notation

Magic Formula Any cout statements following these will output floating-point values in the usual notation, to 2 decimal places. double x = 4.5, y = 12.666666666666, z = 5.0; cout <<x; // prints 4.50 cout <<y; // prints 12.67 cout <<z; // prints 5.00 These statements use what are called stream manipulators, which are symbols defined in the iostream library as shortcuts for setting those particular formatting flags

Alternate Method Here s an alternate way to set the fixed and showpoint flags cout <<fixed; // uses the "fixed" stream manipulator cout <<showpoint; // uses the "showpoint" stream manipulator cout <<setprecision(3); // uses the set precision stream manipulator (you ll need the iomanip library for this) //The above sets precision of the value to 3 numbers. You can change this value based on what you need.