Programming. C++ Basics

Similar documents
H.O.#2 Fall 2015 Gary Chan. Overview of C++ Programming

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

Introduction to Programming

6.096 Introduction to C++ January (IAP) 2009

Chapter 2: Introduction to C++

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

ANSI C Programming Simple Programs

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

C: How to Program. Week /Mar/05

Introduction to C# Applications

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 15 - C++ As A "Better C"

Introduction to C++ Systems Programming

Chapter 2 - Introduction to C Programming

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

Chapter 2: Overview of C. Problem Solving & Program Design in C

Fundamentals of Programming

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

Creating a C++ Program

LECTURE 02 INTRODUCTION TO C++

UEE1302 (1102) F10: Introduction to Computers and Programming

The C++ Language. Arizona State University 1

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

BITG 1233: Introduction to C++

Tokens, Expressions and Control Structures

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

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

Chapter 2. C++ Basics

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

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

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

Fundamental of Programming (C)

Basic Types, Variables, Literals, Constants

CSCI 123 Introduction to Programming Concepts in C++

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

Objectives. In this chapter, you will:

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

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

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

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

A First Program - Greeting.cpp

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

UNIT- 3 Introduction to C++

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

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

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

Variables. Data Types.

CSCI 1061U Programming Workshop 2. C++ Basics

Chapter 1 & 2 Introduction to C Language

Computer Programming : C++

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

Data types, variables, constants

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

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

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

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

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

Chapter 2 - Control Structures

IS 0020 Program Design and Software Tools

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

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

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 1 Introduction to Computers and C++ Programming

Programming with C++ Language

Introduction to Programming

Data Types and Variables in C language

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

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

COMP 202 Java in one week

CS313D: ADVANCED PROGRAMMING LANGUAGE

EEE145 Computer Programming

Introduction to Programming EC-105. Lecture 2

CS3157: Advanced Programming. Outline

Engineering Problem Solving with C++, Etter/Ingber

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

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

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

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

BASIC ELEMENTS OF A COMPUTER PROGRAM

ET156 Introduction to C Programming

Chapter 2 Basic Elements of C++

C Language, Token, Keywords, Constant, variable

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

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-

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

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

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

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

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

Fundamentals of Programming CS-110. Lecture 2

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Topic 2: C++ Programming fundamentals

DEPARTMENT OF MATHS, MJ COLLEGE

Programming Fundamentals and Methodology. COMP104: C++ Basics

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

CHAPTER 3 BASIC INSTRUCTION OF C++

UNIT-2 Introduction to C++

Transcription:

Programming C++ Basics

Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++ is an extension of the C language C programs should run in C++ C++ supports object-oriented programming

Introduction to C++ A C++ program is a collection of one or more subprograms (functions) Function Collection of statements Statements accomplish a task Every C++ program has a function called main

Introduction to C++ Programming language a set of rules, symbols, special words Rules syntax specifies legal instructions Symbols special symbols ( + - *! ) Word symbols reserved words (int, float, double, char )

General form of a C++ program //Program description is first #include directives go next using namespace std; int main(){ constant declarations go here variable declarations go here assignment statements go here return 0; }

General form of a C++ program //simple program #include <iostream> using namespace std; int main(){ // constant declaration const double Pi = 3.14159; // variable declarations double radius; double area; // assignment statements cout << "Enter circle radius: "; cin >> radius; area = Pi * radius * radius; cout << "Area : " << area << endl; return 0; }

Syntax of the C++ Language Reserved words (appear in blue in Visual C++) Reserved words have a special meaning in C++. The list of reserved words: asm, auto, bool, break, case, catch, char, class, const, continue, default, delete, do, double, else, enum, extern, float, for, friend, goto, if, include, inline, int, long, namespace, new, operator, private, protected, public, register, return, short, signed, sizeof, static, struct, switch, template, this, throw, try, typedef, union, unsigned, using, virtual, void, volatile, while

Data Types in C++ Simple C++ variable types: int integer (32-bit integer on the PC)(example: 1) short 16-bit integer (allows ±32,767) long 32-bit integer (allows ±2,147,483,647) float 32-bit floating point number (allows about 7 digits of precision: 0.1234567) double 64-bit double precision float (allows about 15 digits of char Bool precision: 0.12345678901234) 8-bit a single character (example: y ) 8-bit true or false

