Second Class Control and Systems Engineering

Similar documents
C++ Language Tutorial

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

C++ INTERVIEW QUESTIONS

6. Control Structures

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Sources: On the Web: Slides will be available on:

Sequential Program Execution

Chapter One Introduction to Programming

Pemrograman Dasar. Basic Elements Of Java

Comp151. Definitions & Declarations

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

C++ Input/Output: Streams

Object Oriented Software Design

Informatica e Sistemi in Tempo Reale

Object Oriented Software Design

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

13 Classes & Objects with Constructors/Destructors

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

The programming language C. sws1 1

C++ Programming Language

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Moving from CS 61A Scheme to CS 61B Java

C++ Essentials. Sharam Hekmat PragSoft Corporation

JavaScript: Control Statements I

Objective-C Tutorial

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

I PUC - Computer Science. Practical s Syllabus. Contents

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Syllabus OBJECT ORIENTED PROGRAMMING C++

VB.NET Programming Fundamentals

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Numbering Systems. InThisAppendix...

Java Interview Questions and Answers

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

An Incomplete C++ Primer. University of Wyoming MA 5310

Computer Science 281 Binary and Hexadecimal Review

The C Programming Language course syllabus associate level

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Object Oriented Software Design II

C PROGRAMMING FOR MATHEMATICAL COMPUTING

Basics of I/O Streams and File I/O

El Dorado Union High School District Educational Services

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

ASSEMBLY LANGUAGE PROGRAMMING (6800) (R. Horvath, Introduction to Microprocessors, Chapter 6)

Programming languages C

Appendix K Introduction to Microsoft Visual C++ 6.0

Chapter 5. Selection 5-1

Chapter 2: Elements of Java

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Variables, Constants, and Data Types

Curriculum Map. Discipline: Computer Science Course: C++

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

arrays C Programming Language - Arrays

So far we have considered only numeric processing, i.e. processing of numeric data represented

Glossary of Object Oriented Terms

Windows PowerShell Essentials

How To Write Portable Programs In C

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Member Functions of the istream Class

Introduction to Visual C++.NET Programming. Using.NET Environment

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

10CS35: Data Structures Using C

Formatting Numbers with C++ Output Streams

Introduction to Java

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Introduction to Python

Passing 1D arrays to functions.

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

A Programming Language for Mechanical Translation Victor H. Yngve, Massachusetts Institute of Technology, Cambridge, Massachusetts

Computer Programming Tutorial

1 Abstract Data Types Information Hiding

MATLAB Programming. Problem 1: Sequential

Section 1.4 Place Value Systems of Numeration in Other Bases

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Exercise 4 Learning Python language fundamentals

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Base Conversion written by Cathy Saxton

Chapter 5 Names, Bindings, Type Checking, and Scopes

Lecture 22: C Programming 4 Embedded Systems

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

1 Description of The Simpletron

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Transcription:

Republic of Iraq Ministry of Higher Education and Scientific Research University of Technology Control and Systems Engineering Department Second Class Control and Systems Engineering 2010-2011 Language

Syllabus Programming language of Principles of Object-Oriented Programming Introduction to (cin,cout,scanf,printf,gets,puts) (2 hours) (2 hours) Tokens, Expressions, Keywords, Identifier, Data type and User define data type. (4 hours) Constants, #Define Directive, Declaration of Variable and Reference Variables (4 hours) Operators in (4 hours) New and Delete Operators, Scope Resolution Operator, Manipulators and type Cast Operator,setw,endl(manipulator) (2 hours) Conditional Statements (if, if-else, if-else-if-else, switch Statement)(4 hours) Loops ( for Statement, while Statement, do-while, break, continue and goto ) (4 hours) Arrays (one and two dimensions) (4 hours) Strings ( strlen, strcat, strset, strnset, strcmp, strcpy, strrev, strlwr,strupper,strnspn) (2 hours) Functions ( Function Prototype, Call by value, Call by reference, inline Functions, Default Arguments, Function Overloading (2 hours) Pointers (pointer declaration, pointer with function, pointer with strings) (6 hours) Class and Objects ( Structures Revisited, Specifying a Class, Defining Member Functions, Making Outside Function Inline) (4 hours) Array of Objects, Objects as Function Arguments, Friendly Functions (2 hours) Constructors and Destructors ( constructors, Parameterized Constructors, Multiple Constructors in a class, Copy Constructors and destructors) (4 hours) Operator Overloading and Type Conversions (defining operator overloading, Overloading Unary Operators, Overloading Binary Operators, Manipulate string using operators) (4 hours) Files (2 hours)

P-1 L1-1 History of, as the name implies, is essentially based on the C programming language. Therefore, it seems prudent to begin with a brief history of C. The C programming language was devised in the early 1970s at Bell Laboratories by Dennis Ritchie. It was designed as a system implementation language for the Unix operating system. The history of C and Unix are closely intertwined. For this reason a lot of Unix programming is done with C. To some extent, C was originally based on the typeless language BCPL, however it grew well beyond that. L1-2 Fundamentals is a programming language. As such, it shares a number of similarities with other programming languages. First we may need to clarify what a programming language is. A computer thinks in 1 s and 0 s. Various switches are either on (1 s), or off (0 s). Most humans, however, have trouble thinking in 1 s and 0 s. A programming language is a language that provides a bridge between the computer and human beings. A low-level language is one that is closer to a computer s thinking than to a human language. A prime example would be Assembly language. A high-level language is one that is closer to human language.figure 1. Figure 1: Programming languages. Programs are written to handle data. This is why the industry as a whole is often referred to as data processing, information technology, computer information systems,

