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

Similar documents
Computer Programming : C++

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

A First Program - Greeting.cpp

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

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

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.

6.096 Introduction to C++ January (IAP) 2009

2 nd Week Lecture Notes

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

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

Why Is Repetition Needed?

Introduction to Programming using C++

Fundamentals of Programming CS-110. Lecture 2

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

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

Programming, numerics and optimization

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

LECTURE 02 INTRODUCTION TO C++

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

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

Introduction to Programming EC-105. Lecture 2

Chapter 2. C++ Basics

Variables. Data Types.

UNIT- 3 Introduction to C++

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Objectives. In this chapter, you will:

Your first C++ program

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

CHAPTER 3 BASIC INSTRUCTION OF C++

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Chapter 1 INTRODUCTION

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

Programming. C++ Basics

Scientific Computing

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

CS242 COMPUTER PROGRAMMING

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

CSCE 110 PROGRAMMING FUNDAMENTALS

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

From Pseudcode Algorithms directly to C++ programs

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

The C++ Language. Arizona State University 1

Increment and the While. Class 15

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

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

CSCE 206: Structured Programming in C++

Understanding main() function Input/Output Streams

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

Computational Physics Operating systems

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Computer Skills (2) for Science and Engineering Students

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

Introduction to C++ Systems Programming

Introduction to Programming

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

BASIC ELEMENTS OF A COMPUTER PROGRAM

Short Notes of CS201

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

OBJECT ORIENTED PROGRAMMING

Boolean Algebra Boolean Algebra

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

C++ for Python Programmers

CS201 - Introduction to Programming Glossary By

Data Structure Lab. Prepared By Dr. Hanan Ahmed Salman

Chapter 2. C++ Syntax and Semantics, and the Program Development Process. Dale/Weems 1

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Input And Output of C++

BITG 1233: Introduction to C++

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Creating a C++ Program

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

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

CSc Introduction to Computing

Programming with C++ Language

REPETITION CONTROL STRUCTURE LOGO

CE221 Programming in C++ Part 1 Introduction

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

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

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

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

Summary of basic C++-commands

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

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

Exercise 1.1 Hello world

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.

Numbers. John Perry. Spring 2017

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

CSI33 Data Structures

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Binomial pricer (1.1)

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

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

INTRODUCTION TO COMPUTER SCIENCE - LAB

C++ Programming Basics

Transcription:

Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is a compiled language, which means: Source Code Compiler Object Code Linker (with libraries) Executable To create an executable program the source code is compiled to intermediate code. This intermediate code must then be linked with the C++ and other libraries in order to finish up with an executable program. The C language consists of a series of Methods (named functions) which are assembled together to make a complete program. C++ is a strongly typed programming language (with a few exceptions). This means that variables must be declared to be a data type before being used. This means that data contained in variables will be assigned to specific memory locations during the compile/link stage. Other languages, such as Python, PHP, or JavaScript are scripting languages and will dynamically allocate data to memory locations. This results in a language that can produce more efficient executables. Basic program The following is a basic program in C++; The program consists of several sections. The first two lines #include <iostream> using namespace std; These lines import a header file named iostream.h and defines the namespace std. The header file consists of definitions that the game needs to reference data and methods. The using statement identifies the default library as std. This means that when you use elements in the library you don t have to reference the library before using the element. If you did not include the using statement you would have to write: std::cout<< Hello you are <<age<< \n ; The method that includes the executable code is contained in the method named int main().

