Lesson 2 Variables and I/O

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

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

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

The C++ Language. Arizona State University 1

Creating a C++ Program

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

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

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

BTE2313. Chapter 2: Introduction to C++ Programming

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

Exercise: Using Numbers

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

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.

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

Unit 3. Constants and Expressions

Today in CS161. Week #3. Learn about. Writing our First Program. See example demo programs. Data types (char, int, float) Input and Output (cin, cout)

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

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Lesson 1: Hello, world! Line by line explanation

Variables and numeric types

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

CIS220 In Class/Lab 1: Due Sunday night at midnight. Submit all files through Canvas (25 pts)

Getting started with C++ (Part 2)

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

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

Lesson 3: Arithmetic & Casting. Pic 10A Ricardo Salazar

CSCI 1061U Programming Workshop 2. C++ Basics

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

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

Objectives. In this chapter, you will:

Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi Section Webpage:

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

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

Programming with C++ as a Second Language

Chapter 2: Introduction to C++

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

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

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

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

CS242 COMPUTER PROGRAMMING

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Understanding main() function Input/Output Streams

Chapter 1 INTRODUCTION

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

Chapter 2: Overview of C++

CSc Introduction to Computing

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

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

(Refer Slide Time: 00:23)

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

C++ Programming Basics

Chapter 2 Basic Elements of C++

LECTURE 02 INTRODUCTION TO C++

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

QUIZ. What are 3 differences between C and C++ const variables?

3. Simple Types, Variables, and Constants

IT 1033: Fundamentals of Programming Data types & variables

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

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

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

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment

Exercise: Inventing Language

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

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

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

Introduction to Programming EC-105. Lecture 2

Fundamentals of Structured Programming

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

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

Chapter 2. C++ Basics

EE 109 Lab 8a Conversion Experience

WARM UP LESSONS BARE BASICS

Annotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Fundamentals of Programming CS-110. Lecture 2

CS Homework 10 p. 1. CS Homework 10

A First Program - Greeting.cpp

CSCE Practice Midterm. Data Types

4. Structure of a C++ program

BITG 1233: Introduction to C++

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

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

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

Chapter 1 - What s in a program?

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

CS101 PLEDGED SPRING 2001

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

Programming. C++ Basics

CS1500 Algorithms and Data Structures for Engineering, FALL Virgil Pavlu, Jose Annunziato,

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

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

Unit 14. Passing Arrays & C++ Strings

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Full file at

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

Ch 1. Algorithms and Basic C++ Programming

How to approach a computational problem

Transcription:

Lesson 2 Variables and I/O Pic 10A Ricardo Salazar