P-2 and so on. That data might be information about employees, parts to a mathematical computation, scientific data, or even the elements of a game. No matter what programming language or techniques you use, the ultimate goal of programming is to store, manipulate, and retrieve data. Data must be temporarily stored in the program, in order to be manipulated. This is accomplished via variables. A variable is simply a place in memory set aside to hold data of a particular type. It is a specific section of the computer s memory that has been reserved to hold some data. It is called a variable because its value or content can vary. When you create a variable, you are actually setting aside a small piece of memory for storage purposes. The name you give the variable is actually a label for that address in memory. For example, you might declare a variable in the following manner. int j; Then, you have just allocated four bytes of memory; you are using the variable j to refer to those four bytes of memory. You are also stating that the only type of data that j will hold, is whole numbers. (The int is a data type that refers to integers, or whole numbers.) Now, whenever you reference j in your code, you are actually referencing the contents being stored at a specific address in memory. L1-3 Getting Ready to Program Programs are written to instruct machines to carry out specific tasks or to solve specific problems. A step-by-step procedure that accomplishes a desired task is called an algorithm. Thus, programming is the activity of communicating algorithms to computers. The programming process is analogous, except that machines have no tolerance for ambiguity and must have all steps specified in a precise language and in tedious detail. The Programming Process 1. Specify the task. 2. Discover an algorithm for its solution. 3. Code the algorithm in. 4. Test the code.

P-3 A computer is a digital electronic machine composed of three main components: processor, memory, and input/output devices. The processor is also called the central processing unit, or CPU. The processor carries out instructions that are stored in the memory. Along with the instructions, data also is stored in memory. The processor typically is instructed to manipulate the data in some desired fashion. Input/output devices take information from agents external to the machine and provide information to those agents. Input devices are typically terminal keyboards, disk drives, and tape drives. Output devices are typically terminal screens, printers, disk drives, and tape drives. The physical makeup of a machine can be quite complicated, but the user need not be concerned with the details. When a simple program is compiled, three separate actions occur: First the preprocessor is invoked, then the compiler, and finally the linker. The preprocessor modifies a copy of the source code by including other files and by making other changes. The compiler translates this into object code, which the linker then uses to produce the final executable file. A file that contains object code is called an object file. Object files, unlike source files, usually are not read by humans. When we speak of compiling a program, we really mean invoking the preprocessor, the compiler, and the linker. For a simple program, this is all done with a single command. After the programmer writes a program, it has to be compiled and tested. If modifications are needed, the source code has to be edited again. Thus, part of the programming process consists of this cycle: When the programmer is satisfied with the program performance, the cycle ends.

P-4 L1-4 A First Program A first task for anyone learning to program is to print on the screen. Let us begin by writing the traditional first program which prints the phrase Hello, world! on the screen. The complete program is I/P // my first program in #include <iostream> int main () cout << "Hello World!"; return 0; Hello World! O/P The first panel shows the source code for our first program. The second one shows the result of the program once compiled and executed. The previous program is the typical program that programmer apprentices write for the first time, and its result is the printing on screen of the "Hello World!" sentence. It is one of the simplest programs that can be written in, but it already contains the fundamental components that every program has. We are going to look line by line at the code we have just written: // my first program in This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not have any effect on the behavior of the program. The programmer can use them to include short explanations or observations within the source code itself. In this case, the line is a brief description of what our program is. #include <iostream>

P-5 Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines with expressions but indications for the compiler's preprocessor. In this case the directive #include <iostream> tells the preprocessor to include the iostream standard file. This specific file (iostream) includes the declarations of the basic standard input-output library in, and it is included because its functionality is going to be used later in the program. int main () This line corresponds to the beginning of the definition of the main function. The main function is the point by where all programs start their execution, independently of its location within the source code. It does not matter whether there are other functions with other names defined before or after it - the instructions contained within this function's definition will always be the first ones to be executed in any program. For that same reason, it is essential that all programs have a main function. The word main is followed in the code by a pair of parentheses (()). That is because it is a function declaration: In, what differentiates a function declaration from other types of expressions are these parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters within them. Right after these parentheses we can find the body of the main function enclosed in braces (). What is contained within these braces is what the function does when it is executed. cout << "Hello World"; This line is a statement. A statement is a simple or compound expression that can actually produce some effect. In fact, this statement performs the only action that generates a visible effect in our first program. cout represents the standard output stream in, and the meaning of the entire statement is to insert a sequence of characters (in this case the Hello World sequence of characters) into the standard output stream (which usually is the screen). cout is declared in the iostream standard file within the std namespace, so that's why we needed to include that specific file and to declare that we were going to use this specific namespace earlier in our code. Notice that the statement ends with a semicolon character (;). This character is used to mark the end of the statement and in fact it must be included at the end of all expression statements in all programs (one of the most common syntax errors is indeed to forget to include some semicolon after a statement). return 0;

