C++ Programming Basics

Similar documents
UNIT- 3 Introduction to C++

OBJECT ORIENTED PROGRAMMING

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

The C++ Language. Arizona State University 1

Chapter 2: Introduction to C++

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

Work relative to other classes

Introduction to Programming

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

LECTURE 02 INTRODUCTION TO C++

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

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

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

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

A First Program - Greeting.cpp

Chapter 1 Introduction to Computers and C++ Programming

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

Computer Programming : C++

2 nd Week Lecture Notes

Lecture 2 Tao Wang 1

Objectives. In this chapter, you will:

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

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

Basic Types, Variables, Literals, Constants

Fundamental of Programming (C)

BITG 1233: Introduction to C++

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

Programming. C++ Basics

6.096 Introduction to C++ January (IAP) 2009

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

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

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

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

XC Specification. 1 Lexical Conventions. 1.1 Tokens. The specification given in this document describes version 1.0 of XC.

Visual C# Instructor s Manual Table of Contents

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Maciej Sobieraj. Lecture 1

A Fast Review of C Essentials Part I

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

CSC 1107: Structured Programming

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

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

Chapter 12 Variables and Operators

EEE145 Computer Programming

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

Creating a C++ Program

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

JAVA Programming Fundamentals

Fundamentals of Programming

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

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

Chapter 2 Basic Elements of C++

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

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Chapter 2: Overview of C++

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

Informatics Ingeniería en Electrónica y Automática Industrial

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Homework #3 CS2255 Fall 2012

Programming with C++ as a Second Language

Chapter 12 Variables and Operators

Information Science 1

Computer Skills (2) for Science and Engineering Students

Full file at

Basics of Java Programming

Reserved Words and Identifiers

Chapter 2. Outline. Simple C++ Programs

Chapter 2 - Introduction to C Programming

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

Computer System and programming in C

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

UEE1302 (1102) F10: Introduction to Computers and Programming

UNIT-2 Introduction to C++

C: How to Program. Week /Mar/05

Chapter 2. C++ Basics

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

DEPARTMENT OF MATHS, MJ COLLEGE

ME 461 C review Session Fall 2009 S. Keres

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

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

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Chapter 12 Variables and Operators

Tutorial-2a: First steps with C++ programming

CSCE 110 PROGRAMMING FUNDAMENTALS

CSI33 Data Structures

CSCI 1061U Programming Workshop 2. C++ Basics

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

Computers Programming Course 5. Iulian Năstac

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Introduction to C# Applications

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

Professor Peter Cheung EEE, Imperial College

I Internal Examination Sept Class: - BCA I Subject: - Principles of Programming Lang. (BCA 104) MM: 40 Set: A Time: 1 ½ Hrs.

Introduction to C++ Introduction and History. Characteristics of C++

CHAPTER 3 BASIC INSTRUCTION OF C++

CSc Introduction to Computing

C Programming Language (Chapter 2 of K&R) Variables and Constants

Transcription:

C++ Programming Basics Chapter 2 and pp. 634-640 Copyright 1998-2011 Delroy A. Brinkerhoff. All Rights Reserved. CS 1410 Chapter 2 Slide 1 of 25

Program Components Function main P Every C/C++ program has exactly one function named main < main is not a keyword but should be treated as if it was < main is where the (apparent) program execution begins (it is called by the system) PFunctions have 4 parts < Name < Return value type < Argument list < Body { } int main ( ) body (a block ) return value type name argument list header CS 1410 Chapter 2 Slide 2 of 25

Pre-Opened Console Files Pre-opened I/O files available to Console-mode programs PInput < cin >> var; POutput < cout << exp; P Error reporting < cerr << exp; Pcin, cout, and cerr are library objects keyboard standard in stdin cin program screen standard error stderr cerr screen standard out stdout cout CS 1410 Chapter 2 Slide 3 of 25

The C/C++ Preprocessor Simple text manipulation P Traditionally, a program (cpp) that ran before the compiler < Functionality may be merged with modern compilers (-E terminates compilation after preprocessing a file) < Performs textual replacement before compilation begins P Processes directives that begin with # < #include <iostream> < and > indicate system header files (located in the include directory) < #include myprog.h " and " indicate program header files located in the current directory < #define line_length 100 nemonic for magic numbers and strings consistency (one place for change) CS 1410 Chapter 2 Slide 4 of 25

The Preprocessor In Action Substitutes and copies text #define SIZE 100 other stuff preprocessor iostream stuff compiler prog.h other stuff #include <iostream> #include "prog.h" using namespace std; void main( ) { cout << SIZE; } prog.cpp iostream void main( ) { cout << 100; } temporary file CS 1410 Chapter 2 Slide 5 of 25

