Data Structure Lab. Prepared By Dr. Hanan Ahmed Salman

Size: px
Start display at page:

Download "Data Structure Lab. Prepared By Dr. Hanan Ahmed Salman"

Transcription

1 Ministry of Higher Education and Scientific Research Al-Mustansiriyah University وزارة التعليم العالي والبحث الجامعة المستنصرية كلية الهندسة قسم هندسة الحاسوب العلمي Data Structure Lab. Prepared By Dr. Hanan Ahmed Salman

2 Experiment No. (1) Introduction to C++ Basic Programming Language Object: To give a general introduction to computer programming, programming languages, and simple programs in C++ language. Theory: A computer program is a set of instructions that a programmer writes to tell a computer how to carry out a certain task. The instructions, however, must be in a language that the computer understands. Computers only understand a binary language i.e. that composed of 1 s and 0 s. This is a low-level language and very hard to program in. So, humans invented higher level languages such as C++ or Pascal to make the job easier. As you will see, these languages are nearly like English but you don t have the freedom to write what you like there are still rules you have to follow. As shown in below, the input to a computer can be thought of as consisting of two parts, a program and some data. The computer follows the instructions in the program, and in that way, performs some process. The data is what we conceptualize as the input to the program. For example, if the program adds two numbers, then the two numbers are the data. In other words, the data is the input to the program, and both the program and the data are input to the computer. 1

3 Languages: High, low level and assembly C++ is a high-level language, like most of the other programming languages such as C, Java, Pascal, Visual Basic, FORTRAN, COBOL, Lisp, Scheme, and Ada. High-level languages resemble human languages in many ways. They are designed to be easy for human beings to write programs in and to be easy for human beings to read. A highlevel language contains instructions that are much more complicated than the simple instructions a computer s processor (CPU) is capable of following. The kind of language a computer can understand is called a low-level language. The exact details of low-level languages differ from one kind of computer to another. A typical low-level instruction might be the following: ADD X Y Z This instruction might mean Add the number in the memory location called X to the number in the memory location called Y, and place the result in the memory location called Z. The above sample instruction is written in what is called assembly language. Although assembly 2

4 language is almost the same as the language understood by the computer, it must undergo one simple translation before the computer can understand it. In order to get a computer to follow an assembly language instruction, the words need to be translated into strings of zeros and ones. For example, the word ADD might translate to 0110, the X might translate to 1001, the Y to 1010, and the Z to The version of the above instruction that the computer ultimately follows would then be: Assembly language instructions and their translation into zeros and ones differ from machine to machine. Programs written in the form of zeros and ones are said to be written in machine language, because that is the version of the program that the computer (the machine) actually reads and follows. 3

5 Editor: accepts the typing of the source code (or header file). Source file: the file that contains the program you prepared in the editor after you save it. (.cpp) Header file: header files such as iostream.h Pre-processor: performs preliminary operations on files before they are passed to the compiler. Compiler: translates the source code to machine language. Object code: the file containing the translated source code. (.obj) Linker: links the object file with additional code, such as the library codes. Executable code: the file containing the final product. (.exe) PROGRAMMING AND PROBLEM-SOLVING The most difficult part of solving a problem on a computer is discovering the method of solution. After you come up with a method of solution, it is routine to translate your method into the required language, be it C++ or some other programming language. A sequence of precise instructions which leads to a solution is called an algorithm. A computer program is simply an algorithm expressed in a language that a computer can understand. Thus, the term algorithm is more general than the term program.designing a program is often a difficult task. There is no complete set of rules, no algorithm to tell you how to write programs. Program design is a creative process. The entire program design process can be divided into two phases, the problem-solving phase and the implementation phase. The result of the 4

6 problem-solving phase is an algorithm, expressed in English, for solving the problem. To produce a program in a programming language such as C++, the algorithm is translated into the programming language. Producing the final program from the algorithm is called the implementation phase. Program 1: Probably the best way to start learning a programming language is by writing a program. Therefore, here is our first program: // my first program in C++ Hello World! #include <iostream.h> int main () cout << "Hello World!"; return 0; 5

7 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 way to edit and compile a program depends on the compiler you are using. // my first program in C++ 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.h> Lines beginning with a pound 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 C++, 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 C++ programs start their execution, independently of its location within the source code. It does not matter whether there are other 6

8 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 C++ program. For that same reason, it is essential that all C++ 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 C++, 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 C++ 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 C++, 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 7