P-6 The return statement causes the main function to finish. return may be followed by a return code (in our example is followed by the return code 0). A return code of 0 for the main function is generally interpreted as the program worked Let us add an additional instruction to our first program: I/P O/P // my second program in Hello World! I'm a program #include <iostream> using namespace std; int main () cout << "Hello World! "; cout << "I'm a program"; return 0; Ex/write a program to print the following message on the screen. is a programming language,based on the C programming Solution I/P // my second program in #include <iostream.h> Void main () cout << " is a programming language\n"; cout << " based on the C programming "; \n This character means newline on the screen. O/P is a programming language based on the C programming

P-7 L2-1 Structure of a program A computer program is a sequence of instructions that tell the computer what to do. L2-1-1 Statements and expressions The most common type of instruction in a program is the statement. A statement in is the smallest independent unit in the language. In, we write statements in order to convey to the compiler that we want to perform a task. Statements in are terminated by a semicolon. There are many different kinds of statements in. The following are some of the most common types of simple statements: int x; x = 5; cout << x; An expression is an mathematical entity that evaluates to a value. For example, in math, the expression 2+3 evaluates to the value 5 For example, the statement x = 2 + 3; is a valid assignment statement. The expression 2+3 evaluates to the value of 5. This value of 5 is then assigned to x. L2-2 Keywords

P-8 Keywords in are explicitly reserved words that have a strict meaning and may not be used in any other way. They include words used for type declarations, such as int, char, and float; words used for statement syntax, such as do, for, and if; and words used for access control, such as public, protected, and private. Table 2.2 shows the keywords in current systems. asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while L2-3 Identifiers, and naming them The name of a variable, function, class, or other entity in is called an identifier. gives you a lot of flexibility to name identifiers as you wish. However, there are a few rules that must be followed when naming identifiers: The identifier can not be a keyword. Keywords are reserved. The identifier can only be composed of letters, numbers, and the underscore character. That means the name can not contains symbols (except the underscore) nor whitespace. The identifier must begin with a letter or an underscore. It can not start with a number. distinguishes between lower and upper case letters. nvalue is different than nvalue is different than NVALUE. int value; // correct int Value; // incorrect (should start with lower case letter) int VALUE; // incorrect (should start with lower case letter)

P-9 int VaLuE; // incorrect (see your psychiatrist) ; If the identifier is a multiword name, there are two common conventions: separated by underscores, or intercapped. int my_variable_name; // correct (separated by underscores) int myvariablename; // correct (intercapped) int my variable name; // incorrect (spaces not allowed) int MyVariableName; // incorrect (should start with lower case letter Very important: The language is a "case sensitive" language. That means that an identifier written in capital letters is not equivalent to another one with the same name but written in small letters. Thus, for example, the RESULT variable is not the same as the result variable or the Result variable. These are three different variable identifiers. L2-4 Fundamental data types When programming, we store the variables in our computer's memory, but the computer has to know what kind of data we want to store in them, since it is not going to occupy the same amount of memory to store a simple number than to store a single letter or a large number, and they are not going to be interpreted the same way. The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can manage in. A byte can store a relatively small amount of data: one single character or a small integer (generally an integer between 0 and 255). In addition, the computer can manipulate more complex data types that come from grouping several bytes, such as long numbers or non-integer numbers. Next you have a summary of the basic fundamental data types in, as well as the range of values that can be represented with each one: Name Description Size* Range* char Character or small integer. 1byte signed: -128 to 127 unsigned: 0 to 255 short int Short Integer. 2bytes signed: -32768 to 32767

P-10 (short) unsigned: 0 to 65535 int Integer. 4bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 long int (long) Long integer. 4bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 bool Boolean value. It can take one of two values: 1byte true or false true or false. float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits) double Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits) long double Long double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits) L2-4-1 sizeof() In order to determine the size of data types on a particular machine, provides an operator named sizeof. This operator accepts one parameter, which can be either a type or a variable itself and returns the size in bytes of that type or object: Format sizeof(type) sizeof(variable) Example: int a; a = sizeof (char); This will assign the value 1 to a because char is a one-byte long type. The value returned by sizeof is a constant, so it is always determined before program execution. You can compile and run the following program to find out how large your data types are: #include <iostream> int main() using namespace std; cout << "bool:\t\t" << sizeof(bool) << " bytes" << endl;

P-11 cout << "short:\t\t" << sizeof(short) << " bytes" << endl; cout << "int:\t\t" << sizeof(int) << " bytes" << endl; cout << "long:\t\t" << sizeof(long) << " bytes" << endl; cout << "float:\t\t" << sizeof(float) << " bytes" << endl; cout << "double:\t\t" << sizeof(double) << " bytes" << endl; cout << "long double:\t" << sizeof(long double) << " bytes" << endl; return 0; O\P bool: 1 bytes char: 1 bytes wchar_t: 2 bytes short: 2 bytes int: 4 bytes long: 4 bytes float: 4 bytes double: 8 bytes long double: 8 bytes L2-5 VARIABLES Variables are a way of reserving memory to hold some data and assign names to them so that we don't have to remember the numbers like 46735 and instead we can use the memory location by simply referring to the variable. Every variable is mapped to a unique memory address. Every variable in can store a value. However, the type of value which the variable can store has to be specified by the programmer. supports the following inbuilt data types:- int (to store integer values) There are three types of integer variables in, short, int and long int int i; int i=25; long b=299; int s,j,k; float (to store decimal values) Floating point data types comes in three sizes, namely float, double and long double.

