Second Class Control and Systems Engineering

Size: px
Start display at page:

Download "Second Class Control and Systems Engineering"

Transcription

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

2 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)

3 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,

4 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.

5 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.

6 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>

7 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;

8 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

9 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

10 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)

11 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: to 32767

12 P-10 (short) unsigned: 0 to int Integer. 4bytes signed: to unsigned: 0 to long int (long) Long integer. 4bytes signed: to unsigned: 0 to 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;

13 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 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.

14 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

15 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

16 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

17 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 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:

18 P // 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: // e23 // 6.02 x 10^23 1.6e-19 // 1.6 x 10^ // 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: L // 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.

19 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'

20 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 #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 #define NEWLINE '\n' int main () double r=5.0; // radius double circle; circle = 2 * PI * r; cout << circle; O/P

21 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.

22 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:

23 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 Input second value

24 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 Sum is Average is 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.

25 P-23 I/P #include<iostream.h> #include<iomanip.h> int main () int i=10; double a= ; 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 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;

26 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 where actual floating point number is The statement cout << setprecision(7) << a << endl; sets the precision of the floating point number to be 7 digits. The output is where actual floating point number is 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.

27 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

28 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

29 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.

30 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

31 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 (!, &&, )

32 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 ).

33 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 >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.

34 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 = % 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

35 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: ~! 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 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-

36 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

37 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;

38 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()

39 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;

40 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

41 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";

42 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.

43 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

44 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

45 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.

C++ Language Tutorial

C++ Language Tutorial cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain

More information

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

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

6. Control Structures

6. Control Structures - 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,

More information

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

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

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

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from

More information

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

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T) Unit- I Introduction to c Language: C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating

More information

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

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

Sequential Program Execution