Compiling Programs Multi-file programs source code compiler object files libraries editor linker executable runtime.cpp.c CS 1410 Chapter 2 Slide 6 of 25.obj.o

Basic Data Types Type Specifiers PData types < void 0 bytes no value < char 1 byte -128 to 127 or 0 to 255 < short 2 bytes -32,767 to 32,767 < int 2 to 4 bytes -2,147,483,648 to 2,147,483,647 < long 4 bytes -2,147,483,648 to 2,147,483,647 < bool int false / true < float 4 bytes ±3.4028234 10 ±38 (6-7 sig digs) < double 8 bytes ±1.79769313486231570 10 ±308 (~15 sd) < long double 16 bytes not universally supported P Ambiguities < The size of an int is the machine s word size < The only garentee is short # int # long < char is signed on some machines and unsigned on others P Most compilers use IEEE format for floating point numbers CS 1410 Chapter 2 Slide 7 of 25

Definitions and Declarations Important vocabulary terms P Definitions allocate memory < Variables: int counter; < Functions: double sqrt(double x) {... } P Declarations introduce a name, identifier, or symbol to the compiler (the name is placed in the compiler s symbol table) < Variables: extern int counter; < Functions: double sqrt(double x); // in <cmath> PA definition may also serve as a declaration CS 1410 Chapter 2 Slide 8 of 25

Type Conversions Implicit and Explicit Pchars and ints convert back and forth P Small types automatically promoted to large types in arithmetic expressions PIf a and b are ints, a/b is an int (truncates if necessary) P Explicit conversions are called type casts: (type)expression < Required to convert from a large type to a small type and to force conversions for / < int i = (int) 3.14159; // always truncates < int i = (int)(3.14159 + 2.7); < unsigned int i = (unsigned int) 75; < double x = (double) 1 / 3; CS 1410 Chapter 2 Slide 9 of 25

Identifier Names (i.e., Symbols) Variables, functions, structures, classes, etc. PRules < May be any length < Are case sensitive < Must begin with a letter, which includes an underscore (_) < Subsequent characters may be letters, digits, and underscores < Cannot be a keyword < May only be defined once in a scope < Should avoid library names < Must be declared before use < Must be defined exactly once CS 1410 Chapter 2 Slide 10 of 25

Expression and Statement Overview The Building Blocks - vocabulary terms P C++ is an imparative language PExpressions produce a value < Constant < Variable < Function call (returning a value not void) < Grouping of the above combined with operators < Form r-values (allowed on the RHS =): y + z or sqrt(y) or n > 100 PStatements form a complete unit of work are instructions < Are terminated with a semicolon (;) < May span lines or may be more than one on a line < Function call (not returning a value or value ignored) < Assignment statements: x = y + z; or p = sqrt(y); < Compound (or block) statements are formed of simple statements between { and } (block is not terminated with a semicolon) CS 1410 Chapter 2 Slide 11 of 25

Variables Name a region of memory where data is stored PMust be defined before use: includes data type and name P Names are case sensitive PExamples (definition and initialization) < int dollars; < int quarters, dimes, nickels, pennies; < int money = 217; < double x, pi = 3.14159; < char begin = 'A', end = 'Z', newline = '\n'; int i; i undefined 0x0a000010 i is unitialized i = 10; i 10 0x0a000010 i is 10 CS 1410 Chapter 2 Slide 12 of 25

Variables: Address vs Content Address is intrinsic, content may change PA left value (aka l-value) < is a value that can be on the left hand side of = < is the address of a variable PA right value (aka r-value) < is a value that can be on the right hand side of = < can be any valid expression i = // i represents the address of i (l-value or 0xffffff00) = i // i represents the content of i (r-value or 73) i 73 0xffffff00 CS 1410 Chapter 2 Slide 13 of 25

Variable Modifiers C/C++ Keywords P signed P unsigned P long P short Pauto Pstatic little used- turns unsigned char into signed char (the signedness of char is machine and/or implementation defined) no negative values (doubles the magnitude; often used with bit-manipulation operators; unsigned arithmetic does not overflow) long int is usually just called long short int is usually just called short never used except to illustrate that it can be used (i.e., auto is the default access specifier) local static variables maintain values between function invocation CS 1410 Chapter 2 Slide 14 of 25

Constants Types and Examples Pchar 'x' // single quote is a char P String "x" // double quote is a string P String "Hello World" Pint < Decimal 100-100 < unsigned int 123U < long int 10000000L < Octal 0377 unsigned only < Hexadecimal 0xff 0xFF unsigned only P float/double 3.13159 0.1 1.0.1 1. -6.68e-24 P long double 2.74e145L // uncommon P Explicit float 123.456F CS 1410 Chapter 2 Slide 15 of 25