9 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 C++ programs (one of the most common syntax errors is indeed to forget to include some semicolon after a statement). return 0; 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 as expected without any errors during its execution. This is the most usual way to end a C++ program. You may have noticed that not all the lines of this program perform actions when the code is executed. There were lines containing only comments (those beginning by //). There were lines with directives for the compiler's preprocessor (those beginning by #). Then there were lines that began the declaration of a function (in this case, the main function) and, finally lines with statements (like the insertion into cout), which were all included within the block delimited by the braces () of the main function. 8

10 Comments Comments are parts of the source code disregarded by the compiler. They simply do nothing. Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code. C++ supports two ways to insert comments: // line comment /* block comment */ The first of them, known as line comment, discards everything from where the pair of slash signs (//) is found up to the end of that same line. The second one, known as block comment, discards everything between the /* characters and the first appearance of the */ characters, with the possibility of including more than one line. Program 2 We are going to add comments to our second program: /* my second program in C++ with more comments */ Hello World! I'm a C++ program #include <iostream.h> int main () cout << "Hello World! "; // prints Hello World! cout << "I'm a C++ program"; // prints I'm a C++ program return 0; If you include comments within the source code of your programs without using the comment characters combinations //, /* or */, the 9

11 compiler will take them as if they were C++ expressions, most likely causing one or several error messages when you compile it. Questions: 1- Write a C++ program that prints a message Welcome to the first your lesson. 2- Write a C++ program that prints your name and your class number. For example:- Ali 1 st Class 10

12 Experiment No. (2) Variables and Data Types Object: Programming is not limited only to print simple texts on the screen. In order to be able to write programs that perform useful tasks that really save us work, we need to introduce the concept of variables and data types. Theory: Let us think that we ask you to retain the number 5 in your mental memory, and then ask you to memorize the number 2 at the same time. You have just stored two different values in your memory. Now, if we ask you to add 1 to the first number, you should be retaining the numbers 6 (that is 5+1) and 2 in your memory. Now for example, we could subtract and obtain 4 as result. The whole process that you have just done with your mental memory is a simile of what a computer can do with two variables. The same process can be expressed in C++ with the following instruction set: a = 5; b = 2; a = a + 1; result = a - b; Obviously, this is a very simple example since we have only used two small integer values, but consider that your computer can store millions of numbers like these at the same time and conduct sophisticated mathematical operations with them. 11

13 Therefore, we can define a variable as a portion of memory to store a determined value. Each variable needs an identifier that distinguishes it from the others, for example, in the previous code the variable identifiers were a, b and result, but we could have called the variables any names we wanted to invent, as long as they were valid identifiers. Identifiers Symbolic names can be used in C++ for various data items used by a programmer. A symbolic name is generally known as an identifier. The identifier is a sequence of characters taken from C++ character set. The rules for the formation of an identifier are: An identifier can consist of alphabets, digits and/or underscores. It must not start with a digit C++ is case sensitive that is upper case and lower case letters are considered different from each other. It should not be a reserved word. Another rule that you have to consider when inventing your own identifiers is that they cannot match any keyword of the C++ language or your compiler's specific ones since they could be confused with these. The standard reserved keywords are: asm auto break case catch char class const continue default delete do double else enum 12

14 extern inline Int float for friend goto If long new operator private protected public register return short signed sizeof static struct switch template this Try typedef union unsigned virtual void volatile while When programming, we store the variables in our computer's memory. But the computer has to know what 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 C++. 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 C++, as well as the range of values that can be represented with each one: 13

15 Name Description Size* Range* char Character or small integer. 1byte signed: -128 to 127 unsigned: 0 to 255 short (short) int signed: to Short Integer. 2bytes unsigned: 0 to signed: to int Integer. 4bytes unsigned: 0 to long (long) int Long integer. signed: to 4bytes 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 8bytes 1.7e +/- 308 (15 digits) number. wchar_t Wide character. 2bytes 1 wide character * The values of the columns Size and Range depend on the architecture of the system where the program is compiled and executed. Declaration of variables In order to use a variable in C++, we must first declare it specifying which data type we want it to be. The syntax to declare a new variable is to write the desired data type (e.g. int, bool, float...) followed by a valid variable identifier. For example: 14

16 int a; float mynumber; These are two valid declarations of variables. The first one declares a variable of type int with the identifier a. The second one declares a variable of type float with the identifier mynumber. Once declared, the variables a and mynumber can be used within the rest of their scope in the program. If you are going to declare more than one variable of the same type, you can declare all of them in a single statement by separating their identifiers with commas. For example: int a, b, c; This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning as: int a; int b; int c; The integer data types char, short, long and int can be either signed or unsigned depending on the range of numbers needed to be represented. Signed types can represent both positive and negative values, whereas unsigned types can only represent positive values (and zero). This can be specified by using either the specified signed or the specified unsigned before the type name. For example: unsigned short int Number; signed int MyAccount; 15

17 By default, if we do not specify either signed or unsigned most compiler settings will assume the type to be signed, therefore instead of the second declaration above we could have written: int MyAccount; with exactly the same meaning (with or without the keyword signed) An exception to this general rule is the char type, which exists by itself and is considered a different fundamental data type from signed char and unsigned char, thought to store characters. You should use either signed or unsigned if you intend to store numerical values in a char-sized variable. short and long can be used alone as type of specifies. In this case, they refer to their respective integer fundamental types: short is equivalent to short int and long is equivalent to long int. The following two variable declarations are equivalent: short Year; short int Year; Finally, signed and unsigned may also be used as standalone type specifies, meaning the same as signed int and unsigned int respectively. The following two declarations are equivalent: unsigned NextYear; unsigned int NextYear; 16

18 Program 1 To see what variable declarations look like in action within a program, we are going to see the C++ code of the example about your mental memory proposed at the beginning of this section: // operating with variables 4 #include <iostream.h> 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; // terminate the program: return 0; 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 C++: 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: 17

19 type identifier = initial_value ; For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in which it is declared, we could write: 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 C++. Program 2 // initialization of variables 6 #include <iostream.h> 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; 18

20 Variable Scope Scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables. We will learn what a function is and it's parameter in subsequent chapters. Here, let us explain what local and global variables are. Local Variables: Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables. Program 3 #include<iostream.h> int main () // Local variable declaration: int a, b; int c; // actual initialization a =10; b =20; c = a + b; cout << c; return0; 30 19

21 Global Variables: Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables. Program 4 #include<iostream.h> 40 // Global variable declaration: int g=10; int main () // Local variable declaration: int a, b, c; // actual initialization a =10; b =20; c = a + b+ g; cout << c; return0; 20

22 A program can have same name for local and global variables but value of local variable inside a function will take preference. Program 5 #include<iostream.h> 10 // Global variable declaration: int g=20; int main () // Local variable declaration: int g =10; cout << g; return0; Questions: 1- Write a C++ program that computes the z value from the following equations: a- z= a(b*d)-(c*b)+d where a=10, b=20, c=14, and d= 5 b- z=1/x+1/x 2 +1/x 3 where x=2 2- Write a C++ program that prints a temperature in Celsius when a Fahrenheit is given. Use the formula: C 0 =5/9(F-32) 21

23 Experiment No. (3) String and Constant Object: How defining and using stream of characters and constant in the program. Theory: Variables that can store non-numerical values that are longer than one single character are known as strings. The C++ language library provides support for strings through the standard string class. This is not a fundamental type, but it behaves in a similar way as fundamental types do in its most basic usage. A first difference with fundamental data types is that in order to declare and use objects (variables) of this type we need to include an additional header file in our source code: <string> and have access to the std namespace (which we already had in all our previous programs thanks to the using namespace statement). Program 1 // my first string #include <iostream.h> #include <string.h> This is a string int main () string mystring = "This is a string"; cout << mystring; return 0; 22

24 Strings can be initialized with any valid string literal just like numerical type variables can be initialized to any valid numerical literal. Both initialization formats are valid with strings: string mystring = "This is a string"; string mystring ("This is a string"); Strings can also perform all the other basic operations that fundamental data types can, like being declared without an initial value and being assigned values during execution. Program 2 // my first string #include <iostream.h> #include <string.h> This is the initial string content This is a different string content int main () string mystring; mystring = "This is the initial string content"; cout << mystring << endl; mystring = "This is a different string content"; cout << mystring << endl; return 0; An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. An integer literal can also have a suffix that is a 23

25 combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. Here are some examples of integer literals: 212// Legal 215u// Legal 0xFeeL// Legal 078// Illegal: 8 is not an octal digit 032UU// Illegal: cannot repeat a suffix Following are other examples of various types of Integer literals: 85// decimal 0213// octal 0x4b// hexadecimal 30// int 30u// unsigned int 30l// long 30ul// unsigned long Floating-point literals: A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E. Here are some examples of floating-point literals: 24

26 // Legal E-5L// Legal 510E// Illegal: incomplete exponent 210f// Illegal: no decimal or exponent.e55 // Illegal: missing integer or fraction Boolean literals: There are two Boolean literals and they are part of standard C++ keywords: A value of true representing true. A value of false representing false. You should not consider the value of true equal to 1 and value of false equal to 0. Character literals: Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it is a wide character literal (e.g., L'x') and should be stored in wchar_t type of variable. Otherwise, it is a narrow character literal (e.g., 'x') and can be stored in a simple variable of char type. A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02c0'). There are certain characters in C++ when they are preceded by a backslash they will have special meaning and they are used to represent like new line (\n) or tab (\t). Here, you have a list of some of such escape sequence codes: \n Newline \r carriage return 25

27 \t Tab \v vertical tab \b backspace \f form feed (page feed) \a alert (beep) \' single quote (') \" double quote (") \? question mark (?) \\ backslash (\) String literals: String literals are enclosed in double quotes. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.you can break a long line into multiple lines using string literals and separate them using whitespaces. Here are some examples of string literals. All the three forms are identical strings. "hello, dear" "hello, \ dear" "hello, ""d""ear" 26