The string Type The string Type a programmer-defined type requires #include <string> A string is a sequence of characters "Hi Mom" "We're Number 1!" "75607"

Syntax of the C++ Language Comments (appear in green in Visual C++) Comments are explanatory notes not compiled (i.e. no executable code is generated for comments) Comments are done in two ways: // A double slash starts a single line comment /* A slash followed by an asterisk marks the start of a multiple line comment. It ends with an asterisk followed by a slash */

Syntax of the C++ Language Compiler Directive: #include It refers to a header file of library functions or variables (e.g. input and output). When you compile your C++ program, the compiler reads in the contents of the file before compiling the rest of your program. The included file is compiled together with the program. There are two forms of #include: #include <stdio.h> // for pre-defined files #include "my_lib.h // for userdefined files

Libraries #include loads the code from the standard libraries #include <iostream> // new I/O library #include <iostream.h> // old I/O library #include <stdio.h> // standard functions #include <math.h> // math functions #include <stdlib.h> // contains random funct #include <time.h> // time function using namespace std; indicates that the new C++ libraries should be used. If this line is left out, then the old iostream library is loaded: #include <iostream.h>

Syntax of the C++ Language Identifiers (appear in black in Visual C++) An identifier is a name for variables, constants, functions, etc. It consists of a letter followed by any sequence of letters, digits or underscores Names are case-sensitive. The following are unique identifiers: Mark,Mark1,sellary,Sellary - Names cannot have special characters in them e.g., X!Y, J&20, #007, etc. are invalid identifiers. C++ reserved words cannot be used as identifiers. Choose identifiers that are meaningful and easy to remember.

Constant Declarations Constants represent permanent values. Their values can only be set in the declaration: const double pi = 3.14159; They can make a program more readable and maintainable Constant declaration syntax: const <type> <identifier> = <constant expression>; Examples: const double cost1 = 7.8; const double Cost2 = 1.07; const double cost_1_2 = cost1* Cost2;