The method is named main and it returns an integer (the term int identifies a data type). The commands between the that mark the boundary of this method contains a number of C++ statements. The first two statements are: int age; age = 10; Each statement in C++ must end with a ; character. This marks the end of the statement and is used by the compiler. This means that you can write C++ statements in any format as long as the statement ends in ; int age ; age = 10; are also valid C++ statements. The two statements define a variable and then assign a value to this variable. The variable is named age and the kind of data that can be assigned to this variable are integers. The second statement puts the number 10 into this variable. The next statement (line 8) is a command to display information to the console window. cout<< Hello you are <<age<< \n ; The cout command is actually an Object which is linked to the console. The command << sends information into this object which then displays it on the screen in a console window. The string is enclosed in characters. The cout command also can display variables. This is done by using <<age. The final part of the statement is << \n ; which outputs a character (characters are enclosed in ). The character being sent to the console is \n which represents a return character. This statement could have been written as: cout<< Hello you are ; cout<<age; cout<< \n ; The last two lines (10 and 11) are used to pause the console window from closing. Like the cout object the cin object is also tied to the console window but this is an input stream. The cin>>x statement pauses the console window and waits for the use to enter a value. The value will be put into the variable named x which is defined as an integer. Data and Variables Since C++ is a strongly typed programming language you must be aware of the data types the game uses and how to declare variables to hold the different kinds of data. This data is called a data type. There are two kinds of data types in C++, fundamental types and derived types. The fundamental types align with basic computer memory structures. That is, these types map closely with how data is stored in computer memory. Memory in a computer can be thought of as structured in 8 bits blocks (a bit is a single value either 0 or 1). Eight of these 0 and 1 values is called a Byte.

Fundamental data types are: Group Type names* Notes on size / precision Character types Integer types (signed) char char16_t char32_t wchar_t signed char signed short int signed int signed long int signed long long int unsigned char unsigned short int Exactly one byte in size. At least 8 bits. Not smaller than char. At least 16 bits. Not smaller than char16_t. At least 32 bits. Can represent the largest supported character set. Same size as char. At least 8 bits. Not smaller than char. At least 16 bits. Not smaller than short. At least 16 bits. Not smaller than int. At least 32 bits. Not smaller than long. At least 64 bits. Integer types (unsigned) unsigned int (same size as their signed counterparts) Floating-point types Boolean type unsigned long int unsigned long long int float double long double bool Precision not less than float Precision not less than double Void type void no storage Null pointer decltype(nullptr) The relative sizes of these data types are: Size Unique representable values Notes 8-bit 256 = 2 8 16-bit 65 536 = 2 16 32-bit 4 294 967 296 = 2 32 (~4 billion) 64-bit 18 446 744 073 709 551 616 = 2 64 (~18 billion billion)

Before variables can be used they must be declared and the appropriate data put into the variable. For example: int age = 10; double pay = 34.33; char endl = \n ; bool flag = false; Another data type that is derived from char is a string. This is used like it was a fundamental data type but it actually is a series of char variables placed in memory. Strings are defined with the string statement: string name = frank jones ; Using the data type list you can define various types of variables to hold data. You can also add letters to values to force them into the variables. For example: int age = 12; long int distance = 45L; // or 45l unsigned int val = 56U; // or 56u; short int val = 33; float payx = 34.55F; // or 34.55f; double payx = 23.44; // default numbers are double bool flag = false; C++ has a special variable data type called auto that will automatically define a data type based on the initializer (the value put into the variable when it is being created). auto age = 12; auto pay = 34.33; auto newpay = 123.44L; Expressions An expression in C++ is always terminated with a ; character. The assignment operation is written with an = symbol and assigns values to variables. int age; age = 12; Here, the first expression defines an integer variable (age) and the second expression assigns a value to this variable. Constant values include things like numbers, characters, Boolean values. These can be assigned to appropriate variables. Integers can be written as: 12 34-33 Floating point numbers can be written as: 12 45.44

-12.43452 12.02e23 (this is the same as 12.02 times 10 23 ) 1.6e-19 (this is the same as 1.6 times 10-19 ) By default, variables can be changed in a program. However, there are times when we want variables to be constant so they cannot be accidently changed. There are two ways to do this, using the const expression or using #define. const double tax =.45; #define NL \n ; The term const when placed before a variable requires that the variable be assigned a value when it is declared. The #define statement indicates that when the compiler evaluates the code it automatically replaces one character with another. Operators Operators are symbols used in assignment and calculation. The assignment operator is the = symbol and assigns what is on the right side of the symbol to the variable on the left side. int age = 12; If the right side of the assignment operator is an expression, then the expression is first evaluated before being assigned. int age; age = 12 + 4; You can write expressions with more than one = symbol. int a, b, c, d; a = b = c = d = 12; In this case four integer variables are defined and then assigned the value of 12. Other operators include calculation operators. These are: operator description + addition - subtraction * multiplication / division % modulo The last (modulo) operator takes two values and returns the remainder of dividing one by the other. For example: int r = 12%5; The value of r is the remainder of dividing 12 by 5 (which is 2). Expressions using such operators can be grouped with ( ) symbols.