28 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: Program 3 // defined constants: calculate circumference #include <iostream.h> #define PI #define NEWLINE '\n'; int main () double r=5.0; double circle; // radius circle = 2 * PI * r; cout << circle; cout << NEWLINE; return 0; 27

29 In fact the only thing that the compiler preprocessor does when it encounters #define directives is to literally replace any occurrence of their identifier (in the previous example, these were PI and NEWLINE) by the code to which they have been defined ( and '\n' respectively). The #define directive is not a C++ 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. 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 type variable = value; const int pathwidth = 100; const char tabulator = '\t'; const zipcode = 12440; In case that no type is explicitly specified (as in the last example) the compiler assumes that it is of type int. Program 4 #include<iostream.h> int main() 28

30 const int LENGTH =10; const int WIDTH =5; const char NEWLINE ='\n'; int area; area = LENGTH * WIDTH; cout << area; cout << NEWLINE; return 0; When the above code is compiled and executed, it produces the following result: 50 Questions: 1- Write a C++ program to compute the volume of a sphere. 2- Write a C++ program that computes the average of two marks. For example, if 75 is the degree of Maths and 89 of Chemistry then the average is

31 Experiment No. (4) Operators Object: How Mathematical and Logical Operators in the C++ program are. Theory: Once we know of the existence of variables and constants, we can begin to operate with them. For that purpose, C++ integrates operators. Unlike other languages whose operators are mainly keywords, operators in C++ are mostly made of signs that are not part of the alphabet but are available in all keyboards. This makes C++ code shorter and more international, since it relies less on English words, but requires a little of learning effort in the beginning. Assignation (=) The assignation operator assigns a value to a variable. a = 5; This statement assigns the integer value 5 to the variable a. The part at the left of the assignation operator (=) is known as the lvalue (left value) and the right one as the rvalue (right value). The lvalue has to be a variable whereas the rvalue can be either a constant, a variable, the result of an operation or any combination of these. The most important rule of assignation is the right-to-left rule: The assignation operation always takes place from right to left, and never the other way: 30

