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

Similar documents
Introduc)on to C++ CS 16: Solving Problems with Computers I Lecture #2

C++ Basics 1 CS 16: Solving Problems with Computers I Lecture #3

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

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

Chapter 2. C++ Basics

The C++ Language. Arizona State University 1

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

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

Chapter 2: Introduction to C++

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

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

Fundamentals of Programming CS-110. Lecture 2

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

LECTURE 02 INTRODUCTION TO C++

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

Lecture 3 Tao Wang 1

Creating a C++ Program

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

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

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

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

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

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

Introduction to Programming EC-105. Lecture 2

Lecture 2 Tao Wang 1

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

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

Basics of Java Programming

Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5

Unit 3. Constants and Expressions

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

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Computer Programming : C++

BITG 1233: Introduction to C++

CS242 COMPUTER PROGRAMMING

CSc Introduction to Computing

CHAPTER 3 BASIC INSTRUCTION OF C++

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

A First Program - Greeting.cpp

Welcome to Solving Problems with Computers I

UNIT- 3 Introduction to C++

Chapter 2 Basic Elements of C++

Objectives. In this chapter, you will:

Visual C# Instructor s Manual Table of Contents

Fundamental of Programming (C)

BTE2313. Chapter 2: Introduction to C++ Programming

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

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

BASIC ELEMENTS OF A COMPUTER PROGRAM

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

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

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

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

Operators. Java operators are classified into three categories:

2 nd Week Lecture Notes

Chapter 1 Introduction to Computers and C++ Programming

Flow Control in C++ Condi&onals & Loops CS 16: Solving Problems with Computers I Lecture #4

Programming with Java

File I/O CS 16: Solving Problems with Computers I Lecture #9

Connecting with Computer Science, 2e. Chapter 15 Programming II

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

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Maciej Sobieraj. Lecture 1

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Full file at

6.096 Introduction to C++ January (IAP) 2009

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Introduction to Programming

Language Reference Manual

IT 374 C# and Applications/ IT695 C# Data Structures

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

Flow Control in C++ 1 CS 16: Solving Problems with Computers I Lecture #4

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

Chapter 1 INTRODUCTION

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

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

Lesson 2 Variables and I/O

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

Chapter 3: Operators, Expressions and Type Conversion

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

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

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

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Add Subtract Multiply Divide

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

Getting started with C++ (Part 2)

Exercises with Linked Lists CS 16: Solving Problems with Computers I Lecture #15

Java Notes. 10th ICSE. Saravanan Ganesh

Chapter 17. Fundamental Concepts Expressed in JavaScript

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

CMSC 104 -Lecture 5 John Y. Park, adapted by C Grasso

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Numerical Conversions Intro to Strings in C/C++ CS 16: Solving Problems with Computers I Lecture #8

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

Transcription:

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni Dept. of Computer Science, UCSB

Administrative This class is currently FULL and the waitlist is CLOSED Will not be adding anyone else Please do not ask again Lab #1 and submit.cs issues Homework #1 and working on GauchoSpace Reminder: Don t leave your valuables behind in the lab (or class)! 4/5/18 Matni, CS16, Sp18 2

Lecture Outline Basic Rules and Conventions of C++ Variables and Assignments Data Types and Expressions Input and Output 4/5/18 Matni, CS16, Sp18 3

Note the use of tabbed spaces 1-4: Program start 5: Variable declaration 6-20: Statements 21-22: Program end cout << some string or another ; //output stream statement cin >> some_variable; //input stream statement cout and cin are objects defined in the library iostream 4/5/18 Matni, CS16, Sp18 4

What s The Difference??? #include <iostream> using namespace std; int main( ) { int n = 5; while (n < 10) { cout << n; n = n + 1; } #include <iostream> using namespace std;int main( ) {int n=5;while (n<10) {cout<<n;n=n+1;}return 0;} A compiler program can read either one! But which one can YOU read better?!?! J } return 0; 4/5/18 Matni, CS16, Sp18 5

Program Style We will check for this convention use in your lab assignments! The layout of a program is designed mainly to make it readable by humans C++ Compilers accept almost any patterns of line breaks and indentations! So layout conventions are there not for the machine, but for the human Convention vs. Rules what s the difference?? Conventions have been established, for example: 1. Place opening brace { and closing brace } on a line by themselves 2. Use indented statements (i.e. use tabbed spaces) 3. Use only one statement per line 4/5/18 Matni, CS16, Sp18 6

Some C++ Rules and Conventions Variables are declared before they are used Typically at the beginning of program Statements (not always lines) end with a semi-colon ; Breaking these rules is considered a syntax error: your program won t compile! Use curly-brackets { } to encapsulate groups of statements that belong together Parentheses ( ) have a different use in C++ As do square brackets [ ] They are not interchangeable! 4/5/18 Matni, CS16, Sp18 7