Variable Declarations A variable is best thought of as a container for a value with an address: Variable declaration syntax: <type> <identifier>; Examples: int width; int height; 1024 5342.23 A variable must be declared before it can be used. int main(){ x = 5; // illegal: x was not declared }

Variable Declarations A variable can be initialized in a declaration: int x = 3; Several variables of the same type can be declared in the same declaration: double total_usd, area; A variable must have only one type. For example, a variable of the type int can only hold integer values.

Memory Depiction float y = 12.5; short Temperature = 32; char Letter = 'c'; short Number; y Temperature Letter Number Memory location 12.5 32 'c' - 1001 1002 1003 1004 1005 1006 1007 1008 1009

Assignment Statements Assignment syntax: <identifier> = <expression>; Examples: int n, m, k; // declaration n = 5; m = 6 + (4 * 6); k = (n * 2) + m; k = k / 2;

Assignment Statements A variable must be assigned a value before it can be used. Variables are not automatically initialized in VC++. int x, y; // x declared, but not initialized // x and y have random values y = x;// the random value in x assigned to y Once a value has been placed in a variable, it stays there until the program changes it.

Assignment Statements int NewStudents = 6; int OldStudents = 21; int TotalStudents; NewStudents OldStudents TotalStudents 6 21 - TotalStudents = NewStudents + OldStudents ; NewStudents OldStudents TotalStudents 6 21 27

Assignment Statements TotalStudents = NewStudents + OldStudents; NewStudents OldStudents TotalStudents 6 21 27 OldStudents = TotalStudents; NewStudents OldStudents TotalStudents 6 27 27

Value1 = 10; Value2 = 20; int Hold = Value1; Value1 = Value2; Value1 Value2 Hold Value1 Value2 Hold 10 20 10 20 20 10 Value2 = Hold; Value1 Value2 Hold 20 10 10

Common Addition + Arithmetic Operators Subtraction - Multiplication * Division / Mod % Note No exponentiation operator

Integer Division Integer division produces an integer result It rounds down the result Examples 3 / 2 evaluates to 1 4 / 6 evaluates to 0 10 / 3 evaluates to 3

Rules for Division C++ treats integers different than doubles. 100 is an int. 100.0, 100.0000, and 100. are doubles. The general rule for division of int and double types is: double/double -> double (normal) double/int -> double (normal) int/double -> double (normal) int/int -> int (special case: any decimal places discarded)

Rules for Division Example : 220. / 100.0 double/double -> double result is 2.2 220. / 100 double/int -> double result is 2.2 220 / 100.0 int/double -> double result is 2.2 220 / 100 int/int -> int result is 2 Summary: division is normal unless both the numerator and denominator are int, then the result is an int (the decimal places are discarded).

Forcing a Type Change You can change the type of an expression with a cast operation Syntax: variable1 = type(variable2); variable1 = type(expression); Example: int x=1, y=2; double result1 = x/y; // 1/2 = 0 -> 0.0 double result2 = double(x)/y; // 1.0/2 = 0.5 -> 0.5 double result3 = x/double(y); // 1/2.0 = 0.5 -> 0.5 double result4 = double(x)/double(y); // 1.0/2.0 -> 0.5 double result5 = double(x/y); // double(1/2) = double(0) -> 0.0 int cents = int(result4*100); // cents is 50

Mod Produces the remainder of the division Examples 5 % 2 evaluates to 1 12 % 4 evaluates to 0 4 % 5 evaluates to 4

Operators and Precedence Which of the following is it equivalent to mx + b? (m * x) + b m * (x + b) Operator precedence tells how to evaluate expressions Standard precedence order ( ) Evaluated first, if nested innermost done first * / % Evaluated second. If there are several, then evaluate from left-to-right + - Evaluate third. If there are several, then evaluate from left-to-right

Operator Precedence Examples 1 + 2 * 3 / 4-5 = 1 + 1-5 = -3 2 * 4 / 5 + 3 * 5 % 4 = 8/5 + 15%4 = 1+3 = 4 3.0 * 3 / 4 = 9.0 / 4 = 2.25 (1 + 3) * ((2 + 4 * 6) * 3) / 2 + 2 = 4 * (26*3)/2 + 2 = 158

Increment and Decrement Operators Pre-increment ++x; equivalent to x = x + 1; Pre-decrement --x; Changes the value before execution of a statement y = ++x; Post-increment intval++; Post-decrement intval--; Changes the value after execution of the statement y = x++;

Standard Input/Output cin - the standard input stream Input operator >> extracts data from input stream (the keyboard by default) skips over white spaces extracts only characters of the right form and performs automatic conversion to the type specified

Standard Input/Output cout - the standard output stream Output operator << inserts data into the output stream (the screen by default) Example: int id; float score; cout << "Enter student ID and score: "; cin >> id >> score; cout << "Student ID: " << id << " score: " << score << endl;

Output Values sent to an output device Usually the screen Can also be a file or some device Syntax for screen output: cout << expression << Example cout << "The total is "<< sum << endl; Output command Sample Insertion Program operator Manipulator for carriage Values to be return printed

Output Escape sequences also used to manipulate output cout << "The total is\t "<< sum << endl;

Assignment Conversions A floating-point expression assigned to an integer object is always rounded down (truncated) An integer expression assigned to a floating-point object is converted to a floating-point value Example 1: float y = 2.7; int i = 15; int j = 10; i = y; // i is now 2 cout << i << endl; y = j; // y is now 10.0 cout << y << endl;

Example 2: int m, n; double x, y; m = 3; n = 2.5; x = m/n; to x n = x+m/2; Assignment Conversions // 2.5 converted to 2 and assigned to n // 3/2=1 converted to 1.0 and assigned // m/2=1 : integer division // x+m/2 : double addition because x is double // convert result of m/2 to double (i.e. 1.0) // x+m/2=2.0 // convert result of x+m/2 to int (i.e. 2) // because n is int

White Spaces Extra blanks or tabs (white spaces) are ignored x=3; x = 3 ; Blank lines and comments are treated as white spaces Code can be indented in any way More than one statement can be on one line int x, y; x=3; y = 10; int z = x+y; A single statement can be continued over several lines cout << feet << " feet and " << inches << " inches" << endl;

Good Programming Style Place each statement on a line by itself (except long cout statements) x = m/n; Use blank lines to separate sections of code Use the same indentation for all statements in the same block of code { }. ( Format selection, ALT-F8, will automatically fix indentation) int main(){ int x; x = 5; return 0; }

Good Programming Style Use meaningful identifier names double area, sum, radius; Document each variable when it is declared double area; // area of the circle double distance; //distance from top to bottom Document each segment of code // Convert inches to feet and inches feet = inches / in2feet; inches = inches % in2feet; Document the beginning of the program with a header that tells the purpose of the program // Convert inches to feet and inches