32 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 assignation. Therefore a later change of b will not affect the new value of a. Program 1 // assignation operator a:4 b:7 #include <iostream.h> int main () int a, b; a = 10; b = 4; // a:10, b:4 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 31

33 modification of b, even though we declared a = b earlier (that is because of the right-to-left rule). A property that C++ has over other programming languages is that the assignation operation can be used as the rvalue (or part of an rvalue) for another assignation. For example: a = 2 + (b = 5); is equivalent to: b = 5; a = 2 + b; The following expression is also valid in C++: a = b = c = 5; It assigns 5 to the all the three variables: a, b and c. Arithmetic operators ( +, -, *, /, % ) The five arithmetical operations supported by the C++ language are: + Addition - Subtraction * multiplication / division % modulo 32

34 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 may be 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; the variable a will contain the value 2, since 2 is the remainder from dividing 11 between 3. Compound assignation (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, =) 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 assignation operators: Expression is equivalent to value += increase; value = value + increase; a -= 5; a = a - 5; a /= b; a = a / b; price *= units + 1; price = price * (units + 1); Program 2 // compund assignation 5 #include <iostream.h> int main () 33

35 int a, b=3; a = b; a+=2; cout << a; return 0; // equivalent to a=a+2 Increase and decrease (++, --) C++ provides two special operators '++' and '--' for incrementing and decrementing the value of a variable by 1. The increment/decrement operator can be used with any type of variable but it cannot be used with any constant. Increment and decrement operators each have two forms, pre and post. The syntax of the increment operator is: Pre-increment: ++variable Post-increment: variable++ The syntax of the decrement operator is: Pre-decrement: variable Post-decrement: variable In Prefix form first variable is first incremented/decremented, then evaluated In Postfix form first variable is first evaluated, then incremented/decremented Program 3 // compund assignation #include <iostream.h> int main () int x,y; int i=10,j=10; x = ++i; //add one to i, store the result back in

36 x y= j++; //store the value of j to y then add one to j cout<<x; cout<<y; Questions: 1- First, determine the values of the variables for each of the following C++ statements manually: a- z=x++*y. b- z=2*++x*y. c- y %=x. Second, write a C++ program to find the above values to ensure from your answer. 2- Write a C++ program for the following expressions: a- x+y 2 +t/z b- a 3 -b 2 / c For the next experiments you shall need to know the following operators: 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. 35

37 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 C++: == 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. Be careful! The operator = (one equal sign) is not the same as the operator == (two equal signs), the first one is an assignation operator (assigns the value at its right to the variable at its left) and the other one (==) is the equality 36

38 operator that compares whether both expressions in the two sides of it are equal to each other. Thus, in the last expression ((b=2) == a), we first assigned the value 2 to b and then we compared it to a, that also stores the value 2, so the result of the operation is true. Logical operators (!, &&, ) (! ) Operator is the C++ 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 37

39 false true False false false False ( ) Operator 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: a b a b true true true true false true false true true false false false For example: ( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ). ( (5 == 5) (3 > 6) ) // evaluates to true ( true false ). (? ) 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 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

40 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. If condition is true the expression will return result1, if it is not it will return result2. Example: // conditional operator 7 #include <iostream.h> int main () int a,b,c; a=2; b=7; c = (a>b)? a : b; cout << c; return 0; 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 the second value (the one after the colon) which was b, with a value of 7. (, ) 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. 39

41 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. ( &,, ^, ~, <<, >> ) 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 Explicit type casting operator Type casting operators allow you to convert a datum of a given type to another. There are several ways to do this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses (()): int i; 40

42 float f = 3.14; i = (int) f; The previous code converts the float number 3.14 to an integer value (3), the remainder is lost. Here, the typecasting operator was (int). Another way to do the same thing in C++ is using the functional notation: preceding the expression to be converted by the type and enclosing the expression between parentheses: i = int ( f ); Both ways of type casting are valid in C++. sizeof() operator 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: 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. 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: 41

43 a = 5 + (7 % 2) // with a result of 6, or a = (5 + 7) % 2 // with a result of 0 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 C++. From greatest to lowest priority, the priority order is as follows: Level Operator Description Grouping 1 :: scope 2 () []. -> dynamic_cast static_cast reinterpret_cast postfix const_cast typeid ~! sizeof new delete unary (prefix) 3 * & + - unary sign operator 4 (type) type casting 5.* ->* pointer-to-member 6 * / % multiplicative additive Left-toright Left-toright indirection and Right-toleft reference (pointers) Right-toleft Left-toright Left-toright Left-toright 42

44 8 << >> shift 9 < > <= >= relational 10 ==!= equality 11 & bitwise AND 12 ^ bitwise XOR 13 bitwise OR 14 && logical AND 15 logical OR 16?: conditional 17 = *= /= %= += -= >>= <<= &= ^= assignment!= 18, comma Left-toright Left-toright Left-toright Left-toright Left-toright Left-toright Left-toright Left-toright Right-toleft Right-toleft Left-toright Grouping defines the precedence order in which operators are evaluated in the case that there are several operators of the same level in an expression. 43

45 All these precedence levels for operators can be manipulated or become more legible by removing possible ambiguities using parentheses signs ( and ), as in this example: a = % 2; might be written either as: a = 5 + (7 % 2); Or a = (5 + 7) % 2; 44

46 Experiment No. (5) Control Structure (if-statement) Object: Learning (if condition statements) in the C++ program. Theory: Conditional structure: 1. if statement The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is: if (condition) statement Where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional Flow Diagram: structure. 45