P-12 float a; float b=4.84; float a=2e6; double sum; char (to store characters) char a; char name= s ; bool (to store Boolean value either 0 or 1) A variable of type bool can store either value true or false and is mostly used in comparisons and logical operations. When converted to integer, true is any non zero value and false corresponds to zero. To see what variable declarations look like in action within a program. I\P O\P // operating with variables Result=4 #include <iostream> int main () // declaring variables: int a, b; int result; // process: a = 5; b = 2; a = a + 1; result = a - b; // print out the result: cout << result= ; cout << result; // terminate the program: return 0; L2-5-1 Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous code at the

P-13 beginning of the body of the function main when we declared that a, b, and result were of type int. A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block. L2-6 Initialization of variables When declaring a regular local variable, its value is by default undetermined. But you may want a variable to store a concrete value at the same moment that it is declared. In order to do that, you can initialize the variable. There are two ways to do this in : The first one, known as c-like, is done by appending an equal sign followed by the value to which the variable will be initialized: type identifier = initial_value ; For example int a = 0; The other way to initialize variables, known as constructor initialization, is done by enclosing the initial value between parentheses (()): type identifier (initial_value) ; For example: int a (0); Both ways of initializing variables are valid and equivalent in. I\P O\P

P-14 // initialization of variables #include <iostream> int main () int a=5; // initial value = 5 int b(2); // initial value = 2 int result;// initial value undetermined a = a + 3; result = a - b; cout << result; return 0; 6 L3-1 Literals

P-15 Literals are used to express particular values within the source code of a program. We have already used these previously to give concrete values to variables or to express messages we wanted our programs to print out, for example, when we wrote: a = 5; The 5 in this piece of code was a literal constant. Literal constants can be divided in Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values. L3-1-1 Integer Numerals They are numerical constants that identify integer decimal values. Notice that to express a numerical constant we do not have to write quotes (") nor any special character. 1776 707-273 In addition to decimal numbers, allows the use as literal constants of octal numbers (base 8) and hexadecimal numbers (base 16). If we want to express an octal number we have to precede it with a 0 (zero character). And in order to express a hexadecimal number we have to precede it with the characters 0x (zero, x). For example, the following literal constants are all equivalent to each other: 75 // decimal 0113 // octal 0x4b // hexadecimal All of these represent the same number: 75 (seventy-five) expressed as a base-10 numeral, octal numeral and hexadecimal numeral, respectively. Literal constants, like variables, are considered to have a specific data type. By default, integer literals are of type int. However, we can force them to either be unsigned by appending the u character to it, or long by appending l:

P-16 75 // int 75u // unsigned int 75l // long 75ul // unsigned long In both cases, the suffix can be specified using either upper or lowercase letters. L3-1-2 Floating Point Numbers They express numbers with decimals and/or exponents. They can include either a decimal point, an e character (that expresses "by ten at the Xth height", where X is an integer value that follows the e character), or both a decimal point and an e character: 3.14159 // 3.14159 6.02e23 // 6.02 x 10^23 1.6e-19 // 1.6 x 10^-19 3.0 // 3.0 These are four valid numbers with decimals expressed in. The first number is PI, the second one is the number of Avogadro, the third is the electric charge of an electron (an extremely small number) -all of them approximated- and the last one is the number three expressed as a floating-point numeric literal. The default type for floating point literals is double. If you explicitly want to express a float or long double numerical literal, you can use the f or l suffixes respectively: 3.14159L // long double 6.02e23f // float Any of the letters than can be part of a floating-point numerical constant (e, f, l) can be written using either lower or uppercase letters without any difference in their meanings.

P-17 L3-1-3Character and string literals There also exist non-numerical constants, like: 'z' 'p' "Hello world" "How do you do?" The first two expressions represent single character constants, and the following two represent string literals composed of several characters. Notice that to represent a single character we enclose it between single quotes (') and to express a string (which generally consists of more than one character) we enclose it between double quotes ("). Character and string literals have certain peculiarities, like the escape codes. These are special characters that are difficult or impossible to express otherwise in the source code of a program, like newline (\n) or tab (\t). All of them are preceded by a backslash (\). Here you have a list of some of such escape codes: \n newline \r carriage return \t tab \b backspace \a alert (beep) \' single quote (') \" double quote (") \? question mark (?) \\ backslash (\) For example: '\n' '\t'