Sequential Program Execution Sequential Program Execution Quick Start Compile step once always g++ -o Realtor1 Realtor1.cpp mkdir labs cd labs Execute step mkdir 1 Realtor1 cd 1 cp../0/realtor.cpp Realtor1.cpp Submit step cp /samples/csc/155/labs/1/*.

More information

Chapter One Introduction to Programming

Chapter One Introduction to Programming Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of

More information

Pemrograman Dasar. Basic Elements Of Java

Pemrograman Dasar. Basic Elements Of Java Pemrograman Dasar Basic Elements Of Java Compiling and Running a Java Application 2 Portable Java Application 3 Java Platform Platform: hardware or software environment in which a program runs. Oracle

More information

Comp151. Definitions & Declarations

Comp151. Definitions & Declarations Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const

More information

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

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

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

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral

More information

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

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: istream

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer About The Tutorial C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system.

More information

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

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

13 Classes & Objects with Constructors/Destructors

13 Classes & Objects with Constructors/Destructors 13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.

More information

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

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

The programming language C. sws1 1

The programming language C. sws1 1 The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan

More information

C++ Programming Language

C++ Programming Language C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

More information

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.

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. LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

C++ Essentials. Sharam Hekmat PragSoft Corporation www.pragsoft.com

C++ Essentials. Sharam Hekmat PragSoft Corporation www.pragsoft.com C++ Essentials Sharam Hekmat PragSoft Corporation www.pragsoft.com Contents Contents Preface 1. Preliminaries 1 A Simple C++ Program 2 Compiling a Simple C++ Program 3 How C++ Compilation Works 4 Variables

More information

JavaScript: Control Statements I

JavaScript: Control Statements I 1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can

More information

Objective-C Tutorial

Objective-C Tutorial Objective-C Tutorial OBJECTIVE-C TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i ABOUT THE TUTORIAL Objective-c tutorial Objective-C is a general-purpose, object-oriented programming

More information

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

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

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

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand: Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of

More information

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

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

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

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands C Programming for Embedded Microcontrollers Warwick A. Smith Elektor International Media BV Postbus 11 6114ZG Susteren The Netherlands 3 the Table of Contents Introduction 11 Target Audience 11 What is

More information

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

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

I PUC - Computer Science. Practical s Syllabus. Contents

I PUC - Computer Science. Practical s Syllabus. Contents I PUC - Computer Science Practical s Syllabus Contents Topics 1 Overview Of a Computer 1.1 Introduction 1.2 Functional Components of a computer (Working of each unit) 1.3 Evolution Of Computers 1.4 Generations

More information

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

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 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 preceded by an equal sign d. its name has undereline 2. Associations

More information

Syllabus OBJECT ORIENTED PROGRAMMING C++

Syllabus OBJECT ORIENTED PROGRAMMING C++ 1 Syllabus OBJECT ORIENTED PROGRAMMING C++ 1. Introduction : What is object oriented programming? Why do we need objectoriented. Programming characteristics of object-oriented languages. C and C++. 2.

More information

VB.NET Programming Fundamentals

VB.NET Programming Fundamentals Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

More information

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

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

More information

Numbering Systems. InThisAppendix...

Numbering Systems. InThisAppendix... G InThisAppendix... Introduction Binary Numbering System Hexadecimal Numbering System Octal Numbering System Binary Coded Decimal (BCD) Numbering System Real (Floating Point) Numbering System BCD/Binary/Decimal/Hex/Octal

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

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

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, 2008. 1 Introduction 1. 2 Invoking Shell Scripts 2 Unix Shell Scripts Norman Matloff July 30, 2008 Contents 1 Introduction 1 2 Invoking Shell Scripts 2 2.1 Direct Interpretation....................................... 2 2.2 Indirect Interpretation......................................

More information

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

An Incomplete C++ Primer. University of Wyoming MA 5310 An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

More information

Computer Science 281 Binary and Hexadecimal Review

Computer Science 281 Binary and Hexadecimal Review Computer Science 281 Binary and Hexadecimal Review 1 The Binary Number System Computers store everything, both instructions and data, by using many, many transistors, each of which can be in one of two

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

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

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be... What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

C PROGRAMMING FOR MATHEMATICAL COMPUTING

C PROGRAMMING FOR MATHEMATICAL COMPUTING UNIVERSITY OF CALICUT SCHOOL OF DISTANCE EDUCATION BSc MATHEMATICS (2011 Admission Onwards) VI Semester Elective Course C PROGRAMMING FOR MATHEMATICAL COMPUTING QUESTION BANK Multiple Choice Questions

More information

Basics of I/O Streams and File I/O

Basics of I/O Streams and File I/O Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading

More information

El Dorado Union High School District Educational Services

El Dorado Union High School District Educational Services El Dorado Union High School District Course of Study Information Page Course Title: ACE Computer Programming II (#495) Rationale: A continuum of courses, including advanced classes in technology is needed.

More information

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

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 First CGI Script and Perl Perl in a nutshell Prof. Rasley shebang line tells the operating system where the Perl interpreter is located necessary on UNIX comment line ignored by the Perl interpreter End

More information

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

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements 9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

More information

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE PROGRAMMING IN C CONTENT AT A GLANCE 1 MODULE 1 Unit 1 : Basics of Programming Unit 2 : Fundamentals Unit 3 : C Operators MODULE 2 unit 1 : Input Output Statements unit 2 : Control Structures unit 3 :

More information

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

ASSEMBLY LANGUAGE PROGRAMMING (6800) (R. Horvath, Introduction to Microprocessors, Chapter 6) ASSEMBLY LANGUAGE PROGRAMMING (6800) (R. Horvath, Introduction to Microprocessors, Chapter 6) 1 COMPUTER LANGUAGES In order for a computer to be able to execute a program, the program must first be present

More information

Programming languages C

Programming languages C INTERNATIONAL STANDARD ISO/IEC 9899:1999 TECHNICAL CORRIGENDUM 2 Published 2004-11-15 INTERNATIONAL ORGANIZATION FOR STANDARDIZATION МЕЖДУНАРОДНАЯ ОРГАНИЗАЦИЯ ПО СТАНДАРТИЗАЦИИ ORGANISATION INTERNATIONALE

More information

Appendix K Introduction to Microsoft Visual C++ 6.0

Appendix K Introduction to Microsoft Visual C++ 6.0 Appendix K Introduction to Microsoft Visual C++ 6.0 This appendix serves as a quick reference for performing the following operations using the Microsoft Visual C++ integrated development environment (IDE):

More information

Chapter 5. Selection 5-1

Chapter 5. Selection 5-1 Chapter 5 Selection 5-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

More information

Chapter 2: Elements of Java

Chapter 2: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

More information

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

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points

More information

Variables, Constants, and Data Types

Variables, Constants, and Data Types Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class: L&L, 2.1-2.3, App C 1 Primitive Data There are eight

More information

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

Curriculum Map. Discipline: Computer Science Course: C++ Curriculum Map Discipline: Computer Science Course: C++ August/September: How can computer programs make problem solving easier and more efficient? In what order does a computer execute the lines of code

More information

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

JavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved. 1 6 JavaScript: Introduction to Scripting 2 Comment is free, but facts are sacred. C. P. Scott The creditor hath a better memory than the debtor. James Howell When faced with a decision, I always ask,

More information

arrays C Programming Language - Arrays

arrays C Programming Language - Arrays arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)

More information

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

So far we have considered only numeric processing, i.e. processing of numeric data represented Chapter 4 Processing Character Data So far we have considered only numeric processing, i.e. processing of numeric data represented as integer and oating point types. Humans also use computers to manipulate

More information

Glossary of Object Oriented Terms

Glossary of Object Oriented Terms Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction

More information

Windows PowerShell Essentials

Windows PowerShell Essentials Windows PowerShell Essentials Windows PowerShell Essentials Edition 1.0. This ebook is provided for personal use only. Unauthorized use, reproduction and/or distribution strictly prohibited. All rights

More information

How To Write Portable Programs In C

How To Write Portable Programs In C Writing Portable Programs COS 217 1 Goals of Today s Class Writing portable programs in C Sources of heterogeneity Data types, evaluation order, byte order, char set, Reading period and final exam Important

More information

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

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C 1 An essential part of any embedded system design Programming 2 Programming in Assembly or HLL Processor and memory-sensitive

More information

Member Functions of the istream Class

Member Functions of the istream Class Member Functions of the istream Class The extraction operator is of limited use because it always uses whitespace to delimit its reads of the input stream. It cannot be used to read those whitespace characters,

More information

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

Introduction to Visual C++.NET Programming. Using.NET Environment ECE 114-2 Introduction to Visual C++.NET Programming Dr. Z. Aliyazicioglu Cal Poly Pomona Electrical & Computer Engineering Cal Poly Pomona Electrical & Computer Engineering 1 Using.NET Environment Start

More information

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

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information

10CS35: Data Structures Using C

10CS35: Data Structures Using C CS35: Data Structures Using C QUESTION BANK REVIEW OF STRUCTURES AND POINTERS, INTRODUCTION TO SPECIAL FEATURES OF C OBJECTIVE: Learn : Usage of structures, unions - a conventional tool for handling a

More information

Formatting Numbers with C++ Output Streams

Formatting Numbers with C++ Output Streams Formatting Numbers with C++ Output Streams David Kieras, EECS Dept., Univ. of Michigan Revised for EECS 381, Winter 2004. Using the output operator with C++ streams is generally easy as pie, with the only

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

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

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics

More information

Introduction to Python

Introduction to Python Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment

More information

Passing 1D arrays to functions.

Passing 1D arrays to functions. Passing 1D arrays to functions. In C++ arrays can only be reference parameters. It is not possible to pass an array by value. Therefore, the ampersand (&) is omitted. What is actually passed to the function,

More information

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

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2). CHAPTER 5 The Tree Data Model There are many situations in which information has a hierarchical or nested structure like that found in family trees or organization charts. The abstraction that models hierarchical

More information

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

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies) Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies) Duration of Course: 6 Months Fees: Rs. 25,000/- (including Service Tax) Eligibility: B.E./B.Tech., M.Sc.(IT/ computer

More information

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

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

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

A Programming Language for Mechanical Translation Victor H. Yngve, Massachusetts Institute of Technology, Cambridge, Massachusetts [Mechanical Translation, vol.5, no.1, July 1958; pp. 25-41] A Programming Language for Mechanical Translation Victor H. Yngve, Massachusetts Institute of Technology, Cambridge, Massachusetts A notational

More information

Computer Programming Tutorial

Computer Programming Tutorial Computer Programming Tutorial COMPUTER PROGRAMMING TUTORIAL by tutorialspoint.com tutorialspoint.com i ABOUT THE TUTORIAL Computer Prgramming Tutorial Computer programming is the act of writing computer

More information

1 Abstract Data Types Information Hiding

1 Abstract Data Types Information Hiding 1 1 Abstract Data Types Information Hiding 1.1 Data Types Data types are an integral part of every programming language. ANSI-C has int, double and char to name just a few. Programmers are rarely content

More information

MATLAB Programming. Problem 1: Sequential

MATLAB Programming. Problem 1: Sequential Division of Engineering Fundamentals, Copyright 1999 by J.C. Malzahn Kampe 1 / 21 MATLAB Programming When we use the phrase computer solution, it should be understood that a computer will only follow directions;

More information

Section 1.4 Place Value Systems of Numeration in Other Bases

Section 1.4 Place Value Systems of Numeration in Other Bases Section.4 Place Value Systems of Numeration in Other Bases Other Bases The Hindu-Arabic system that is used in most of the world today is a positional value system with a base of ten. The simplest reason

More information

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

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1 QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For

More information

Exercise 4 Learning Python language fundamentals

Exercise 4 Learning Python language fundamentals Exercise 4 Learning Python language fundamentals Work with numbers Python can be used as a powerful calculator. Practicing math calculations in Python will help you not only perform these tasks, but also

More information

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

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The

More information

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

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]

More information

Base Conversion written by Cathy Saxton

Base Conversion written by Cathy Saxton Base Conversion written by Cathy Saxton 1. Base 10 In base 10, the digits, from right to left, specify the 1 s, 10 s, 100 s, 1000 s, etc. These are powers of 10 (10 x ): 10 0 = 1, 10 1 = 10, 10 2 = 100,

More information

Chapter 5 Names, Bindings, Type Checking, and Scopes

Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Type Checking Strong Typing Scope Scope and Lifetime Referencing Environments Named

More information

Lecture 22: C Programming 4 Embedded Systems

Lecture 22: C Programming 4 Embedded Systems Lecture 22: C Programming 4 Embedded Systems Today s Goals Basic C programming process Variables and constants in C Pointers to access addresses Using a High Level Language High-level languages More human

More information

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

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 Lecture 3 Data structures arrays structs C strings: array of chars Arrays as parameters to functions Multiple subscripted arrays Structs as parameters to functions Default arguments Inline functions Redirection

More information

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

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Example Assume the following specification: Input: read a number N > 0 Output:

More information

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

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification: Example Introduction to Programming (in C++) Loops Assume the following specification: Input: read a number N > 0 Output: write the sequence 1 2 3 N (one number per line) Jordi Cortadella, Ricard Gavaldà,

More information

1 Description of The Simpletron

1 Description of The Simpletron Simulating The Simpletron Computer 50 points 1 Description of The Simpletron In this assignment you will write a program to simulate a fictional computer that we will call the Simpletron. As its name implies

More information

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

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information