47 For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100: if (x == 100) cout << "x is 100"; If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces : if (x == 100) cout << "x is "; cout << x; Program 1 #include <iostream.h> int main () a is less than 20; value of a is : 10 // local variable declaration: int a = 10; // check the boolean condition if( a < 20 ) // if condition is true then print the following cout << "a is less than 20;" << endl; cout << "value of a is : " << a << endl; return 0; 46

48 2. If else statement We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is: if (condition) statement1 else statement2 For example: if (x == 100) cout << "x is 100"; else cout << "x is not 100"; The program prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x is not 100. The if + else structures can be concatenated with the intention of verifying a range of values. The following example shows its use telling 47

49 if the value currently stored in x is positive, negative or none of them (i.e. zero): if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0"; Remember that in case that we want more than a single statement to be executed, we must group them in a block by enclosing them in braces. Program 2 #include <iostream.h> int main () // local variable declaration: int a = 100; // check the boolean condition if( a < 20 ) // if condition is true then print the following cout << "a is less than 20;" << endl; else // if condition is false then print the following cout << "a is not less than 20;" << endl; cout << "value of a is : " << a << endl; return 0; a is not less than 20; value of a is :

50 Program 3 #include <iostream.h> int main () // local variable declaration: int a = 100; // check the boolean condition if( a == 10 ) // if condition is true then print the following cout << "Value of a is 10" << endl; else if( a == 20 ) // if else if condition is true cout << "Value of a is 20" << endl; else if( a == 30 ) Value of a is not matching Exact value of a is : 100 // if else if condition is true cout << "Value of a is 30" << endl; else // if none of the conditions is true cout << "Value of a is not matching" << endl; cout << "Exact value of a is : " << a << endl; return 0; 49

51 3. nested if statements: Syntax: if ( boolean_expression 1) // Executes when the boolean expression 1 is true if(boolean_expression 2) // Executes when the boolean expression 2 is true Program 4 Write a program that converts an integer number to character. #include <iostream.h> Void main() int number; cout<< Enter an integer number: ; cin>> number; if (number <=0) if (number >=127) cout<< The Character is : number<<endl; << (char) Note: the above two if statements can be replaced by the statement: If (number>=0&&number <=127) cout<< The character is: <<(char) number<<endl; 50

52 Questions: 1- Write a C++ program that computes the division for two integer numbers. 2- Write a C++ program that inputs an integer number and determines whether the number is even or odd. 3- Write a C++ program that computes the following equation: Homework: 1- Write a program that reads a number and determines whether the number is positive, negative, or zero. 2- Write a C++ program that computes the following equation: 51

53 Experiment No. (6) Control Structure (switch-statement) Object: Learning (the selective structure switch) in the C++ program. Theory: The syntax of the switch statement is to check several possible constant values for an expression. Something similar to several if and else if instructions. Its form is the following: switch (expression) case constant1: group of statements 1; break; case constant2: group of statements 2; break;... default: default group of statements 52

54 It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure. If expression was not equal to constant1 it will be checked against constant2. If it is equal to this, it will execute group of statements 2 until a break keyword is found, and then will jump to the end of the switch selective structure. Finally, if the value of expression did not match any of the previously specified constants (you can include as many case labels as values you want to check), the program will execute the statements included after the default: label, if it exists (since it is optional). 53

55 Both of the following code fragments have the same behavior: switch example if-else equivalent switch (x) case 1: cout << "x is 1"; break; case 2: cout << "x is 2"; break; default: cout << "value of x unknown"; if (x == 1) cout << "x is 1"; else if (x == 2) cout << "x is 2"; else cout << "value of x unknown"; Notice that switch can only be used to compare an expression against constants. Therefore we cannot put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):) because they are not valid C++ constants. If you need to check ranges or values that are not constants, use a concatenation of if and else if statements. Program 1 #include <iostream.h> int main () You passed Your grade is D // local variable declaration: char grade = 'D'; switch(grade) 54

56 case 'A' : cout << "Excellent!" << endl; break; case 'B': cout << "good!" << endl; break; case 'C': cout << "Well done" << endl; break; case 'D': cout << "You passed" << endl; break; case 'F' : cout << "Better try again" << endl; break; default : cout << "Invalid grade" << endl; cout << "Your grade is " << grade << endl; return 0; 4. nested switch statements: Syntax switch (ch1) case 'A': cout << "This A is part of outer switch"; switch(ch2) case 'A': cout << "This A is part of inner switch"; break; case 'B': //... break; case 'B': //... 55

57 Questions: 1- Write a C++ program that performs the arithmetic operations (+, -, *, /) determined by a user input. 2- Write a C++ program that reads an average mark and prints the range of it. For example, if the mark is 95 then print your average between

58 Experiment No. (7) Control Structure (while-loop) Object: Learning iteration structures (while-loops) in the C++ program. Theory: Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled. 1. The while loop Its format is: while (expression) statement Its functionality is simply to repeat statement while the condition set in expression is true. Flow the following diagram: 57

59 Program 1 // custom countdown using while Enter the starting number > 8 8, 7, 6, 5, 4, 3, 2, 1, loop is finish! #include <iostream.h> int main () int n; cout << "Enter the starting number > "; cin >> n; while (n>0) cout << n << ", "; --n; cout << "loop is finish!"; return 0; 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 loop is finish! and end program. 58