Special Character Constants Backslash Characters P Digraphs represent a single character P\n new line P\t horizontal tab P\0 null (terminates strings) P\b back space P\f form feed P\r carriage return P\a alert (i.e., bell) P\" double quote P\' single quote P\\ backslash P\ddd octal number P\xff hexadecimal number P"Hello\tWorld\n" < The compiler automatically places a \0 after the \n CS 1410 Chapter 2 Slide 16 of 25

Operators Precedence and Associativity Operator [ ]., -> (dot and arrow) ( ) ++, --! ~ +, - ( ) & * sizeof Description indexing member selectio n function invocation auto increment and decrement logical negation bitwise complement unary grouping and casting address off indirection or dereference size of variable or type *, /, % multiplication, division, modulo º CS 1410 Chapter 2 Slide 17 of 25 Assoc º º º»»»»»»»»

Operators Continued +, - addition and subtraction º << >> bitwise left shift bitwise right shift (sign extend) <, >, <=, >= logical relationships º ==,!= logical equality or inequality º & bitwise and º ^ bitwise exclusive-or º bitwise or º && logical and º logical or º?: conditional expression º =, +=, -=, *=, /=, %=, <<=, >>=, &=, =, ^= operation and assignment (target must be a variable or l-value) CS 1410 Chapter 2 Slide 18 of 25 º º»

Operator Examples Unusual operators P Multiple assignment (i.e., the = operator returns a value) < i = j = k = 0; /* equivalent to i = (j = (k = 0)) */ < while ((c = getc( ))!= -1) P Auto increment and decrement < Target must be a variable (i.e., an l-value) < int i, j =10; < i = j++; /* i is 10, j is 11 */ < i = ++j; /* i is 11, j is 11 */ < i = j--; /* i is 10, j is 9 */ < i = --j; /* i is 9, j is 9 */ < i++, ++i, i--, and --i are legal (i.e., assignment is not required) < May be embedded in expressions < Often used in array indexes CS 1410 Chapter 2 Slide 19 of 25

Auto Increment / Decrement Understanding the shortcuts x = 10; Operator Meaning Result a = x++; a = x; a == 10 x = x + 1; x == 11 a = ++x; x = x + 1; a == 11 a = x; x == 11 a = x--; a = x; a == 10 x = x - 1; x == 9 a = --x; x = x - 1; a == 9 a = x; x == 9 CS 1410 Chapter 2 Slide 20 of 25

Operation with Assignment More unusual operators Pop= (+=, -=, *=, /=, %=, ~=, <<=, >>=) < variable op= expression; ø variable = variable op expression; < x += 10; ø x = x + 10; < i -= 2; ø i = i -2; < a /= b; ø a = a / b; < index %= size; ø index = index % size; < mask <<= 2; ø mask = mask << 2; CS 1410 Chapter 2 Slide 21 of 25

Comments Program documentation PC < /* comments go here */ < Can span lines PC++ < /* can use C style comments */ < // comments to the end of the line < Styles can be nested < I use C++ style and save C style to temporarily comment out code /* This style works well for large * commentary before functions */ // Function descriptions can // also be presented in this style /* void func( ) { a = b + c: } */ // comment CS 1410 Chapter 2 Slide 22 of 25

Test Cases and Program Validation The first step in test driven programming PA test case consists of at least two values: < Input value < Correct output value for the input < Long calculations may require one or more intermediate values PA set of test cases tests the behavior of the program with < Correct input < Incorrect input < Boundary values if appropriate Boundary values are on the boundary between correct and incorrect Many errors occur near or on boundary values double c = 5.0 / 9.0 * (f - 32); test cases: input: 32; output 0 input: 30; output: -1.111111 input: 212; output 100 input: 213; output: 100.555556 CS 1410 Chapter 2 Slide 23 of 25

Test Driven Programming AKA Test Driven Development PUnit tests < Are often but not always automated < They test the functionality of individual parts of a system PA unit test is a set of test cases P When practicing test driven programming / development, programmers create the unit test before writing any code PUnder what conditions can the code fail? P Programming is finished when the programmer cannot think of and test for any more failure conditions CS 1410 Chapter 2 Slide 24 of 25

Programming Style Only one rule: MAKE IT READABLE P Compiler ignores indentation and blank lines P Long statements may span multiple lines PMultiple statements may be placed on one line P Recomendations: < One definition / declaration per line < One statement per line < Keep lines short enough that they fit on the screen or printed page < Let physical layout reflect logical construction ( pretty printing ) < Use indentation consistently (use a single editor if possible) < Use blank lines to separate code into logical units; more space for more logically separated units < Place braces ( { and } ) consistently CS 1410 Chapter 2 Slide 25 of 25