X = 12 * 3; Y = 4 + 2 * X; The order of calculation means which operators are used first and second. The multiplication and division and modulo are done before addition and subtraction, otherwise the operations proceed from left to right. X = (12 + 2) * 2; // 14 times 2 There are also operators that are shortcut for increment and decrement (increase or decrease by one). int X = 12; X++; cout<<x; // this prints 13 int Y = 5; cout<<y--; C++ also has a set of shortcut compound operators Expression equivalent to... y += x; y = y + x; x -= 5; x = x - 5; x /= y; x = x / y; price *= units + 1; price = price * (units+1); Along with calculation operators C++ has a set of Boolean operators and return true or false based on the values. operator description == Equal to!= Not equal to < Less than > Greater than <= Less than or equal to >= Greater than or equal to

These can be combined with AND, OR, or NOT logical operators: bool retvalue; retvalue = (12 > 4); retvalue = (10 == 10); retvalue = (12!= 10); retvalue = (12 <= 11); retvalue = ( (12>10) (12 < 100) ) retvalue = ( (9 < 10) && (12 >= 100) ) // returns false // returns true // returns true // returns false // returns true // returns false && OPERATOR (and) a b a && b true true true true false false false true false false false false OPERATOR (or) a b a b true true true true false true false true true false false false There is also the? operator which is a simplified IF statement: int val; val = 12 > 100? 10 : 9; // returns 9 The structure of the? operator is: [ Boolean expression ]? [return if true] : [return if false]

Logical Operations Logical operations include looping and flow control. These operations are done by evaluating logical operations. These operations resolve into either true or false (Boolean values). Logical Operations control the flow of the program. The two main logical operations are IF and SWITCH. if ( Boolean is true ) //perform actions if value is true else // perform actions if value is false int age = 12; if( age > 100 ) cout<< Over ; else cout<< Under ; The switch statement format is: switch( value ) case v1: [statements] break; case v2: [statements] break; default: [statements]

The value for a switch must be a discrete value (not floating point or string). int age = 12; switch(age) case 10: cout<< 10 ; break; case 12: cout<< 12 ; break; default: cout<< None ; Loops There are three types of loops in C++, while, do..while, and for. Each uses Boolean values. while( [Boolean is true] ) // statements do // statements while( [Boolean is true] ); The difference between these loops is that the test condition is tested at the start of the loop in the while() and at the end of the loop in the do..while() int age = 100; while( age > 10 ) cout<< Count down << \n ; age--; int age = 100; do cout<< Count down << \n ; age --; while( age > 10); The third type of loop is the for loop. This loop has three parameters to control the loop: for( [starting statement] ; [check condition] ; [end of loop operation] ) // statements

Functions A function is a set of C++ statements defined with a name, a return type, and parameters. Functions in C++ must be declared before they are used. In this case, the ShowCount() function is passed an Integer value (limit) which it then uses to print out and total up a value. The total value is then returned to the main() method. The pause() method does not return anything or is passed any parameters so the return type is void and the parameter list is empty.

Data is passed into functions in two ways, by value and by reference. Constant values such as numbers and characters are passed by value. Function parameters can have default values. If a value is not supplied then the default is used. int calctotal( int a, int b=10) return a+b; Functions can be overloaded in C++. This means that if two functions have the same name but different parameters then the compiler will choose the correct function.

In this case the function calctotal can be called by passing strings or integers. In the string version it uses stoi() to convert from string to number (this is a C++11 version).