60 When creating a while-loop, we must always consider that it has to end at some point, therefore we must provide within the block some method to force the condition to become false at some point, otherwise the loop will continue looping forever. In this case we have included --n; that decreases the value of the variable that is being evaluated in the condition (n) by one - this will eventually make the condition (n>0) to become false after a certain number of loop iterations: to be more specific, when n becomes 0, that is where our while-loop and our countdown end. 2. The do-while loop Its format is: do statement while (condition); Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. Flow the following diagram: 59

61 For example, the following example program echoes any number you enter until you enter 0. Program 2 // number echoer Enter number (0 to end): You entered: #include <iostream.h> Enter number (0 to end): You entered: int main () Enter number (0 to end): 0 You entered: 0 unsigned long n; do cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "\n"; while (n!= 0); return 0; The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact if you never enter the a value 0 in the previous example you can be prompted for more numbers forever. Questions: 1- Write a C++ program that computes the sum of ten numbers input by the user. Use while loop. 2- Write a C++ program that computes the sum of consecutive integer number n. Use do/while loop. 60

62 Experiment No. (8) Control Structure (for-loop) Object: Learning Iteration structures (loops) in the C++ program. Theory: Its format is: for (initialization; condition; increase) statement; and 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. 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. 61

63 Program 1 // countdown using a for loop #include <iostream.h> int main () for (int n=10; n>0; n--) cout << n << ", "; cout << "loop completed!"; return 0; 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, loop completed! The initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written. For example we could write: for (;n<10;) if we wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to include 62

64 an increase field but no initialization (maybe because the variable was already initialized before). 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: for ( n=0, i=100 ; n!=i ; n++, i-- ) // whatever here... 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 break statement Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count down before its natural end (maybe because of an engine check failure?): 63

65 Program 2 // break loop example #include <iostream.h> 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted! int main () int n; for (n=10; n>0; n--) cout << n << ", "; if (n==3) cout << "countdown aborted!"; break; return 0; The continue statement The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. Program 3 For example, we are going to skip the number 5 in our countdown: // continue loop example #include <iostream.h> 10, 9, 8, 7, 6, 4, 3, 2, 1, loop completed! int main () for (int n=10; n>0; n--) if (n==5) continue; 64

66 cout << n << ", "; cout << "loop completed!"; return 0; Questions: 1- Write a C++ program that prints the numbers from 1 to Write a C++ program that computes the sum of ten integer numbers input by the user. 3- Write a C++ program that computes the factorial of an integer number. Homework: 1- Write a C++ program that computes the power of an integer number. 2- Write a C++ program that computes the following series: 65

67 Experiment No. (9) Array (Part I) Object: Learning how to define and use an array one-dimension in C++ programming language. Theory: C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1,..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Declaring Arrays: To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows: type arrayname [ arraysize ]; This is called a single-dimension array. The arraysize must be an integer constant greater than zero and type can be any valid C++ data type. For 66

68 example, to declare a 10-element array called balance of type double, use this statement: double balance[10]; You can initialize C++ array elements either one by one or using a single statement as follows: double balance[5] = , 2.0, 3.4, 17.0, 50.0; The number of values between braces can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array: If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write: double balance [] = , 2.0, 3.4, 17.0, 50.0; balance[4] = 50.0; The above statement assigns element number 5th in the array a value of Array with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representation of the same array we discussed above: Accessing Array Elements: An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example: double salary = balance[9]; 67

69 The above statement will take 10th element from the array and assign the value to salary variable. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays. Program 1 Write a C++ program that calculates the sum and average of an initialized integer array. #include <iostream.h> void main () int b[ 10 ]=9, 3, 11, 7, 1; int sum=0; for ( int i = 0; i < 5; i++ ) sum+=b[i]; cout<< Sum is <<sum << endl; << Average is <<sum/5.0; Program 2 Write a C++ program that inputs ten integer values into an array and finds the maximum number in the array. #include <iostream.h> void main () const int size=10; 68

70 int c[size], max; cout<< Enter ten integer values: ; for (int i=0; i<10; i++) cin>>c[i]; max=c[0]; for (int i=0; i<10; i++) if (c[i]>max) max=c[i]; cout<< The maximum number is <<max; Questions: 1- Write a C++ program that reads a one-dimensional array b and find minimum number. 2- Write a C++ program that reads a one-dimensional array b and sort its elements in ascending order. 69

71 Experiment No. (10) Array (Part II) Object: To solve more problems about a one-dimension array in addition to an array of string. Theory: String is a character array that is terminated with null. Null is zero and can be expressed as NUL or \0. The compiler adds the null to the end of string automatically. For example: char name[11];//hold 10 characters plus null char str[12]= H, e, l, l, o,, t, h, e, r, e ; or char str[12]= Hello there ;//string constant plus null str H e l l o t h e r e 0 70

72 Program 3 Write a C++ program that reads a string and then computes the number of capital letters in the string. #include <iostream.h> void main () char str[30]; int count=0 cout<< Enter your string: ; cin>>str; for ( int i = 0; i < =30; i++ ) if (str[i]>= A &&str[i]<= Z ) count++; cout<< No. of capital letters is << count; Questions: 1- Write a C++ program that computes the number of even integer numbers in an array entered by the user. 2- Write a C++ program that computes the length of a string entered by the user. 71

