C++ LECTURES ABDULMTTALIB. A. H. ALDOURI
INTRODUCTION
A program is a sequence of instructions for a computer to execute. Every program is written in some programming language. The C++ (pronounced “see-plus-plus”) language is one of the newest and most powerful programming languages available. It allows the programmer to write efficient, structured, object-oriented programs. Prior to 1983, Bjarne Stroustrup added features to C language and formed what is called "C with Classes". During the 1990s, C++ became one of the most popular commercial programming languages.
STRUCTURE OF A C++ PROGRAM // This is our first program (comment) # include
The body ←the starting brace of the Statements; program
} {
1. Comments : make←the programming end brace simple and help us to understand the program. They are not execution statements. In C++, comments can be given in two ways: a) Single line comments: They start with // (double slash) symbol. For example: int a ; // declares the variable a of integer type C b) Multi line comments: Start with a /* symbol and terminate with a */ symbol. 2. Header files: The second statement directs the compiler to include the header file
[1]
C++ LECTURES ABDULMTTALIB. A. H. ALDOURI
BASIC DATA TYPES IN C++ The basic data types available in C++ language are given in the following table:
Data Range Size Usage Type int -32768 to 32767 2 bytes (16 bits) For storing numbers without decimal. long -2147483648 to 2147483647 4 bytes (32 bits) For storing integers. Has higher range than „int‟. char 0 to 255 1 byte (8 bits) For storing characters. float -3.4 * 1038 to 3.4 * 1038 4 bytes (32 bits) For storing floating point numbers. It has seven digits of precision. double ±1.7*10 ±308 (15 digits) 8 bytes (64 bits) It is used to store double precision floating point numbers.
DECLARATION OF VARIABLES A variable may be declared as below: type variable_name ; type variable_name = initial value; type variable_name ( value) ; type is the data type such as int, float or double, char, etc. C++ allows long descriptive variable or identifier names. The rules for forming a variable name also apply to function names. The rules are: 1. The first character must be a letter, either lowercase or uppercase; 2. Case is significant, uppercase and lowercase letters are different; 3. Variable names are composed of lowercase letters, numbers, and the underscore character 4. Defined constants are traditionally made up of all uppercase characters 5. The number of characters allowed in a variable name is compiler dependent, but the variable must be unique in the first eight characters in order to be safe across compilers;
[2]
C++ LECTURES ABDULMTTALIB. A. H. ALDOURI
6. Make variable names descriptive; 7. Do not make a variable name the same as a reserved word.
The Reserved Words for C++ Language are:
volatile double int struct break else long switch register typedef for extern union char void const unsigned return do sizeof float auto case static continue default if signed short goto enum while
Examples: int my_Age; ( to declare an integer variable.) long Fact=5376894; (to declare a long integer variable with initial value.) float AVERAGE2; (to declare a real (floating point) variable.) double x (2.12356724); (to declare a double precision floating point variable with initial value.) char ch; (to declare a character variable.)
char CH = „A‟; (to declare a character variable with initial value.) int x1, x2, x3=0; (to declare more than one integers.)
CONSTANTS C++ allow for the programmer to define constants that represent decimal, hexadecimal octal, string and character constants. The #define directive can be used to define constants and it is placed after headers files. #define PI 3.14156 #define MYNAME "JOHN DOE" #define LIMIT 10 #define ESC 0x1B Also we can use const to define constants as follows : const int diameter = 10 ; const float PI = 3.14159; const char ch= 'a';
[3]
C++ LECTURES ABDULMTTALIB. A. H. ALDOURI
INPUT AND OUTPUT STATEMENTS
The input statement has the following syntax: cin>> variable_name; cin>> var1>> var2>> var3>>……… ; Examples: cin>>age; cin>>x1>>x2>>x3; The output statement has the following syntax: cout<
This produces the following output: 500 1F4 764 setw( ) : The 'setw( )' manipulator is used to set the field width for the next insertion operator. The header file
#include
[4]
C++ LECTURES ABDULMTTALIB. A. H. ALDOURI
{ int i = 100; cout << setw(6) << dec << i; cout << setw(6) << hex << i; cout << setw(6) << oct << i; return 0; } This produces the following output:
100 64 144
OPERATORS IN C++ LANGUAGE 1. Assignment Operator: The basic assignment operator is ( = ) which is often called equal to. Consider the following assignments. int x = 5,y = 10, z, w; // Declaration and initialization z = x; // assignment w = x + y; // assignment x=(b=3, b+2);//first assign 3 to variable b and then calculate x
y =(x = 5)+2 ; // assign the value 5 to x, then assign x+2 to y a = b = c = 5; // assign the value 5 to a, b, and c
2. Arithmetic Operators: Arithmetic operators are used to perform the basic arithmetic operations. They are explained in the following table:
Operator Usage Examples + Used for addition Sum = a + b
- Used for subtraction Difference = a – b * Used for multiplication Product = a * b / Used for division Quotient = a / b This operator is called the remainder or the Remainder = a % b modulus operator. It is used to find the % remainder after the division. This operator cannot be used with floating type variables.
[5]
C++ LECTURES ABDULMTTALIB. A. H. ALDOURI
3. Compound Assignment Operators C++ allows combining the arithmetic operators with assignment operator as in the following table. Operator C++ expression Equivalent expression Explanation and use
+= B + = 5; B = B +5; int B= 4; B+=5 ; // B=9 = int C = 10; – C – = 6; C = C – 6; C–= 6 ; // C=4 *= D * = 2; D = D*2; int D = 10; D*=2; // D=20 /= E / = 3; E = E/3; int E = 21; E/=3; // E = 7 %= F % = 4; F = F % 4 ; int F=10; F%=4 ; // F=2
4. Relational Operators: The relational operators are explained in the following table:
Operator Usage Example Explanation < Less than A Greater than A>B A is greater than B. <= Less than or equal to A<=B A is less than or equal to B. >= Greater than or equal to A>=B A is greater than or equal to B. == Equality A == B A equal to B. != Not equal to A != B A is not equal to B.
5. Logical Operators The logical operators are used to combine multiple conditions (logical statements). The following table describes the logical operators:
Operator Usage Example && (logical AND) The compound condition is true, ((a>b) && (a>c)) if both conditions are true. || (logical OR) The compound statement is true, (( a>b) || (a>c)) if any or both conditions are true. ! (logical NOT) It negates the condition. !(a>b)
[6]
C++ LECTURES ABDULMTTALIB. A. H. ALDOURI
Examples y= ((2 == 4) && (7>5)); z= !(1 > 4); w= ((2 > 0) || (5<0)); the results are: y=0 , z=1 , w=1
The following program illustrates the application of logical operators. #include >radius;
[11]
C++ LECTURES ABDULMTTALIB. A. H. ALDOURI
area=PI*radius*radius; circum=2*PI*radius; cout<<"area="< void main( ) { float R1, R2, V,I,V1,V2; cin>> R1>> R2>> V; I=V/(R1+R2); V1=I*R1; V2=I*R2; cout<<" I="<
2. if .... else STATEMENT. This statement is used when we have two choices, it is written as follows: if (condition) { Block1_of_statements ; } else { Block2_of_statements ; }
[13]
C++ LECTURES ABDULMTTALIB. A. H. ALDOURI
if (x %2== 0) { cout << "x is even"; } else { cout << "x is odd"; }
.of an integer (قابلي القسم ) The following program uses the if....else to test for divisibility #include A chain of if .. else expressions is used if there are more than two choices. The following program selects the name of the day of the week out of 7 choices. #include [14] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI cout<<"It is Monday "< CONDITIONAL SELECTION OPERATOR ( ? : ) If there are two options to choose from, the conditional selection operator ( ? : ) may be used in place of if … else . The syntax is illustrated below : condition ? statement 1 : statement 2 The above expression means that if the condition is true then statement1 will be executed, otherwise statement2 will be executed. For example: m>n ? max = m : max = n ; y=(x>3) ? 100:200; z=(x>3) ? x*x : 2*x+1; Ex: Use the selection operator ( ? : ) to find the maximum of four integers. [16] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI #include H.W Use the selection operator ( ? : ) to find the maximum of six integers. 3. The switch STATEMENT (Multiple Choice Statement) When a multiple selection is required we may use switch statement which is illustrated below: switch (expression or variable ) { case value1 : statement1; break; case value2 : statement2; break; ...... case value n : statement n; break; default : statement; } During execution of the program, the expression is evaluated and compared with the values mentioned in different cases of switch expression. If the value matches a value of a particular case, the statements in that case are executed. If no case-value matches with the value of the expression the program goes to the last statement which is a default statement as shown in figure below: [17] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI Note The word break means exit from switch statement. The following program illustrate the switch statement. #include [18] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI Ex: Write a program to receive an arithmetic operator and two integers, the program performs the arithmetic operation on the two numbers (use switch statement). #include case '–' : cout< H.W. Write a program to find the value of y from the following (using switch statement). √ sin { [19] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI LOOP AND OTHER CONTROL STATEMENTS In C++ programming language, there are three loop statements, they are: 1. The while statement (loop) . 2. The do…while statement (loop) . 3. The for statement (loop). 1. THE while STATEMENT. The while statement or loop is as illustrated below : while (conditional expression) { Block_of_statements ; } This means that as long as the condition is true, Block_of_statements will be executed. Ex: while (i <= n) sum +=i++; Ex: Use while loop to find the sum of numbers from 1 to 10. #include Ex: Write a program to find the sum of squares of integers. #include [21] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI int i = 1, n, sum = 0; cout << "Enter a positive integer:"; cin>>n; while (i <= n) { sum += i*i; i++; } cout << " sum = " << sum ; return 0; } THE NESTED while STATEMENTS When more than one parameter such as i and j are to be varied in a program, two loops are required. The i loop is the outer loop and j loop is the inner loop. The code may be written is illustrated below. while (int i < n) { while (int j < m) { statements ; } } The following program illustrates nested while loops by finding the the value of Z: ∑∑ #include [21] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI while (j<=4) // inner while loop { Z+=(i*j); ++j } ++i; } cout<<"Z="< 2. THE do…while LOOP The do...while statement is almost the same as the while statement. Its syntax is: do { Block_of_statements; } while (condition); The only difference between while and do…while is that the do...while statement executes the statements first and then tests the condition. These two steps are repeated until the condition becomes false. A do...whi1e loop always iterates at least once, regardless of the value of the condition, because the statement executes before the condition is evaluated. Ex: Write a program to evaluate the factorial of an integer. #include [22] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI do { f *= n; --n; } while (n > 1); cout <<"factorial of"< 3. THE for LOOP The for loop is written as given below: - for (initial value ; condition ; increment /decrement) { Block_of_statements ; } The for loop is controlled by three expressions: an initialization, a condition, and update (increment/decrement). Ex: for (i=0 ; i<=10 ; i++) x=i+2 ; The statement (x=i+2) is executed repeatedly as long as (i< = 10 ). Ex: Write a program to evaluate the factorial of an integer. #include [23] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI { f *= n; } cout <<"factorial= "<< f ; } NESTED for LOOPS If a function involves more than one variable and we want to evaluate it for different values of all the variables, we will have to use a nested for loop, as illustrated below: for ( int n=0; n<= A; n++) { for ( int m=0; m<= B ; m++) { Statements; } } Ex : Write a program finds the value of Z form the following formula: #include [24] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI int i, x, sum=0; float av; for (i=1; i<=25; ++i) { cin>>x; sum+=x; } av=sum/i; cout<<"sum= "< [25] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI Ex: Write a program to find the sum of the following series. #include void main( ) { int i, j=2, r, n; long f; float p, x, sum=0; cin>>x>>n; while(j<=n) { i=r=f=1; while(i<=j) { f*=i; ++i; } p=pow(x,j) sum=sum+(f/p)*r; j+=2; r*=-1; } cout<<"sum="< ENDLESS for LOOP If for loop is written as below it is called endless loop: for (int i = 0 ; i<10 ; ) for ( ; ; ) THE break STATEMENT We have already seen the break statement used in the switch statement. It is also used in while, do…while, and for loops. When it is executed, it terminates the loop, “breaking out” of [26] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI the iteration at that point. The following program illustrates the use of endless loop and break statement: #include Ex: Write a program to find the sum of the series (the sum doesn't exceed 50000): 13 + 33 + 55 + 77 + … # include [27] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI int i =1,sum=0; cin>>n; while ( i>0) { sum = sum + pow(i,i) ; if (sum>50000) break; i+= 2 ; } cout<<" The sum of the series = "< Ex: Write a program to find the sum of the following series: 1 + 1/2! + 1/3! + … 1/n! # include [28] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI FUNCTIONS A function is a group of statements used to perform a certain operation. It is called from some point of the main program or another function. There are several (تستدعى) advantages of using functions: Functions allow for breaking down the program into discrete units. Programs that use functions are easier to design, program, debug and maintain. Functions are of two types: 1. Functions return a value to the main program end with return statement. 2. Functions do not return a value defined by the word void. 1. FUNCTIONS RETURN A VALUE: The function definition is illustrated below: type function_name (type parameter1, type parameter2, …… ) { statements ; return value; } In the above definition the first word is the type of the function, it is the type of data it returns. The second item is the name of the function. (type parameter1, type parameter2, ……) are called arguments of the function. For example: int sum(int x, int y) { int sum=x+y; return sum; } استدعاء الدالة (ACCESSING A FUNCTION (The Call of the Function The main program calls the function by declaring a variable followed by the function name and its arguments, as follows: type variable_name=function_name(arguments) For example: int s1=sum(a, b) ; [29] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI Ex: Write a function finds the sum of two numbers, the main program calls the function to find the sum of four numbers. #include Ex: Write a program includes a function receives a character and returns its type (number, lowercase alphabet, uppercase alphabet, or symbol ) #include [31] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI int type; char ch; cout << "Enter the character:"< Ex: Write a program includes two functions, the first is named power receives two numbers and return the power and the second is named octal receives an octal number and returns the decimal value by using the first function. #include [31] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI { int y=z%10; int k=power(m, 8); sum+=k*y; z/=10; ++m; } return sum; } main( ) { int A; cin>>A; int n=octal(A); cout< Ex: Write a function that finds the factorial of an integer, the main program calls the function to compute “y” from the following formula. y=k!*m!/(k-m)! #include [32] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI if (m>k){ long f1=fact(k); long f2=fact(m); long f3=fact(k-m); y=fact(k)*fact(m)/fact(k-m); y=f1*f2/f3; cout<<"y="< 2. VOID FUNCTIONS A function does not return a value to the main program and is known as a procedure or a subroutine. In C++, such a function is identified simply by placing the word void before the name of the function as shown below: void function_name (arguments) For example : void AA(int x, int y) { int sum; sum=x+y; cout< This type of functions is called by its name without using any variable as shown: AA(a, b) ; Ex: Write a function that find and print the square of an integer, the main program calls this function to find the squares of 0-10. #include [33] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI } main( ) { cout<<"x\t"<<"x*x"< The following function does not receive arguments form the main program and does not return value to the main program. The definition is as shown below: void AA(void) { cout<<”this is a C++ program”; } The call of this function is as shown below: AA( ); H.W. (1) Write a program to find the sum of the following series: S=(1) + (1+2) + (1+2+3) + (1+2+3+4) +…………+ (1+2+3+……….+n) (2) Write a program include two functions, the first is named fact receives one integer and returns its factorial, and the second is named pow receives two integers and returns the power of them. The main program uses the two functions to find the value of Z from the following series. n [34] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI ARRAYS AND MATRICES In an array, multiple values of the same data type can be stored with one variable name. In computer, array elements are stored in a sequence of adjacent memory locations. Arrays are of two types: 1. One dimensional array. 2. Multi-dimensional array. 1. ONE DIMENSOINAL ARRAY The position of an element in array is called array index or subscript. In the case of an array of five elements A[4]={6 , 7, 8, 9,}, their index or subscript values are 0, 1, 2, and 3 . Note that count for array elements or subscripts starts from 0 as shown below. Index A[0] = 6 0 1 2 3 A[1] = 7 A[2] = 8 A[3] = 9 Element The declaration of one dimensional array is done as illustrated below. type name [number of elements in the array] ; for example: int A[10]; // Array „A‟ has 10 elements of type integer. float B[20]; // Array „B‟ has 20 elements of type float. double D[15]; // Array „D‟ has 15 elements of type double. char name[20]; // Array 'name' has 20 elements of type char. INPUT/OUTPUT OF ONE DIMENSOINAL ARRAY The input/output of an array is carried out element by element either a for loop or while loop may be used. For example, an array Bill[5] having n elements are to be read as follow: for (int i = 0; i<5; i++) cin>> Bill[i] ; An array can be read by another way called “static initialization” as shown: إعطاء قيم م اشر عند تعريف المصفوف ;{int Bill[5]={10, 20, 30,40, 50 [35] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI and the output (printing) is as follows: for (int i = 0; i<5; i++) لط اعتها على شكل صف ; " ">>[cout<< Bill[i OR for (int i = 0; i<5; i++) لط اعتها على شكل عمود ; cout<< Bill[i]< 2. TWO DIMENSIONAL ARRAYS (MATRIX) The two dimensional array is represented by ith rows and jth columns. The figure below shows an array of two rows and five columns. A[0][0] = 5 0 1 2 3 4 A[0][1] = 2 0 A[1][0] = 6 1 A[1][3] = 9 A two dimensional array can be declared as below. type name [number of rows][number of columns]; For example: int A[2][5]; float B[10][20]; INPUT/OUTPUT OF TWO DIMENSOINAL ARRAY The two dimensional array A[m][n] can be read as follow: for(i=0; i To print a two dimensional array we can use the following form: for(i=0; i [36] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI Ex: Write a program to read an array of 50 real numbers, the program calculates the sum and the average and the maximum element of the array. #include Ex: Write a program to sort an array of 10 integers in an ascending order. #include [37] C++ LECTURES ABDULMTTALIB. A. H. ALDOURI