P-18 "Left \t Right" "one\ntwo\nthree" String literals can extend to more than a single line of code by putting a backslash sign (\) at the end of each unfinished line. "string expressed in \ two lines" L3-2 Defined constants (#define) You can define your own names for constants that you use very often without having to resort to memory-consuming variables, simply by using the #define preprocessor directive. Its format is: #define identifier value For example: #define PI 3.14159265 #define NEWLINE '\n' This defines two new constants: PI and NEWLINE. Once they are defined, you can use them in the rest of the code as if they were any other regular constant, for example: I/P // defined constants #include <iostream.h> #define PI 3.14159 #define NEWLINE '\n' int main () double r=5.0; // radius double circle; circle = 2 * PI * r; cout << circle; 31.4159 O/P

P-19 cout << NEWLINE; return 0; Notes The #define directive is not a statement but a directive for the preprocessor; therefore it assumes the entire line as the directive and does not require a semicolon (;) at its end. If you append a semicolon character (;) at the end, it will also be appended in all occurrences within the body of the program that the preprocessor replaces. L3-3 Declared constants (const) With the const prefix you can declare constants with a specific type in the same way as you would do with a variable: const int pathwidth = 100; const char tabulator = '\t'; Here, path width and tabulator are two typed constants. They are treated just like regular variables except that their values cannot be modified after their definition.

P-20 L4-1 Input/Output input/output is not directly part of the language but rather is added as a set of types and routines found in a standard library. The standard I/O library is iostream or iostream.h. The iostream library overloads the two bit-shift operators. << // "put to" output stream, normally left shift >> // "get from" input stream, normally right L4-1-1 Standard Output (cout) By default, the standard output of a program is the screen, and the stream object defined to access it is cout. cout is used in conjunction with the insertion operator, which is written as << (two "less than" signs). cout << "Output sentence"; // prints Output sentence on screen cout << 120; // prints number 120 on screen cout << x; // prints the content of x on screen The insertion operator (<<) may be used more than once in a single statement: cout << "Hello, " << "I am " << "a statement"; Additionally, to add a new-line, you may also use the endl manipulator. For example:

P-21 cout << "First sentence." << endl; cout << "Second sentence."<< endl; would print out: First sentence. Second sentence. The endl manipulator produces a newline character, exactly as the insertion of '\n' does, but it also has an additional behavior when it is used with buffered streams: the buffer is flushed. Anyway, cout will be an unbuffered stream in most cases, so you can generally use both the \n escape character and the endl manipulator in order to specify a new line without any difference in its behavior L4-1-2 Standard Input (cin). The standard input device is usually the keyboard. Handling the standard input in is done by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will store the data that is going to be extracted from the stream. For example: int age; cin >> age; char v; v= a ; Following example illustrates use of cin operator, where we input two values using cin operator and print sum and average of those values. I/P # include <iostream.h> void main () float var1, var2, sum, avg; O/P Input first Value 32.45 Input second value

P-22 cout << "Input first value" << endl; cin >> var1; cout << "Input second value" << endl; cin >> var2; sum = var1+ var2; avg = sum / 2; cout << "Sum is" << sum << endl; cout << "Average is " << avg << endl 12.76 Sum is 45.21 Average is 22.605 L4-2 Iomanip.h The iomanip is a parameterized input output manipulator. In order to access manipulators that take parameters the header file <iomanip> is included in the program. Some of the manipulators are:- setbase(int n) It sets the output representation of the number to octal, decimal or hexadecimal corresponding to the argument n which is 8 in case of octal, 10 for decimal and 16 for hexadecimal. Any other value will not change the base. setfill (char c) It sets the fill character to be the value of character c. The fill character is used in output stream for padding. setprecision(int n) It sets the precision of floating point number to n digits. setw(int n) It sets the width of the field of the next output to n characters. If the length of the output stream is less than n then spaces are padded. The no of spaces padded is the difference between n and length of the output stream. If the length of the output stream is less than n there will be no effect on output stream. Here is a program which illustrates the working of input output manipulators.

P-23 I/P #include<iostream.h> #include<iomanip.h> int main () int i=10; double a=78.121113; char c[50]; char c1='p'; cout << "Enter your name " << endl; cin >> c; cout << setw(10) << c << endl; cout << setw(15) << c << endl; cout << setprecision(5) << a << endl; cout << setprecision(7) << a << endl; cout << "Hexedecimal number : " << setbase(16) << i << endl; cout << "Octal number : " << setbase(8) << i << endl; cout << setfill(c1) << setw(12) << c << endl; cout << setfill(c1) << setw(2) << c << endl; return(0); O/P Enter your name ahmed ahmed ahmed 78.121 78.12111 Hexedecimal number : a Octal number : 12 pppppppahmed ahmed Press any key to continue The statement #include<iomanip> includes a header file iomanip into the program. The user enters then name Ahmed. The statement cout << setw(10) << c << endl; Sets the width of the string c as 10. Since the length of the name Ahmed is 3 extra spaces are added to set the width to be 10. No of spaces added are 7. The statement cout << setw(15) << c << endl;

P-24 Sets the width of string c as 15. This time more no of spaces are added. The statement cout << setprecision(5) << a << endl; Sets the precision of the floating point number a to be 5 digits. The output is 78.121 where actual floating point number is 78.121113. The statement cout << setprecision(7) << a << endl; sets the precision of the floating point number to be 7 digits. The output is 78.12111 where actual floating point number is 78.121113. The statement cout << "Hexedecimal number : " << setbase(16) << i << endl; Sets the base of the number i as hexadecimal. The value of the variable i is 10. The hexadecimal format of 10 is a. Therefore output is a. The statement cout << "Octal number : " << setbase(8) << i << endl Sets the base of the number 10 as octal. The octal format of 10 is 12 therefore it displays 12. The statement cout << setfill(c1) << setw(12) << c << endl; sets the fill character to be c1. The value of c1 is p. The statement performs the same function of setw but instead of spaces character p is padded. The length of string Ahmed is 3 therefore 9 ps are padded to set the width to be 12. The statement cout << setfill(c1) << setw(2) << c << endl; sets the fill character to be c1. Since the width of the output stream is less than the length of the string Ahmed therefore there is no effect on output.

P-25 L5_1 Operators Once we know of the existence of variables and constants, we can begin to operate with them. For that purpose, integrates operators. Unlike other languages whose operators are mainly keywords, operators in are mostly made of signs that are not part of the alphabet but are available in all keyboards. This makes code shorter and more international, since it relies less on English words, but requires a little of learning effort in the beginning. L5-1-1 Assignment (=) The assignment operator assigns a value to a variable. a = 5; The most important rule when assigning is the right-to-left rule: The assignment operation always takes place from right to left, and never the other way: a = b; This statement assigns to variable a (the lvalue) the value contained in variable b (the rvalue). The value that was stored until this moment in a is not considered at all in this operation, and in fact that value is lost. Consider also that we are only assigning the value of b to a at the moment of the assignment operation. Therefore a later change of b will not affect the new value of a. For example, let us have a look at the following code - I have included the evolution of the content stored in the variables as comments: I/P // assignment operator #include <iostream> int main () int a, b; // a:?, b:? a = 10; // a:10, b:? b = 4; // a:10, b:4 a:4 b:7 O/P

P-26 a = b // a:4, b:4 b = 7; // a:4, b:7 cout << "a:"; cout << a; cout << " b:"; cout << b; return 0; This code will give us as result that the value contained in a is 4 and the one contained in b is 7. Notice how a was not affected by the final modification of b, even though we declared a = b earlier (that is because of the right-to-left rule). A property that has over other programming languages is that the assignment operation can be used as the rvalue (or part of an rvalue) for another assignment operation. For example: a = 2 + (b = 5); is equivalent to: b = 5; a = 2 + b; that means: first assign 5 to variable b and then assign to a the value 2 plus the result of the previous assignment of b (i.e. 5), leaving a with a final value of 7. The following expression is also valid in : a = b = c = 5; It assigns 5 to the all the three variables: a, b and c. L5-1-2 Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, =) When we want to modify the value of a variable by performing an operation on the value currently stored in that variable we can use compound assignment operators: expression expression

P-27 value += increase; value = value + increase; a -= 5; a = a - 5; a /= b; a = a / b; price *= units + 1; price = price * (units + 1); and the same for all other operators. For example: I/P // compound assignment operators #include <iostream> int main () int a, b=3; a = b; a+=2; // equivalent to a=a+2 cout << a; return 0; 5 O/P L5-1-3 Arithmetic operators ( +, -, *, /, % ) The five arithmetical operations supported by the language are: + addition - subtraction * multiplication / division % modulo Operations of addition, subtraction, multiplication and division literally correspond with their respective mathematical operators. The only one that you might not be so used to see is modulo; whose operator is the percentage sign (%). Modulo is the operation that gives the remainder of a division of two values. For example, if we write: a = 11 % 3; // o/p= 2 the variable a will contain the value 2, since 2 is the remainder from dividing 11 between 3.

P-28 L5-1-4 Increase and decrease (++, --) Shortening even more some expressions, the increase operator (++) and the decrease operator (--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus: c++; c+=1; c=c+1; are all equivalent in its functionality: the three of them increase by one the value of c. A characteristic of this operator is that it can be used both as a prefix and as a suffix. That means that it can be written either before the variable identifier (++a) or after it (a++). Although in simple expressions like a++ or ++a both have exactly the same meaning, in other expressions in which the result of the increase or decrease operation is evaluated as a value in an outer expression they may have an important difference in their meaning: In the case that the increase operator is used as a prefix (++a) the value is increased before the result of the expression is evaluated and therefore the increased value is considered in the outer expression; in case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the outer expression. Notice the difference: B=3; A=++B; B=3; A=B++; Example 1 O/P Example 2 O/P A contains 4, B contains 4 A contains 3, B contains 4

P-29 L5-1-5 Relational and equality operators (==,!=, >, <, >=, <= ) In order to evaluate a comparison between two expressions we can use the relational and equality operators. The result of a relational operation is a Boolean value that can only be true or false, according to its Boolean result. We may want to compare two expressions, for example, to know if they are equal or if one is greater than the other is. Here is a list of the relational and equality operators that can be used in : == Equal to!= Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to Here there are some examples: (7 == 5) // evaluates to false. (5 > 4) // evaluates to true. (3!= 2) // evaluates to true. (6 >= 6) // evaluates to true. (5 < 5) // evaluates to false. Of course, instead of using only numeric constants, we can use any valid expression, including variables. Suppose that a=2, b=3 and c=6, (a == 5) //evaluates to false since a is not equal to 5. (a*b >= c) // evaluates to true since (2*3 >= 6) is true. (b+4 > a*c) //evaluates to false since (3+4 > 2*6) is false. ((b=2) == a) // evaluates to true. L5-1-6 Logical operators (!, &&, )

P-30 The Operator! is the operator to perform the Boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. For example:!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true.!(6 <= 4) // evaluates to true because (6 <= 4) would be false.!true // evaluates to false!false // evaluates to true. The logical operators && and are used when evaluating two expressions to obtain a single relational result. The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true, and false otherwise. The following panel shows the result of operator && evaluating the expression a && b: && OPERATOR a b a && b true true true true false false false true false false false false The operator corresponds with Boolean logical operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves. Here are the possible results of a b: OPERATOR For example: a b a && b true true true true false true false true true false false false ( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ). ( (5 == 5) (3 > 6) ) // evaluates to true ( true false ).

P-31 L5-1-7 Conditional operator (? ) The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false. Its format is: condition? result1 : result2 If condition is true the expression will return result1, if it is not it will return result2. 7==5? 4 : 3 // returns 3, since 7 is not equal to 5. 7==5+2? 4 : 3 // returns 4, since 7 is equal to 5+2. 5>3? a : b // returns the value of a, since 5 is greater than 3. a>b? a : b // returns whichever is greater, a or b. I/P // conditional operator #include <iostream> int main () int a,b,c; a=2; b=7; c = (a>b)? a : b; cout << c; return 0; 7 In this example a was 2 and b was 7, so the expression being evaluated (a>b) was not true, thus the first value specified after the question mark was discarded in favor of O/P the second value (the one after the colon) which was b, with a value of 7. L5-1-8 Comma operator (, ) The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.

P-32 For example, the following code: a = (b=3, b+2); Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would contain the value 5 while variable b would contain value 3. L5-1-9 Bitwise Operators ( &,, ^, ~, <<, >> ) Bitwise operators modify variables considering the bit patterns that represent the values they store. operator asm equivalent description & AND Bitwise AND OR Bitwise Inclusive OR ^ XOR Bitwise Exclusive OR ~ NOT Unary complement (bit inversion) << SHL Shift Left >> SHR Shift Right L5-2 Precedence of operators When writing complex expressions with several operands, we may have some doubts about which operand is evaluated first and which later. For example, in this expression: a = 5 + 7 % 2 we may doubt if it really means: a = 5 + (7 % 2) // with a result of 6, or a = (5 + 7) % 2 // with a result of 0

P-33 The correct answer is the first of the two expressions, with a result of 6. There is an established order with the priority of each operator, and not only the arithmetic ones (those whose preference come from mathematics) but for all the operators which can appear in. From greatest to lowest priority, the priority order is as follows: 3 ++ -- ~! sizeof new delete unary (prefix) * & indirection and reference (pointers) + - unary sign operator Level Operator Description Grouping 1 :: scope Left-toright 2 () []. -> ++ -- dynamic_cast static_cast reinterpret_cast const_cast typeid postfix Left-toright Right-toleft 4 (type) type casting Right-toleft 5.* ->* pointer-to-member Left-toright 6 * / % multiplicative Left-toright 7 + - additive Left-toright 8 << >> shift Left-toright 9 < > <= >= relational Left-toright 10 ==!= equality Left-toright 11 & bitwise AND Left-toright 12 ^ bitwise XOR Left-to-

P-34 right 13 bitwise OR Left-toright 14 && logical AND Left-toright 15 logical OR Left-toright 16?: conditional Right-toleft 17 = *= /= %= += -= >>= <<= &= ^= = assignment Right-toleft 18, comma Left-toright L6-1 Control flow introduction When a program is run, the CPU begins execution at the top of main(), executes some number of statements, and then terminates at the end of main(). The sequence of statements that the CPU executes is called the program s path. Most of the programs you have seen so far have been straight-line programs. Straight-line programs have sequential flow that is, they take the same path (execute the same statements) every time they are run (even if the user input changes). However, often this is not what we desire. For example, if we ask the user to make a selection, and the user enters an invalid choice, ideally we d like to ask the user to make another choice. This is not possible in a straight-line program. Fortunately, provides control flow statements (also called flow control statements), which allow the programmer to change the CPU s path through the program. There are quite a few different types of control flow statements, so we will cover them briefly here, and then in more detail throughout the rest of the section. L6-1-1 Conditional branches

P-35 A conditional branch is a statement that causes the program to change the path of execution based on the value of an expression. The most basic conditional branch is an if statement, which you have seen in previous examples. Consider the following program: If statements The most basic kind of conditional branch in is the if statement. An if statement takes the form: if (expression) statement or if (expression) statement else statement2 If the expression evalutes to true (non-zero), the statement executes. If the expression evaluates to false, the else statement is executed if it exists. Here is a simple program that uses an if statement to check then number is smallest or largest then 10 number : #include <iostream.h> int main() using namespace std; cout << "Enter a number: "; int nx; cin >> nx; if (nx > 10) else cout << nx << "is greater than 10" << endl;

P-36 cout << nx << "is not greater than 10" << endl; return 0; Note that the if statement only executes a single statement if the expression is true, and the else only executes a single statement if the expression is false. In order to execute multiple statements, we can use a block: if (grade > 70 && grade < 80) cout << " you passed "; cout << " very good"; Nested if It is also possible to nest if statements within other if statements: Here is a simple program to input the grade of the student then check it and output the result. Grade Result G<50 Failed G<60 Acceptance G<70 median G<80 good G<90 Very good G<=100 Excellent #include <iostream> using namespace std; int main()

P-37 int grade; // from 0 to 100 char letter_grade = 'Z'; // A, B, C, D, F, or Z cout << "Enter Your Number Score:" << endl; cin >> grade; if (grade == 100) cout << " First in Class!\n"; letter_grade = 'A'; else if (grade >= 90 && grade < 100) cout << " Congratulations!\n"; letter_grade = 'A'; else if (grade >= 80 && grade < 90) cout << " Very Good\n"; letter_grade = 'B'; else if (grade >= 70 && grade < 80) cout << " good\n"; letter_grade = 'C'; else if (grade >= 60 && grade < 70) cout << " medium\n"; letter_grade = 'D'; else if (grade >= 50 && grade < 60) cout << " acceptance\n"; letter_grade = 'E'; else if (grade >= 0 && grade < 50) cout << " Sorry you failed\n"; letter_grade = 'F'; else cout << " Not a recognizable grade" << endl; cout << " Your grade was " << letter_grade << endl;

P-38 The switch Statement The switch statement is a multiway conditional statement generalizing the if-else statement. The general form of the switch statement is given by switch (expression) case constant1: group of statements 1; break; case constant2: group of statements 2; break;... default: default group of statements where statement is typically a compound statement containing case labels, and optionally a default label. Typically, a switch is composed of many cases, and the condition in parentheses following the keyword switch determines which, if any, of the cases are executed. Both of the following code fragments have the same behavior: switch example if-else equivalent int x; int x; cin>>x; cin>>x; switch (x) if (x == 1) case 1: cout << "x is 1"; cout << "x is 1"; break; else if (x == 2) case 2: cout << "x is 2"; cout << "x is 2"; break; else

P-39 default: cout << "value of x unknown"; cout << "value of x unknown"; The same program existing in page-35 can be solved using switch statement. // Program for printing out grade meanings #include <iostream.h> int main() int grade; // from 0 to 100 char letter_grade = 'Z'; // A, B, C, D, F, or Z cout << "Enter Your Number Score:" << endl; cin >> grade; grade = (grade > 100)? -1 : grade; switch (grade/10) case 10: cout << " First in Class!\n"; letter_grade = 'A'; break; case 9: cout << " Congratulations!\n"; letter_grade = 'A'; break; case 8: cout << " Very Good\n"; letter_grade = 'B'; break; case 7: cout << " Good\n"; letter_grade = 'C'; break; case 6: cout << " Medium\n";

P-40 letter_grade = 'D'; break; case 5: cout << " Acceptance\n"; letter_grade = 'E'; break; case 4: case 3: case 2: case 1: case 0: cout << " Sorry you failed\n"; letter_grade = 'F'; break; default: cout << " Not a recognizable grade" << endl; cout << "Your grade was " << letter_grade << endl; L6-1-2 Loops A loop causes the program to repeatedly execute a series of statements until a given condition is false.

P-41 for loop Its main function is to repeat statement while condition remains true, like the while loop. But in addition, the for loop provides specific locations to contain an initialization statement and an increase statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration. Its format is: for (initialization; condition; increase) statement It works in the following way: 1. initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once. 2. condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed). 3. statement is executed. As usual, it can be either a single statement or a block enclosed in braces. 4. finally, whatever is specified in the increase field is executed and the loop gets back to step 2. Here is an example of print numbers between 1 to 10 using a for loop: I/P O/P #include <iostream.h> 1,2,3,4,5,6,7,8,9,10,OK void main() for (int i = 1; i <= 10; i++) cout<<i<<, ; cout << " OK << endl; Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a for loop, like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression

P-42 where only one is generally expected. For example, suppose that we wanted to initialize more than one variable in our loop: 1 for ( n=0, i=100 ; n!=i ; n++, i-- ) 2 3 // whatever here... 4 This loop will execute for 50 times if neither n or i are modified within the loop: n starts with a value of 0, and i with 100, the condition is n!=i (that n is not equal to i). Because n is increased by one and i decreased by one, the loop's condition will become false after the 50th loop, when both n and i will be equal to 50. The while Statement The general form of a while statement is while (condition) statement First, condition is evaluated. If it is true, statement is executed, and control passes back to the beginning of the while loop. The result: The body of the while loop, namely, statement, is executed repeatedly until condition is false. At that point, control passes to the next statement. In this way, statement can be executed zero or more times. Example// custom countdown using while I/P O/P

P-43 #include <iostream.h> int main () int n; cout << "Enter the starting number > "; cin >> n; while (n>0) cout << n << ", "; --n; cout << "FIRE!\n"; return 0; Enter the starting number > 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE! When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true. The whole process of the previous program can be interpreted according to the following script (beginning in main): 1. User assigns a value to n 2. The while condition is checked (n>0). At this point there are two possibilities: * condition is true: statement is executed (to step 3) * condition is false: ignore statement and continue after it (to step 5) 3. Execute statement: cout << n << ", "; --n; (prints the value of n on the screen and decreases n by 1) 4. End of block. Return automatically to step 2 5. Continue the program right after the block: print FIRE! and end program.