73 Experiment No. (11) Array (Part III) Object: Learning how to define and use multidimensional arrays in C++ programming language. Theory: C++ allows multidimensional arrays. Here is the general form of a multidimensional array declaration: type name[size1][size2]...[sizen]; For example, the following declaration creates a three dimensional integer array: int threedim[5][10][4]; Two-Dimensional Arrays: The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x,y, you would write something as follows: type arrayname [ x ][ y ]; Where type can be any valid C++ data type and arrayname will be a valid C++ identifier. A two-dimensional array can be think as a table, which will have x number of rows and y number of columns. A 2-dimensional array a, which contains three rows and four columns can be shown as below: 72

74 Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a. Initializing Two-Dimensional Arrays: Multi-dimensioned arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns. int a[3][4] = 0, 1, 2, 3, /* initializers for row indexed by 0 */ 4, 5, 6, 7, /* initializers for row indexed by 1 */ 8, 9, 10, 11 /* initializers for row indexed by 2 */ ; The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example: int a[3][4] = 0,1,2,3,4,5,6,7,8,9,10,11; 73

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes 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

More information

Programming with C++ Language

Programming with C++ Language Programming with C++ Language Fourth stage Prepared by: Eng. Samir Jasim Ahmed Email: engsamirjasim@yahoo.com Prepared By: Eng. Samir Jasim Page 1 Introduction: Programming languages: A programming language

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

C++ INDEX. Introduction: Instructions for use. Basics of C++: Structure of a program Variables. Data Types. Constants Operators Basic Input/Output

C++ INDEX. Introduction: Instructions for use. Basics of C++: Structure of a program Variables. Data Types. Constants Operators Basic Input/Output INDEX Introduction: Instructions for use Basics of : Structure of a program Variables. Data Types. Constants Operators Basic Input/Output Control Structures: Control Structures Functions (I) Functions

More information

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

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Second week Variables Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable.

More information

1

1 History of C++ & what is C++ During the 60s, while computers were still in an early stage of development, many new programming languages appeared. Among them, ALGOL 60, was developed as an alternative

More information

Manual. Subject Code: CS593. Computer Science and Engineering

Manual. Subject Code: CS593. Computer Science and Engineering Programming Practices using C++ Laboratory Manual Subject Code: CS593 Computer Science and Engineering B-Tech (5 th Semester) Structure of a program Probably the best way to start learning a programming

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Computer Skills (2) for Science and Engineering Students

Computer Skills (2) for Science and Engineering Students م رات ب Computer Skills () for Science and Engineering Students وا ا () ا C++ Department of Computer Science Prince Abdullah Bin Ghazi Faculty of Information Technology Prepared by: Dr. Habes Khraisat

More information

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

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types ME240 Computation for Mechanical Engineering Lecture 4 C++ Data Types Introduction In this lecture we will learn some fundamental elements of C++: Introduction Data Types Identifiers Variables Constants

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

UNIT-2 Introduction to C++

UNIT-2 Introduction to C++ UNIT-2 Introduction to C++ C++ CHARACTER SET Character set is asset of valid characters that a language can recognize. A character can represents any letter, digit, or any other sign. Following are some

More information

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

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

EEE145 Computer Programming

EEE145 Computer Programming EEE145 Computer Programming Content of Topic 2 Extracted from cpp.gantep.edu.tr Topic 2 Dr. Ahmet BİNGÜL Department of Engineering Physics University of Gaziantep Modifications by Dr. Andrew BEDDALL Department

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

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

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9 Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces

More information

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

Programming in C++ 4. The lexical basis of C++ Programming in C++ 4. The lexical basis of C++! Characters and tokens! Permissible characters! Comments & white spaces! Identifiers! Keywords! Constants! Operators! Summary 1 Characters and tokens A C++

More information

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

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed C Overview C OVERVIEW Goals speed portability allow access to features of the architecture speed C fast executables allows high-level structure without losing access to machine features many popular languages

More information

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

PART I.   Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++. Unit - III CHAPTER - 9 INTRODUCTION TO C++ Choose the correct answer. PART I 1. Who developed C++? (a) Charles Babbage (b) Bjarne Stroustrup (c) Bill Gates (d) Sundar Pichai 2. What was the original name

More information

DEPARTMENT OF MATHS, MJ COLLEGE

DEPARTMENT OF MATHS, MJ COLLEGE T. Y. B.Sc. Mathematics MTH- 356 (A) : Programming in C Unit 1 : Basic Concepts Syllabus : Introduction, Character set, C token, Keywords, Constants, Variables, Data types, Symbolic constants, Over flow,

More information

Basic Types, Variables, Literals, Constants

Basic Types, Variables, Literals, Constants Basic Types, Variables, Literals, Constants What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet) But some machines had 7, or 9, or... A word is the basic

More information

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

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program 1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

More information

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

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information

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

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1 NAGERCOIL COMPUTER SCIENCE Grade: IX C++ PROGRAMMING 1 C++ 1. Object Oriented Programming OOP is Object Oriented Programming. It was developed to overcome the flaws of the procedural approach to programming.

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

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

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things. A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

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

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm. CHAPTER 1&2 OBJECTIVES After completing this chapter, you will be able to: Understand the basics and Advantages of an algorithm. Analysis various algorithms. Understand a flowchart. Steps involved in designing

More information

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

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

More information

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

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Fifth week Control Structures A program is usually not limited to a linear sequence of instructions. During its process

More information

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

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA. DECLARATIONS Character Set, Keywords, Identifiers, Constants, Variables Character Set C uses the uppercase letters A to Z. C uses the lowercase letters a to z. C uses digits 0 to 9. C uses certain Special

More information

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

