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

Similar documents
UEE1302 (1102) F10: Introduction to Computers and Programming

CSc Introduction to Computing

Fundamentals of Programming

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.

CS242 COMPUTER PROGRAMMING

Fundamental of Programming (C)

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

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

The C++ Language. Arizona State University 1

6.096 Introduction to C++ January (IAP) 2009

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

3.1. Chapter 3: The cin Object. Expressions and Interactivity

UNIT- 3 Introduction to C++

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

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

BITG 1233: Introduction to C++

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

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

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

Programming. C++ Basics

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

A First Program - Greeting.cpp

CSCE 110 PROGRAMMING FUNDAMENTALS

Lecture 2 Tao Wang 1

Engineering Problem Solving with C++, Etter/Ingber

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Objectives. In this chapter, you will:

A SHORT COURSE ON C++

Introduction to Programming

Expressions, Input, Output and Data Type Conversions

Lecture 4 Tao Wang 1

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

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

Variables. Data Types.

EEE145 Computer Programming

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

Operations. Making Things Happen

Introduction to C++ Systems 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

Chapter-8 DATA TYPES. Introduction. Variable:

DEPARTMENT OF MATHS, MJ COLLEGE

Chapter 2 C++ Fundamentals

Creating a C++ Program

A Fast Review of C Essentials Part I

LECTURE 02 INTRODUCTION TO C++

Variables in C. CMSC 104, Spring 2014 Christopher S. Marron. (thanks to John Park for slides) Tuesday, February 18, 14

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

Introduction to Programming EC-105. Lecture 2

Fundamentals of Programming CS-110. Lecture 2

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

Chapter 2. Outline. Simple C++ Programs

Input and Expressions Chapter 3 Slides #4

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Topic 2: C++ Programming fundamentals

C Programming

VARIABLES & ASSIGNMENTS

Programming and Data Structures

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

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

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

Input And Output of C++

Chapter 15 - C++ As A "Better C"

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

UNIT-2 Introduction to C++

BLM2031 Structured Programming. Zeyneb KURT

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

Computer Programming : C++

Lecture 3 Tao Wang 1

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.

Chapter 2 - Introduction to C Programming

Tokens, Expressions and Control Structures

COMP322 - Introduction to C++

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

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

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

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.

Chapter 7 - Notes User-Defined Functions II

C: How to Program. Week /Mar/05

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

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

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Chapter 2: Introduction to C++

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

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

Chapter 3. Numeric Types, Expressions, and Output

Basic Elements of C. Staff Incharge: S.Sasirekha

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

Programming with C++ as a Second Language

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

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

Chapter 2 Basic Elements of C++

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

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

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

CS201 - Introduction to Programming Glossary By

Programming Language. Functions. Eng. Anis Nazer First Semester

Chapter 1 & 2 Introduction to C Language

Chapter 2 - Control Structures

Transcription:

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 input Constant variables 2

Variables Symbolic names used in place of memory addresses Symbolic names are called variables These variables refer to memory locations The value stored in the variable can be changed Simplifies programming effort 3

Variable Declarations All variables must be declared before being used Declaration tells the data type of a variable so that a compiler can Allocate suitable memory space for the variable Check for program syntax errors in terms of data type compatibility 4

Declaration Statement Names a variable, specifies its data type General form: datatype variablename; e.g. int sum; declares sum as variable which stores an integer value Declaration statements can be placed anywhere in function Typically grouped together and placed immediately after the function s opening brace 5

Identifier Naming Conventions A variable in C++ must begin with a letter or underscore must consist of letters, digits, or underscore can be of any length cannot be a C++ reserved word (see next slide) use meaningful names, e.g. incometax start all (variable, function) names with lowercase letter C++ is case sensitive! 6

C++ Key Words Not to be used as variable names char, int, short, long, float, double, enum, void, signed, unsigned, const if, else, switch, case, default, while, for, do, break, continue, goto sizeof, return, typedef, auto, static new, delete, struct, union, class, private, public, protected, friend More, see Table 1.1 in textbook 7

Examples of Variable Names Examples of valid identifiers: grosspay taxcalc addnums degtorad multbytwo salestax netpay bessel Examples of invalid identifiers: 4ab3 (begins with a number) e*6 (contains a special character) while (is a keyword) 8

Example #include<iostream> using namespace std; int main( ) { char ch; // declares a character variable ch = 'a'; // stores the letter a into ch cout << "The character stored in ch is " << ch << endl; ch = 'm'; // now stores new letter m into ch cout << "The character now stored in ch is " << ch << endl; return 0; } 9