Free form layout C++ lets you use spaces and returns (enter key) wherever you see fit. cout << 1 << 2; cout<<1 <<2; If you want a space or a new line in the output you have to code it with " " or "\n" cout << 1 << 2; cout << 1 << " " << 2; The last line of your program, namely return 0 is not necessary... but it is considered good style to have it. Think of it as saying 'Good bye' when your program ends. int main(){ cout << "Hola\n"; {

(2.1) Variables and data types A variable is a storage location with a name. Think of it as a house (physical location) where someone (one single value) lives. The value could be a number, a character (letter), or even a collection of numbers. Warning: Different types of values require different types of houses. Why is it a good idea? Suppose we want to repeat 2 times the phrase The value of n is: 2 We could try: cout << "The value of n is: 2\n"; cout << "The value of n is: 2\n"; But what if we change our mind and want n to be 3 instead? What if we repeated the phrase 100 times instead of 2?

Variables (cont) If we had the ability to write: n = 2 ; cout << "The value of n is: " << n << "\n"; cout << "The value of n is: " << n << "\n"; then instead of two changes to the code (or 100 changes) we would only need to replace the first line with: n = 3 ; Just one change ;-) But what if we want n to be 3.14? If the computer/compiler was smart it would be as simple as writing: n = 3.14 ; Unfortunately it is not that simple :-( But it can be done... we just need to tell the compiler what type of number to expect.

Data types To save memory we want use as few bits as possible to represent numbers (i.e. choose a proper size for the houses without wasting real estate). Type Description Bits* bool Boolean value (True/False) 1 char Character (letter, e.g. R) 8 (1 bytes) short Short integer 16 (2 bytes) int Integer (whole number) 32 (4 bytes) float Floating point ( real numbers, e.g. 3.14, ½) 32 (4 bytes) double Long float 64 (8 bytes) long double Very long float 128 (16 bytes) * The actual number of bits depends on the particular computer. int and float are the most commonly used types.

Declaring variables Before we can use a variable we need to specify the type of values it will hold. This is know as declaration. This action allocates (reserves) the right amount of memory for the variable based on its type. Examples: int a; double b; a = -100; b = 3.1416; Declaration and assignation can be done at the same time. int a = -100; double b = 3.1416; What is wrong with the following code? int a = 3.1416; double b = -100; Something is indeed wrong: a will only 'house' the integer 3. There is no rounding! Nothing, the compiler will let you do it (with a couple of warnings), but we are asking an eagle to live in a hummingbird's nest and vice-versa.

Variable names Some rules need to be followed when selecting the name of a variable. Cannot be a reserved word. Like cout, main or return. Must start with a letter or an underscore. E.g: Yo, c_u_l8ter, _thisisthenameofmy_favorite_variable No spaces. But underscores and 'camel notation' are OK. E.g: your_choice yourchoice Variable names are case sensitive. The following are three different variable names: Hola hola hola

Variable names (guidelines) By convention variable names always start with a lower-case letter. Classes and constants (discussed later) start with upper-case letters. Use descriptive names for your variables. Recall that your code should be readable by humans. cob vs CurrentlyOwnedBikes As a 'rule of thumb', except for counters variable names should be at least 5 characters long.

Declare variables right away because houses are always inhabited! The standard used to be to declare them at the top of a block of code. int main(){ int numberofpages=10; STATEMENTS return 0; } Introducing them right before they are needed is also possible int main(){ STATEMENTS int extrapages=2; STATEMENTS_THAT_USE_extraPages return 0; } moreover it improves readability. What is the output of the following program? #include <iostream> using namespace std; int main(){ int number; } cout << "N= " << number << "\n"; return 0; Garbage!!! Well... it is actually 0 but in very few cases this is the desired outcome.

A conversion program (How much is 8 pennies, 4 dimes and 3 quarters?) It is hard to know what the program does just by reading it. Same outcome. Yet it is easier to understand what is really going on.

Comments (Improving readability) The idea is to give some clues (e.g. what the program does, who is the author, what are the known problems, etc) that the compiler will ignore. There are 2 ways to comment your code. // This is a comment /* This is another one */ The second method can span more than one line. As a 'rule of thumb', always comment on variables and parts of your code that are complex and/or difficult to follow. It doesn't matter how long a comment is, the compiler will ignore it.

Comments (cont) The top of every source file should contain some basic information. Example: Your name The date A brief description of what it does /* ******************************************** Ricardo Salazar Jan 7, 2014 This program displays the message "Hola!" ******************************************* */ #include <iostream> using namespace std;

(2.2) Input / Output Recall that cout stands for 'console out'. There is a similar instruction in <iostream> cin = 'console in' that grabs (reads) data from the console. cin works the same way as cout but it uses >> to pull data. For example, the code int num1, num2; cout << "Type two numbers: "; cin >> num1 >> num2; cout << "The product is " << num1 * num2 << ".\n"; Produces the output Type two numbers: 5 3 The product is 15.

Be careful with the data types Always plan ahead. Think of the data types that you will request as well as the ones you could probably obtain. E.g. If you are expecting a decimal, use a double. Since the compiler doesn't know in advance what a user might input you will not get a compiler error... but you could find yourself in uncharted territory!!! int a; user inputs the decimal 1.234 cin >> a ; computer sets a=1 it assumes 0.234 is the value for the next input!!! This is known as buffered input. The 'extra' data is stored in memory until it is needed. Buffering can be very annoying (you have been warned!).

Buffering (cont) Consider the following code (assuming data types are not a problem) cout << "Enter 1st number: "; cin >> num1; cout << "Enter 2nd number: "; cin >> num2; cout << "\n1st number = " << num1 << ", 2nd number = " << num2 << ".\n"; Buffering occurs when a user gets impatient Enter 1st number: 5 9 Enter 2nd number: 1st number = 5, 2nd number = 9. The user doesn't get a chance to type a number in the second line. The assignation num2 = 9 occurs immediately.

Let's put everything together Currency conversion (the easy part)