Unit-II Programming and Problem Solving (BE1/4 CSE-2) Unit-II Programming and Problem Solving (BE1/4 CSE-2) Problem Solving: Algorithm: It is a part of the plan for the computer program. An algorithm is an effective procedure for solving a problem in a finite

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

Introduction to Programming using C++

Introduction to Programming using C++ Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know

More information

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Understanding main() function Input/Output Streams

Understanding main() function Input/Output Streams Understanding main() function Input/Output Streams Structure of a program // my first program in C++ #include int main () { cout

More information

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

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

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols. EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Spring 2005 Lecture 1 Jan 6, 2005 Course Information 2 Lecture: James B D Joshi Tuesdays/Thursdays: 1:00-2:15 PM Office Hours:

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

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

REVIEW. The C++ Programming Language. CS 151 Review #2 REVIEW The C++ Programming Language Computer programming courses generally concentrate on program design that can be applied to any number of programming languages on the market. It is imperative, however,

More information

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

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style 3 2.1 Variables and Assignments Variables and

More information

Chapter 2. C++ Basics

Chapter 2. C++ Basics Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-2 2.1 Variables and Assignments Variables

More information

Java Notes. 10th ICSE. Saravanan Ganesh

Java Notes. 10th ICSE. Saravanan Ganesh Java Notes 10th ICSE Saravanan Ganesh 13 Java Character Set Character set is a set of valid characters that a language can recognise A character represents any letter, digit or any other sign Java uses

More information

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

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

More information

LECTURE 02 INTRODUCTION TO C++

LECTURE 02 INTRODUCTION TO C++ PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION

More information

4. Structure of a C++ program

4. Structure of a C++ program 4.1 Basic Structure 4. Structure of a C++ program The best way to learn a programming language is by writing programs. Typically, the first program beginners write is a program called "Hello World", which

More information

LEXICAL 2 CONVENTIONS

LEXICAL 2 CONVENTIONS LEXIAL 2 ONVENTIONS hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. ++ Programming Lexical onventions Objectives You will learn: Operators. Punctuators. omments. Identifiers. Literals. SYS-ED \OMPUTER EDUATION

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

More information

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

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

CHAPTER 3 BASIC INSTRUCTION OF C++

CHAPTER 3 BASIC INSTRUCTION OF C++ CHAPTER 3 BASIC INSTRUCTION OF C++ MOHD HATTA BIN HJ MOHAMED ALI Computer programming (BFC 20802) Subtopics 2 Parts of a C++ Program Classes and Objects The #include Directive Variables and Literals Identifiers

More information

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

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah Lecturer Department of Computer Science & IT University of Balochistan 1 Outline p Introduction p Program development p C language and beginning with

More information

Full file at C How to Program, 6/e Multiple Choice Test Bank

Full file at   C How to Program, 6/e Multiple Choice Test Bank 2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)

More information

INTRODUCTION 1 AND REVIEW

INTRODUCTION 1 AND REVIEW INTRODUTION 1 AND REVIEW hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Programming: Advanced Objectives You will learn: Program structure. Program statements. Datatypes. Pointers. Arrays. Structures.

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

Programming with C++ as a Second Language

Programming with C++ as a Second Language Programming with C++ as a Second Language Week 2 Overview of C++ CSE/ICS 45C Patricia Lee, PhD Chapter 1 C++ Basics Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Introduction to

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

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

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is

More information

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

More information

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur Operators and Expressions 8/24/2012 Dept of CS&E 2 Arithmetic operators Relational operators Logical operators

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

A First Program - Greeting.cpp

A First Program - Greeting.cpp C++ Basics A First Program - Greeting.cpp Preprocessor directives Function named main() indicates start of program // Program: Display greetings #include using namespace std; int main() { cout

More information

Programming Lecture 3

Programming Lecture 3 Programming Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements

More information

Language Reference Manual simplicity

Language Reference Manual simplicity Language Reference Manual simplicity Course: COMS S4115 Professor: Dr. Stephen Edwards TA: Graham Gobieski Date: July 20, 2016 Group members Rui Gu rg2970 Adam Hadar anh2130 Zachary Moffitt znm2104 Suzanna

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Overview of Source Code Components Comments Library declaration Classes Functions Variables Comments Can

More information

Computers Programming Course 5. Iulian Năstac

Computers Programming Course 5. Iulian Năstac Computers Programming Course 5 Iulian Năstac Recap from previous course Classification of the programming languages High level (Ada, Pascal, Fortran, etc.) programming languages with strong abstraction

More information

Introduction of C++ OOP forces us to think in terms of object and the interaction between objects.

Introduction of C++ OOP forces us to think in terms of object and the interaction between objects. Introduction of C++ Object Oriented Programming :- An Object Oriented Programming (OOP) is a modular approach which allows the data to be applied within the stipulated area. It also provides reusability

More information

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 1 C++ Basics Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

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

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents: Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language Dr. Amal Khalifa Lecture Contents: Introduction to C++ Origins Object-Oriented Programming, Terms Libraries and Namespaces

More information

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance. 2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C

More information

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

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

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

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

EP241 Computer Programming

EP241 Computer Programming EP241 Computer Programming Topic 2 Dr. Ahmet BİNGÜL Department of Engineering Physics University of Gaziantep Modifications by Dr. Andrew BEDDALL Department of Electric and Electronics Engineering Sep

More information

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

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Copyright 2011 Pearson Addison-Wesley. All rights

More information

This watermark does not appear in the registered version - Slide 1

This watermark does not appear in the registered version -   Slide 1 Slide 1 Chapter 1 C++ Basics Slide 2 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output Program Style

More information