Implication of a Declaration Tells compiler to Reserve enough room for an integer number int total; 4 Physical storage bytes Tells compiler to tag the reserved storage with the name total 10

Declaration with Initialisation Tells compiler to int total=12; Byte of lower address Reserve enough room for an integer number 12 0 0 0 4 bytes Tells compiler to assign value 12 to the reserved storage for the variable 11

Declaration of Multiple Variables Variables with the same data type can be grouped together and declared in one statement format: datatype variablelist ; e.g. double grade, total, average; Initialization: using a declaration statement to store a value in a variable Good programming practice is to declare each initialized variable on a line by itself e.g. double grade2 = 93.5; 12

Summary A simple C++ program containing declaration statements has the format: #include <iostream> using namespace std; int main( ) { declaration statements; other statements; Usual Layout } return 0; 13

Your Turn Write a C++ program in which a variable salary is declared in a proper type. Initialise the variable to the value $76,543.21 and display it to the screen. #include<iostream> using namespace std; int main( ) { double salary=76543.21; cout << salary; return 0; } int float double?? 14

Assignment Operators. Basic Assignment Operator: format: variable = expression; computes value of expression on right of "=" sign, assigns it to variable on left side of "=" If not initialized in a declaration statement, a variable should be assigned a value before being used in any computation Variables can only store 1 value at a time Subsequent assignment statements will overwrite the previously assigned values 15

Assignment Operators.. Operand to right of = sign can be A constant A variable A valid C++ expression Operand to left of = sign must be a variable If the operand on the right side is an expression, all variables in expression must have a value in order to get a valid result from the assignment 16

Assignment Operators... Expression: combination of constants and variables that can be evaluated Assignment examples sum = 3 + 7; diff = 15 6; product =.05 * 14.6; tally = count + 1; newtotal = 18.3 + total; average = sum / items; slope = (y2 y1) / (x2 x1); 17

#include<iostream> using namespace std; int main( ) { double length, width, area; length = 27.2; width = 13.6; area = length * width; This program calculates the area of a rectangle given its length and width. cout << "Area of given rectangle = " << area << endl; return 0; } OUTPUT: Area of given rectangle = 369.92 18

Coercion Value on right side of a C++ expression is converted to data type of variable on the left side of the assignment operator = Example: If temp is an integer variable, the assignment temp = 25.89; causes integer value 25 to be stored in integer variable temp 19

Assignment Variations sum = 2*sum + 1; is a valid C++ expression value of 2*sum+1 is stored in variable sum not a valid algebra equation lvalue: any valid quantity on left side of assignment operator rvalue: any valid quantity on right side of assignment operator A number can only be an rvalue A variable can appear on either side of an assignment expression 20

#include<iostream> using namespace std; int main( ) { int sum; Old value overwritten 25 35 sum = 25; cout << "The number stored in sum is " << sum << endl; sum New value is stored sum = sum + 10; cout << "The number stored in sum is " << sum << endl; return 0; } 21

Assignment Variations Assignment expressions such as sum = sum + 25; can be by using a particular one shortcut operator of the following: += -= *= /= %= e.g. sum = sum + 10; can be written as sum += 10; 22

Accumulating The following statements add the numbers 96, 70, 85 and 60 in the calculator fashion: Statement Value in sum sum = 0; 0 sum = sum + 96; 96 sum = sum + 70; 166 sum = sum + 85; 251 23

#include<iostream> using namespace std; int main( ) { int sum; OUTPUT: sum now is 0 sum now is 96 sum now is 166 The final sum is 251 sum = 0; cout << "sum now is " << sum << endl; sum = sum + 96; cout << "sum now is " << sum << endl; sum = sum + 70; cout << "sum now is " << sum << endl; sum = sum + 85; cout << "The final sum is " << sum << endl; return 0; } 24

Counting. Has the form: variable = variable + fixednumber; Each time statement is executed, value of variable is increased by a fixed amount Increment/Decrement Operator (++)/(--) Unary operator for special case when variable is increased or decreased by 1 Using the increment operator, the expression variable = variable + 1; can be replaced by either ++variable; or variable++; 25

Counting.. Examples of counting statements: i= i + 1; n = n + 1; count = count + 1; j = j + 2; m = m + 2; kk = kk + 3; 26

Counting... OUTPUT: count now is 1 count now is 2 Examples of the increment operator: Expression i = i + 1 n = n + 1 count = count + 1 #include<iostream> using namespace std; int main( ) { int count; count = 1; cout << "count now is " << count << endl; Alternative i++ or ++i n++ or ++n count++ or ++count count++; cout << "count now is " << count << endl; return 0; } 27