Some C++ Rules and Conventions Include directives (like #include <iostream>) are always placed in the beginning of the program before any code Tells the compiler where to find information about objects used in the program using namespace std; Tells the compiler to use names of objects in iostream in a standard way main functions end with a return 0; statement You should always have this although it s a convention, not a strict rule 4/5/18 Matni, CS16, Sp18 8

Reminder: What are Variables A variable is a symbolic reference to data The variable's name represents what information it contains They are called variables because the data can change while the operations on the variable remain the same If variables are of the same type, you can perform operations on them 4/5/18 Matni, CS16, Sp18 9

Variables in C++ In C++, variables are placeholders for memory locations in the CPU We can assign a value to them We can change that value stored BUT we cannot erase the memory location of that particular variable 4/5/18 Matni, CS16, Sp18 10

Types of C++ Variables: General There are 3 properties to a variable: Variables have a name (identifier), a type, and a value attached to them Integers Whole numbers Example: 122, 53, -47 Floating Point Numbers with decimal points Example: 122.5, 53.001, -47.201 Boolean Takes on one of two values: true or false Character A single alphanumeric Example: c, H, % Note the use of quotation marks String A string of characters Example: baby, what the!@$? Note the use of quotation marks There are many other types of variables you also make your own types! 4/5/18 Matni, CS16, Sp18 11

About Variable Names We will check for this convention use in your lab assignments! Good variable name: indicates what data is stored inside it A good variable name is a noun or noun phrase, e.g.: FirstName A good function name is a verb or verb phrase, e.g.: SortNumbers() They should make sense to a non computer programmer Avoid generic names, like var1 or x Example: name = Bob Roberts is not descriptive enough, but candidate_name = Bob Roberts is better 4/5/18 Matni, CS16, Sp18 12

Variable Name Rules in C++ Variable names in C++ must adhere to certain rules. Breaking these rules is considered a syntax error: your program won t compile! They MUST start with either a letter or an underscore (_) They cannot start with a number The rest of the letters can be alphanumerics or underscores. They cannot contain spaces or dots or other symbols Which of these is a legal variable name in C++ 4MyBae _StopCondition MyLittlePony_007 James.Bond 4/5/18 Matni, CS16, Sp18 13

Variable Name Casing We will check for this convention use in your lab assignments! When naming variables, functions, etc Snake Case: Using underscore character ( _ ) Example: mortgage_amount function_fun() Associated with C, C++ programmers Camel Case: Using upper-case letters to separate words Example: MortgageAmount FunctionFun() Associated with Java programmers For this class, YOU CAN USE EITHER! But PICK ONE AND BE CONSISTENT!!! 4/5/18 Matni, CS16, Sp18 14

Reserved Keywords Used for specific purposes by C++ Must be used as they are defined in C++ Cannot be used as identifiers Breaking these rules is considered a syntax error: your program won t compile! EXAMPLE: You cannot call a variable int or else For a list of all C++ keywords, see: http://en.cppreference.com/w/cpp/keyword 4/5/18 Matni, CS16, Sp18 15

Other Styling Conventions We will check for this convention use in your lab assignments! Comments: Must have them In C++, use // for one line at a time, or /* */ for multiple lines Tabbing and Braces: Code inside of main() must be tabbed appropriately Even one-liner if-statements Open and close curly braces { } on new lines and align them with the block 4/5/18 Matni, CS16, Sp18 16

int main() { // Get user input on number of people // Then determine if there is room for them int max_capacity(100), num_people; cout << Enter number of people: ; cin >> num_people; if (num_people > max_capacity) { cout << Too many people! By a count of ; cout << num_people max_capacity; } else { cout << Ok! ; } return 0; } Example of Good Styling

Declaring Variables before Variables in C++ must be declared they are used! Declaration syntax: Type_name Variable_1, Variable_2,... ; Examples: double average, m_score, total_score; int id_num, height, weight, age, shoesize; int points; 4/5/18 Matni, CS16, Sp18 18

Initializing/Assigning Variable Values When you declare a variable, it s not created with any value in particular It is good practice to initialize variables before using them Otherwise they will contain whatever value is in that memory location Using = or ( ) for assignment of declared values is up to you! Do not declare variables inside loops!!! EXAMPLE: int num, doz; num = 5; sum(5); doz = num + 7; num is initialized to 5 and so is sum doz is initialized to (num + 7) 4/5/18 Matni, CS16, Sp18 19

Assignment vs. Algebraic Statements C++ syntax is NOT the same as in Algebra EXAMPLE: number = number + 3 In C++, it means: take the current value of number, add 3 to it, C++ shortcut: number += 3 Also works with: -= *= /= %= etc then reassign that new value to the variable number 4/5/18 Matni, CS16, Sp18 20

Variable Comparisons When variables are being compared to one another, we use different symbols a is equal to b a == b a is not equal to b a!= b a is larger than b a > b a is larger than or equal to b a >= b a is smaller that b a < b a is smaller than or equal to b a <= b 4/5/18 Matni, CS16, Sp18 Note: The outcome of these comparisons are always either true or false i.e. Boolean Boolean variables: false = 0 true 0 (note the lower-case)

Variable Types in C++ 1. Integers int: Basic integer (whole numbers, positive OR negative) Usually 32 or 64 bits wide So, if it s 32 bits wide, the range is -2 31 to +2 31-1 Which is: -2,147,483,648 to +2,147,483,647 You can express even larger (+ve and ve) integers using: long int and long long int You can express only positive integers (and thus get a longer +ve range) using: unsigned int 4/5/18 Matni, CS16, Sp18 22

Variable Types in C++ 2. Real (rational) numbers double: Real numbers, positive OR negative Type double can be written in two ways: Simple form must include a decimal point Examples: 34.1, 23.0034, 1.0, -89.9 Alternate form: Floating Point Notation (Scientific Notation) 3.41e1 means 34.1 3.67e17 means 367000000000000000.0 (17 digits after 3 ) 5.89e-6 means 0.00000589 (6 decimal places before 5 ) Number left of e (for exponent) does not require a decimal point The exponent cannot contain a decimal point 4/5/18 Matni, CS16, Sp18 23

char: single character Variable Types in C++ 3. Characters Can be any single character from the keyboard To declare a variable of type char: char letter; Character constants are enclosed in single quotes char letter = 'a'; 4/5/18 Matni, CS16, Sp18 24

Variable Types in C++ 4. Strings string: a collection of characters (a string of characters) string is a class, different from the primitive data types discussed so far. We ll discuss classes further in the course Using C++ strings requires you to include the string module: #include <string> To declare a variable of type string: string name = Homer Simpson ; There are older types of strings called C-Strings that are still in use in C++ More on those later 4/5/18 Matni, CS16, Sp18 25

Note on vs Single quotes are only used for char types Double quotes are only used for string types So, which of these is ok and which isn t? char letter1 = a ; char letter2 = b ; string town1 = Mayberry ; string town2 = Xanadu ; 4/5/18 Matni, CS16, Sp18 26

Type Compatibilities General Rule: You cannot operate on differently typed variables. Except with int and double types Just like in most computer languages So, if: then: int my_var = 2; my_var + my_char is a syntax error char my_char = x ; There are rules with operations between int and double 4/5/18 Matni, CS16, Sp18 27

int ßà double Variables of type double should not be assigned to variables of type int Variable of type int, however, can normally be stored in variables of type double EXAMPLE: double numero; numero = 2; numero will contain 2.0000 (unfixed number of places after decimal pt) EXAMPLE: int numero; numero = 2.789; numero will contain 2 4/5/18 Matni, CS16, Sp18 28

So, what happens with variable z here? int x(9); double y(4), z; z = x / y; cout << z; This prints out: 2.25 If one or both operands are double, the result is double int ßà double So, what happens with variable p here? int n(4); double m(9), p; p = m / n; cout << p; This prints out: 2.25 So, what happens with variable c here? int a(9), b(4); double c; c = a / b; cout << c; This prints out: 2 4/5/18 Matni, CS16, Sp18 29

Variable Types in C++ 5. Booleans bool: a binary value of either true (1) or false (0). You can perform LOGICAL operations on this type: Logical OR && Logical AND Also, when doing comparisons, the result is a Boolean type. EXAMPLE: What will this print out?? int a = 44, b = 9; bool c; c = (a == b); cout << c; Ans: 0 4/5/18 Matni, CS16, Sp18 30

Arithmetic Expressions Precedence rules for operators are the same as what you used in your algebra classes EXAMPLE: x + y * z ( y is multiplied by z first) Use parentheses to force the order of operations (recommended) EXAMPLE: (x + y) * z ( x and y are added first) 4/5/18 Matni, CS16, Sp18 31

Operator Shorthands Some expressions occur so often that C++ contains shorthand operators for them All arithmetic operators can be used this way: count = count + 2; ---can be written as--- count += 2; bonus = bonus * 2; ---can be written as--- bonus *= 2; time = time / factor; ---can be written as--- time /= factor; remainder = remainder % (cnt1+ cnt2); ---can be written as--- remainder %= (cnt1 + cnt2); 4/5/18 Matni, CS16, Sp18 32

AND operator && Review of Boolean Expressions: AND, OR, NOT (expression 1) && (expression 2) True if both expressions are true OR operator (expression 1) (expression 2) True if either expression is true Note: no space between each character! NOT operator!!(expression) False, if the expression is True (and vice versa)

Truth Tables for Boolean Operations X Y X && Y F F F T T F T T AND OR NOT F F F T X Y X Y F F F T T F T T F T T T X! X F T T F IMPORTANT NOTES: 1. AND and OR are not opposites of each other!! 2. AND: if just one condition is false, then the outcome is false 3. OR: if at least one condition is true, then the outcome is true 4. AND and OR are commutative, but not when mixed (so, order matters) X && Y = Y && X X && (Y Z) is not the same as (X && Y) Z 4/5/18 Matni, CS16, Sp18 34

Precedence Rules on Operations in C++ If parenthesis are omitted from C++ expressions, the default precedence of operations is: 4/5/18 Matni, CS16, Sp18 35

q Finish Lab1 by Monday q Do HW2 by Tuesday YOUR TO-DOs q Visit Prof s and TAs office hours if you need help! Ø Prof. s hours are MONDAY from 11 AM to 12 PM (or by appointment!) q Reverse global warming q Bonus points for ending world hunger 4/6/18 Matni, CS16, Sp18 36

4/6/18 Matni, CS16, Sp18 37