Prefix/Postfix Increment Operator How is it actually done? It s possible to write C++ programs without using any of these operators total = total + 1; total += 1; ++total; total++; tmpholder= total + 1; total = tmpholder; sum= total++ + 10; sum=total+10, total=total+1; sum= ++total + 10; total=total+1, sum=total+10; Execution order 28

Mathematical Library Functions. Standard preprogrammed functions that can be included in a program e.g sqrt(number) calculates the square root of number Many mathematical functions are available in C++, see Table 3.1 To access these functions in a program, the header file cmath must be used: #include <cmath> 29

Mathematical Library Functions.. What will a header file typically contain? Why including the header file? Before using a C++ mathematical function the programmer must know: Name of the desired mathematical function What the function does Type of data required by the function Data type of the result returned by the function 30

Mathematical Library Functions... Some Maths Functions: abs(x): absolute value of x pow(x, y): x raised to the y power sqrt(x): square root of x Examples: abs(-.302) gives 7.302 pow(2.0, 5.0) gives 32.0 #include<iostream> #include<cmath> using namespace std; int main( ) { double x = 3.1416; double root; root = sqrt(x); cout << "Square root of Pi=" << root << endl; return 0; } result 31

Typecasting: Explicit vs Auto (new type) variable (new type) (expression) char c='a'; int i=(int) c; unsigned long m=(unsigned long) c; m=1234567890; c=char(m); char c='a'; int i= c; unsigned long m= c; m=1234567890; c= m; m= char(m)* 1234; m= m * 1234; 32

Evaluation of expr1 op expr2 For a maths op (+, -, *, /, etc), evaluation is done directly if both expr1 and expr2 have the same data type (meaningful for the op) Otherwise, the less richer type of the operants is promoted (typecast) to the other richer type first before the evaluation The resulting type of the evaluation is thus the richest type of the both operands 33

Interactive Keyboard Input If a program only executes once, data can be included directly in the program If data changes, program must be rewritten Capability is needed to enter different data cin object: used to enter data while a program is executing Example: cin >> num1; Statement stops program execution and accepts data from the keyboard 34

Interactive Keyboard Input cin, like cout, is contained in a C++ library prototyped by the header file iostream Must include the header file via e.g. #include <iostream> How to read values into variables from keyboard ( standard input device ): cin >> varname; cin >> var1 >> var2 >>... >> varn ; 35

#include<iostream> using namespace std; int main( ) { double num1, num2, product; cout << "Type in a number: "; cin >> num1; cout << "Type in another number: "; cin >> num2; product = num1 * num 2; cout << num1 << " times " << num2 << " is " << product << endl; return 0; } // simplest IO Session output Type in a number: 30 Type in another number: 0.01 30 times 0.01 is 0.3 36

What will Happen during the Execution? Program first prints out a message (a prompt), telling the person at the terminal what to do Next statement, cin, pauses computer waits for user to type a value user signals the end of data entry by pressing ENTER key entered value stored in variable to the right of extraction symbol (>>) Computer comes out of pause and goes to next statement (e.g. cout statement) 37

Symbolic Constants. Magic Numbers: literal data used in a program. e.g. π = 3.1416 Constants can be assigned symbolic names const float PI = 3.1416f; const double SALESTAX = 0.05; Must be declared before use Data of const type can not be modified compiler to ensure this, a measure against programming bugs 38

Symbolic Constants.. const: qualifier specifies that the declared identifier cannot be changed A const identifier can be used in any C++ statement in place of number it represents circum = 2 * PI * radius; amount = SALESTAX * purchase; const identifiers commonly referred to as: symbolic constants named constants 39

Placement of Statements As a matter of good programming practice, the order of statements typically should be preprocessor directives int main() { symbolic constants variable declarations other executable statements return value } 40

OUTPUT #include<iostream> using namespace std; int main( ) Enter the amount purchased: 3000 The sales tax = 150 The total bill = 3150 { const double SALESTAX = 0.05; double amount, taxes, total; cout << "\nenter the amount purchased: "; cin >> amount; taxes = SALESTAX * amount; total = amount + taxes; cout << "The sales tax = " << taxes << endl; cout << "The total bill = " << total << endl; return 0; } 41

Reading Bronson s 3 rd Edition: Chapter 3, Section 2.4 Bronson s 4 th Edition: Chapter 3 Robertson s Chapters 1, 2 (secondary) Secondary, here and later on, refers to desirable reading material, which is of less priority than the other (primary) reading material. 42