Você está na página 1de 55

Digitally signed by Hosam 358

Introduction to C++ programming


Course overview:
This course is aimed to teach one of the most fundamental programming languages, C language as an example and introduction to the programming world. The course does not go so deep in the details of the C++ and its related topics like object oriented programming, but it just includes the basics of any programming language, which are the basic set of skills needed The material recommended for this course is:

C++ from the ground up

Some basic concepts: Why do we program?!


The computer can never be regarded as a creative or intelligent device, but it is just a piece of silicon circuits that doesnt have a mind of its self The benefits of the computer is its 1-accuracy and 2-its high speed in manipulation several problems. But, it still unable to think or to find answers of its own, so we use programs. A program is a set of instructions written in a manner that the computer can understand, those instructions tell the computer how to behave in a specific problem The manner we write the program is the programming language that we use.

Programming language & compilers:


For the computer to understand what you want him to do, you need to talk to him in the language he understands. The only language the computer understands is the machine language which is just a set of 0s and 1s, so in order to write a single command for the computer you may need to write some thing like this: 00110100110010100, that way was a very hard and time-consuming way for programmers, and it was hard to maintain and to correct errors, from this point the need for a simpler and more advanced language aroused.

In order to make programming easier we needed to develop new languages nearer to our spoken languages like English, and the more the language is near to English, the higher its level is. Now we have two kinds of languages: 1- Languages near to the computer language, which are called low-level languages. 2- Languages near to English language and it are called high-level languages. For that the high-level language consists mainly of combinations of the English words, We still need something to translate what we wrote almost in English into the language the computer understands (machine language), and that is the rule of the compiler.

The compiler is an intermediate level between your program and the


computer. It translates the words and phrases you write into machine language so the computer will understand it and execute it. Now you can write your program in a simple way near to English language and rely on the compiler to take care of translation process to machine language. Now we can advance to see the construction of the program in the C language.

Program construction in C++:


#include <iostream.h> void main () { cout<<hello C++; }

Lets consider the simplest program represented next:

In the real programs we may find a program that consists from over 1,000,000 lines of code, that may be confusing for the programmer, makes programs hard to read, hard to correct errors and hard to maintain. The key solution for this problem was by breaking the program into smaller blocks of code, simpler code blocks that can be maintained separately and can be easily corrected. In C++, the program is usually divided into smaller blocks of code; each block of code must begin with an opening brace "{" and end with a closing brace "}". One of the most important kinds of code blocks is functions, which will be discussed later during the course. 2

The main program body is a function called: main () The main is the function that represents the whole program, when the computer runs the program, it searches for the main and begin with the first line of code inside it and closes when it reaches the last line, an empty program may look like this: void main () { }

Statement:
Inside our example programs main, we find the line of code: cout<<hello C++; This is a very good example of code lines or statements in C++ as it always ends with a semicolon, and it begins with the keyword cout, which tells the computer to bring what is included between the double quotation marks on the screen.

The #include directive:


Here we meet a critical point in C++, the C language doesnt have a built in support for anything, so you have to build your program from the ground up, but for your convenience, the C language offers you some ready sets of functions, those functions are a common purpose functions and they are essential to any program, one of them is the functions we just met called cout to print out a word on the screen. The code needed for those built in functions is not automatically considered part of you program until you tell the program to do so. To do that you must give the program the location of the code you may use in your program. In order to include any set of code files in our program we use a keyword in C++, #include this word tells the compiler to open a file and reads all code inside it. The file name comes on the right of this word and is always surrounded by <> like the first line in our example : #include <iostream.h> All code files we may include in our programs are ended with the extension ".h".

Main structure of a program:


Whatever the problem we are trying to solve using computer and independent of the programming language we may use, all programs consists of two major elements: 1- Data. 2- Functions on those data.

The data we use may be the length of a square in a geometric program or the age of a student in a school database program; the functions on the data may include the process of getting the area of the square or the average age of school students. In order to use data in our programs, we must save them a place in the computer memory, so that we may save, edit, retrieve and manipulate the data quickly during the program runs, to do this we have to declare variables.

Variables is places for data in memory, we reserve a place for our data, and
call that place a name by declaring a variable. The major types of data variables we have are: 1- int, which is the most, used data type; it takes 2 bytes of memory space and is used to hold integer data (like 1, 2, and 5). 2- float, which is the second most important data type, it takes 4 bytes of memory space and it is usually used to hold fractional numbers like 2.4, 3.55 . 3- char and this type is a very special type as it may be used to represent numbers or characters as we will see in moments, this type takes 1 byte of memory space. 4- double and this is a data type that carries fractional data just like float but it has wider range as it takes 8 bytes of memory space . 5- bool, this is a very special data type as it doesnt carry characters or numbers, but it just carries the logic 0 and 1 so it has just two values : True or False. To declare a variable we must supply two main properties: 1- The variable type like int, char, or float. 2- The variable name, which is a name we call this variable so we can use it in the program. Example of declaring a variable may look like this: int squarelength; Here we wrote the type of the variable first followed by the variable name and ended by the semicolon.

To name a variable we have to follow some restricted rules those rules are: 1- The variable name consists of the English characters only and the underscore (_) , you cant use any other special character, like % , some thing like the following will not work: int benefit%; // error 2- The variable name cant include white spaces, the whole variable name must be one word so you cant use the next syntax: int square length; // error 3- You may use numbers in your variable name but the first character of your variable name must be a letter or an underscore _ : int 2pi; // error int pi2; // allowed 4- Try to give a meaningful names for your variables, this is not a must but a good practice as it make the revision and correction of the program easier int x1; // allowed but not recommended int square_length; /*allowed and recommended, the program looks easier to understand*/

Character representation in C++ (ASCII representation):


In C++ all characters of English and some of the common special characters are represented and manipulated in the computer as numbers for example, the capital letter A is represented by 65 and 66 represents the capital B and so on, but to distinguish real numbers from those used to represent characters by using the type char for the numbers representing characters.

Input / Output operations:


To input a value from the keyboard or to output the value on the screen we use a special syntax for each case,

1- Output using cout:


To output a value we write the keyword cout then we use the operator << then we write the value to be printed on the screen and end the line with semicolon. ex: Cout << "this is a test";

To print the contents of a data variable we put the name of the variable without quotation marks after the operator <<, ex for that may be: Int length; Length=10; Cout<<length; The output of this program will be 10. To output multiple values we may cascade the output operator << like the next example: Cout << length= << << length;

The output of this line will be: length= 10 To force the program to begin writing the next value from the beginning of a new line you may use the keyword endl, cascade it as a value to be outputted on the screen Example: cout<< "Maged shafie Mohammed"<<endl<<"computer science"; The output of the previous line will be like that: Maged shafie Mohammed Computer science

2- Input using cin:


To input data into a variable, we must first declare a variable to hold the data we will input from the keyboard, and then we use the next syntax: cin>>squarelength; The last code line takes input from the keyboard as the user inputs the data and puts this data into the variable called squarelength. Here we must be careful of type matching that the data the user inputs must be of the same data type as the variable we use to hold the data, the following code will not work properly if the user inputs a name like Maged: int age; cin>>age;

That is because we just declared a variable of type int, which holds integer data and we are trying to input a word inside which for sure, would not match the int data type.

Assignment:
While we write our code we may use to set a variable value to some constant value, that may be like int x; X=5; As we just seen this can be done by using the assignment operator = then we write out the constant value we want to use.

Arithmetic Operators:
Arithmetic operators like (*, / , + and -) are used in C++ in almost the same manner it is used in math . You may write something like that in C++ int x1,x2,x3,x4; x4 = x1 + x2*x1 /x3 +6;

Note:
The right hand side of any arithmetic statement like the previous one must be the name of a variable; it cannot be an expression the following code is not allowed in C++: x1+x2= x1*x2/2; // error

Arithmetic Precedence:
The order of arithmetic operations in a complicated expression is the same as the order in math, the multiplication and division is made first, then addition or subtraction. If you want to force part of a complicated expression to be done, first you use parentheses.

Example: Determine the result of the following code:


#include <iostream.h> void main() { int x1=5; int x2=6; int result; result=x1*5+x2; cout<<result<<endl; result =x1* (5+x2); cout<<result<<endl; }

Answer:
The result will be: 31 55 Here we realize that in the second arithmetic expression we used parentheses to force addition to be executed first.

Automatic Conversions:
One of the important related topics to mathematical operations is automatic type conversions; consider the following example: int x=6; int y=5; float result=x/y; cout<<result; Here the result is not as expected which is 1.2 but it will be 1 Why? The answer is to know how the computer deals with the arithmetic expression we just wrote: 1- First, the computer brings the values of both x and y. 2- Second, the computer divides the two values. 3- Third, the computer checks the data type of both variables and then creates a temporary data location in the memory to hold the result of the division, this memory location will be reserved to match the type of the x and y, so in our example it will be int too. That was the reason that the computer took just the integer part of the result, but in order to force the computer to use the data type we want we use type casts. 8

Type casts:
In the previous example we saw how the automatic type conversion results in the loss of part of the data which is the fractional part, so if we want to force the computer to use a special data type in the temporary data memory we use the cast syntax. The cast syntax consists of the desired data type put between parentheses before the expression we deal with. If we modify the previous example so that the expression looks like that: result= (float) x/y; The result now will be 1.2 as we always wanted.

NOTE....!!!!
C++ is a case sensitive programming language, i.e. capital letters not equal to small ones.. A not equal a

Statements
In programming languages, we use many commands. Each does some thing for us depending on its type. We use any of them where and when we need depending on our program logic. These statements are separated into 3 basic types: 1) Conditional statements. 2) Iteration or Loop statements. 3) Jump statements.

Operators:
We use some useful operators with these statements and they are separated into 2 main types: 1) Arithmetic operators:

> >= < <= == !=

Greater than Greater than or equal Less than Less than or equal If equals (comparing) Not equal

2) Logic operators:

&& || !

Logic AND Logic OR Logic NOT (Inverter)

10

Now we will explain each statement in more details:

1) Conditional statements:
Some times, you need to make a decision or that your program executes some thing specified if some thing happened. When some thing happens (called an expression or condition)the expression becomes truethe program executes a certain code you write. Example: If we wish to write a program that results the grade of a student depending on his marks. The condition here is the students marks and the code will be executed is evaluating his grade. In C++, we have 2 basic conditional statements:

1) if statement:
The basic form of (if) is:

if(expression or condition) { Statement1; Statement2; . . }

Here the compiler first checks the condition if its true it executes the code written between braces. If its false it skips all the written code between braces and goes directly to the first statement after the (if) block. Example:

If(mark>=85) { cout<<The grade is excellent; }

11

Some times, you need to execute certain code if the condition is true or to execute another code if the condition is false. You can do this by using if-else statement:

if(expression or condition) { Statement1; Statement2; . . } else { Statement3; Statement4; . . }

Example:

if(mark>=50) { cout<<succeeded; } else { cout<<failed; }

12

-The if-else ladder:


Code A if(mark>=85) { grade=A; } else if(mark<85 && mark>=75) { grade=B; } else if(mark<75 && mark>=65) { grade=C; } else if(mark<65 && mark>=50) { grade=D; } else { grade=F; } Code B if(mark>=85) grade=A; if(mark<85 && mark>=75) grade=B; if(mark<75 && mark>=65) grade=C;

if(mark<65 && mark>=50) grade=D; if(mark<50) grade=F;

These 2 codes result the same (evaluate a student grade depending on his mark). However, we say that code A is better. A closer look to both codes can explain why. Assume that the student mark is (90). For code A, the compiler will check the first expression (mark>=85) then its true, the compiler executes the code associated with that condition block (grade=A;) and skips all other conditions (no need to check all other conditions that the first one is true) and goes directly to the first statement after the if-else ladder block. But for code B, the compiler checks the first expression (mark>=85) then its true so it executes the code associated with that condition (grade=A;) and goes to the next statement i.e. it goes to the next if block, it checks the condition (mark<85 && mark>=75) its false so it skips the if block and continues to the next statement (the next if block) and so on. That means: code A checks only one condition, but code B checks all conditions, and for a larger code it will take more time.

-The Nested if :
Some times, we have more than one condition we must check them all to do certain code

13

i.e. we must check many conditions and all are true to execute our code. We can do this by a large expression consists of many small expressions relational together by logic operators ((mark<85) && (mark>=75)) or using the nested if statements. if(1st expression) if(2nd expression) if(3rd expression) . . . . if(nth expression) { your code; } Example: if(math==p) if(physics==p) if(circuits==p) if(electronics==p) { cout<<clear; }

2) switch statement:
When a variable takes some certain specified values and for each value of it we wish to execute certain code i.e. when it takes value X do this when it takes value Y do this and so on, we can do this using an if-else ladder with many if statements or use a switch statement.

14

switch(variable or expression) { case 1st value: your code; break; case 2nd value: your code; break; case 3rd value: your code; break; . . . . . case nth value : your code; break; default: your code; } The compiler enters the switch block and checks case by case. If a case is matched, it executes the code associated with it, then break; statement results the compiler to exit the switch block. Notes about switch statement: 1) The variable you switch should be ONLY a (char) or (int) type. Also the expression you use should results a (char) or (int) type only. 2) No two cases can have the same value in one switch statement, however in two (or more) different switch statements they can have the same value. 3) break; statement results to exit the switch block when it finishes executing the code associated with the matched case. However break; statement is optional, you may not use it. If a case is not ended with a break; statement the compiler
15

continues to the next statement and executes the code without checking the value. Also you dont need a break; statement for the last case that the switch statement is already finished. Example: int i; cin>>i; switch(i) { case 1:

cout<<ok; break; case 2: cout<<bad; case 3: cout<<error; } For this example assume first the user entered (1), the program displays ok on the screen. But if the user entered (2) for example, the program displays bad error. 4) The default statement is optional. We use default to execute certain code when no matched case is found; you may not use it. However, the compiler executes nothing if no matched case is found and a default is not used.

2) Iteration statements:
Some times, you want to repeat a certain code for a specified number of times, or to execute the same code if a condition remains true until it becomes false. You can do this by using the iteration statements. In C++ we have 3 main types of iteration statements:

1) while loop. 2) do-while loop. 3) for loop.

16

1) while loop:
The basic form of while loop is while(expression or condition) { your code; } Here the compiler first checks the condition. If its true, it executes the code written between braces, then it returns back to the loop condition to check it again. If its true, it executes the code again and so on until the condition becomes false, then it skips the code written between braces and goes directly to the first statement after the loop block. However, if the condition of the loop is false, before the first iteration, it skips all code written between braces. So the condition must becomes false to exit from the loop, then you need to change the loop condition to become false in the code written inside braces for the next iteration to not be executed. If you didnt change the loop condition to become false, the loop will iterate forever and then its called infinite loop and results in a bug destroys the program. Example: //This code displays numbers entered by user until zero is entered int i=1; while(i!=0) { cin>>i; cout<<i; }

2) do-while loop:
do-while loop is the same as while loop except that at the first iteration it executes the code written between braces first then checks the condition, thats mean it executes your code at least once. But after the first iteration is completed the compiler checks the condition first then executes the code written between braces if the condition is true. That also means if the condition is false before the first iteration it will be executed and next iteration wont be executed.

17

The basic form of do-while loop is: do { your code; }while(expression or condition); Note: you must not forget the (;) after the while statement. Also, here you must change the condition to become false, so it doesnt result in an infinite loop. Example: //This code displays numbers entered by user until zero is entered int I; do { cin>>I; cout<<I; }while(I!=0);

3) for loop:
The for loop is the most common loop in C++ language. The basic form of for loop is: for(initialization ; condition ; step) { your code; } A for loop consists of 3 basic statements initialization, condition and step. The for loop is controlled by a variable (counter or stepper) called control variable. The initialization is a statement that sets the initial value of the control variable. Condition statement is a condition the compiler checks and executes the code written between braces if its true. Step statement identifies the step the control variable changes by every iteration.

18

The compiler first initializes the control variable, then checks the condition if its true it continues. It then executes the code written and changes the control variable by the value identified by the step statement. After this it checks the condition again if its true it continues and so on, if its false it exits from the loop and goes directly to the first statement after the loop block. The step can be incrimination or discrimination and by any value. Note that if the condition is false before the first iteration it wont iterate at all. Example: //This code displays numbers from 0 through 9 for(int i=0;i<10;i++) { cout<<i; }

Here the compiler first sets a control variable (i) by (0), then checks the condition (i<10), its true so it executes the code (displays the value of (i) on the screen) and then increments (i) by (1). It returns back to the condition to check again and so on. The last iteration (i=9) the compiler increments (i) by (1) so its (10) and then checks the condition (10<10) so its false, it wont iterate and exit from the loop. Notes on for loop: 1) The for loop is the most common loop in C++ and its most used as a counter. 2) You can leave any of the for loop statements empty or all of them. 3) A for loop without a condition statement becomes an infinite loop unless you write the condition with a break; statement inside the code written between braces. But this technique is useless. 4) A for loop without a step statement continues to iterate normally until the condition is false. You may write a step statement inside the code written between braces. 5) A for loop without an initialization statement needs the control variable to be initialized first before the loop. 6) If all statements are empty the for loop becomes an infinite loop.

19

7) You can make a time delay loop by using for loop as a counter which its condition is true for a large number of iterations, and its code is an empty statement (; only). Example: for(int i=0;i<1000;i++) ;

8) You may write more than one statement for each part of for loop. i.e. you can write more than one initialization statement or condition statement or step statement. You must separate them by ( , ) as follows: Example: for( i=0,j=10;i<10,j>0;i++,j--) { cout<<i<<endl<<j; }

Note: an empty statement is a statement ends with a ( ; ) without writing any code. For this the compiler will do nothing.

3) Jump statements:
Some times, you may need to jump from one statement to another far away -maybe before or after that statement- breaking by this the normal sequence of your program compiling. Other times you need to exit from a loop before its all iterations is completed. Jump statements are used for this. In C++ we have 3 basic jump statements: 1) break; 2) continue; 3) goto

1) break; :
break; statement is used with loops. It causes to exit the loop to the first statement after the loop block (break;).
20

2) continue; :
continue; statement is used with loops also. It causes the loop to exit the current iteration and start the next iteration immediately (continue;).

3) goto :
goto statement is used in any part of your program without any conditions. It causes the compiler to jump from one statement to any other one in your code. It breaks the normal sequence of your program compiling, therefore its strongly recommended NOT TO USE goto and try to find a more simple and better way to solve your problem. When you use goto you need to specify the place (statement) where the compiler should go, therefore you must write a specific word before the statement you wish to go to. start: cout<<hello; . . . . goto start;

21

Arrays & Strings


One-dimensional arrays:
Some times, you wish to make a list. List of variables, numbers or characters that the members of the list are related to each other. Its just like when you go to a market, you make a list of things to buy and you divide these things into groups, each group have a name and all its members are of the same kind (food, clothes, toys, etc). You can consider each group as a list of things related to each other and have a common name. In programming languages you can do the same, you can group some variables or constants together with a common name. However, in C++ its common and wide use to do lists (arrays). In fact an array in programming language is a Data Type just like int, char, float, etc. All Data Type rules are applied to the arrays. You must specify the type of your array, all the array members must be of the same type, also you need to give your array a valid name, and to specify the size of your array. The size of an array is the number or members the array can contain. The basic form of creating an array is: Data_type Example: int float list[5]; numbers[20]; valid_name [size];

List (array) The compiler holds a location in the memory for the array. It holds sequent locations for all array members 0 and of the same type. It gives this location the name you specified. Also it gives each member of the array an index (number) so you 1 can deal with any member of the array separately, these indexes starts with zero (0) and ends with (size-1) so the index of the first 2 member is always zero (0) and the index of the last member is always (size-1). However, the size of the array must be a specified constant. 3 Inside the code you can't use another variable as the size of the array even if you assigned a value for this variable before you use it as the 4 size of the array (this will give a compile error), but you still can do this using the pointers technique.
22

We now get a closer look to the memory:

int

index

Note: You must distinguish between the member index and the value stored in this member location. Notes: 1) You can deal with any member of the array separately by specifying its index as follows: array_name [index] and use this with any statement, but you cant use the array as a unit except for array of (char) as we will see later in this notes. //this code is WRONG array_name=10;

2) To fill an array members with values you must fill it one by one. However use any of: a) fill only one member by using a simple assignment statement: array_name [index]=value;

b) fill some of the members or all of them using a loop (for loop is preferred) Example: for(int i=0;i<5;i++) { cin>>list[i]; } c) fill the whole array at the declaration statement, you can also leave the size part empty and the compiler will calculate it: data_type data_type array_name [size]={ , , , , ,} ; array_name []={, , , , , };

23

d) fill the whole array at the declaration statement with the same value: data_type array_name [size]={value} ;

3) To display an array on the screen you need to use a loop to display all or some of the array members or use single statement to display only one member. Example: for(i=0;i<5;i++) { cout<<list[i] ; } 4) Your program will be destroyed, if you tried to assign values to or use members that dont exist in the array (using indexes greater than the size of the array). However, this wont cause a compile error you, must check it yourself.

Strings:
A string is an array of characters. Though its an array it has some different rules but its still created and declared using the same way:

char

array_name [size] ;

A very important difference is that the string always ends with a null byte ('\0'). A null byte is a byte that stores nothing but not zero its just stores nothing. The reason that string ends with a null byte is when you declare a string the compiler holds a location for the string in the memory. That location was holding something before (noise) and this noise is also a character so for the compiler to differentiate between the last character of the string and the noise the string always ends with null byte. Then you must ensure counting the null byte when you evaluate the string size, for example if your string is 5 characters make the size 6.

24

Example: char name[6]=Ahmed;


name

0 1 2 3 4 5

A h m e d \0

null byte

As we said string is an array of characters, and then we deal with characters, therefore we use the following rules to fill a string: 1) You can fill a string as a whole unit without using any loop: char name[6] ; name=Ahmed ; but note that we put our value between double quotes ( ). 2) You can also fill or deal with any member of the string separately by specifying the member index just like arrays. But you must put the member value between single quotes ( ) because its a character. name[2]=y ; 3) You can fill the string with the same value (character) at the declaration statement, also you can leave the size part empty and the compiler will calculate the size and will also count the null byte as follows: char name[6]={A} ; char phone_no[]=5555555;

25

Note: You can use the string as a whole unit by its name unlike the arrays, and you still can deal with any member of the string separately by specifying its index. cin>>name; cout<<name;

Multi dimensional arrays:


Two dimensional arrays:
Some times, you wish to create a table. Its allowable in C++ to do as follows: data_type valid_name [no of rows][no of coulmns]; However, its also an array called 2 dimensional array and it has the same rules of the arrays exactly.

Notes: 1) When you fill this array at the declaration statement you use as follows: Int table [3][2]={ {1,2},{3,4},{5,6} } ; 2) To fill the array using loops, use 2 nested for loops: for(int i=0;i<rows;i++) for(int j=0;j<columns;j++) cin>>array_name[i][j] ;

26

Array of strings:
Its the most common use of the 2 dimensional array technique. It means to make a list of strings (names for example). char names [5][10]; for(int i=0;i<5;i++) cin>>name[i]; However, you can make multi dimensional array not only 2. It depends on how you can imagine this array. The rules of any are the same as the one-dimensional array.

Note: We will know some useful functions that deal with strings in the part of functions.

27

Functions in C++
Introduction:
For the very early programming languages, we used to write all code in one code block, write all the code line after another in the same place and in order and the compiler used to read and execute them line by line in their order. As programs grows longer, the number of lines became more, its complexity grew faster and higher, It became clear that code cant be written in one block, and it must be broken into smaller blocks of code, simpler to use, simpler to debug and to understand. The basic benefits about separating our code to many smaller blocks are: 1- Very easy to maintain each block separately. 2- Any block can do the same code it has many times as we wish. 3- When any block is destroyed, it doesnt affect on other blocks, so we need to repair it only not all other code we have.

What is a function?!
The function is simply a block that contains code to do certain operation, you can think about it as a factory that we give what we want and the material to make it, and receive the result.

28

How to define a function:


The function definition consists of 3 main parts: 1. Function name: it is just a name we call the function by (the same idea as naming variables), the function name must never include spaces or be a reserved word (you obey the same rules of naming the variables). These names are invalid: add numbers, include, int, *. While these names are valid: add_numbers, include_file, multiply. 2- Arguments (parameters): the second part of the function declaration is its arguments, which are the data we send it to the function to operate correctly, like the 2 numbers to be added in a simple add function. The arguments are written after the function name in brackets with commas separating each one from another, our add function should look like this: int Add (int x, int y) As you see you must write the kinds of the data the function expects to get with its names, however it accepts any number of parameters you may send. 3- The return type: which is the type of data that function returns after it finishes its job, you may think about that as the final product of our factory. We write the return type before the function name, if the function doesnt return any value we have to give it the type "void" (before the function name).
29

Notes: 1. The variables we declare in a function cant be used directly in another (local variables), same for the data declared in the main, but it has to be passed first to the second function as arguments. 2. A function may take any number of arguments, and its arguments may be of different kinds of data types, like int, float, double and so on. If the function we created doesnt need to take any arguments, we leave the two brackets empty or write void in between. 3. A function can never return more than one value.

The function body:


As we said, the function is a block of code, so far we saw how to declare it but didnt write the code it includes yet. The function code is written between two braces following the declaration line, a simple add function will look like that: int add ( int x, int y) { int result =x+y; return result; } In the last line of code we saw the word return which returns the result of the function job, the product in our factory for example. If you define a function with return type int, it must have a return statement returning a variable of type int too (like our example, result is a variable of type int).
30

Important Note:
If you write your function after the main, and you wish to use it in the main, the compiler will not detect the presence of your function and will raise an error, this problem has 2 ways to be solved: 1- Write the whole function before the main function. 2- Write a prototyping for the function before the main function. The prototyping for any function is just like its declaration line ended with semicolon. Ex: int add (int x, int y); /* this is a prototyping for our simple add function*/

How can we use a function?


In order to know how to create and use a function, we will give a simple example and go step by step in the code: 1-First you must write your main. Declare your function with its code between braces following its declaration, the code will look like that #include <iostream.h> void main () { }

int add (int x, int y) { int result= x+y; return result; }

31

2- The second step is to write a prototyping for the function you want to use, before the place you will use it in, here we want to use it in the main, so we will write its prototyping before the main and right after the include statements . 3- the last step is to call the function and give it the data it needs as arguments, the call consists of the function name followed by the data it needs between brackets add (5,6); The complete code will be: #include <iostream.h> int add (int x, int y); void main () { int myresult=add(5,6); cout<<the result is :<<myresult<<endl; } int add (int x, int y) { int result=x+y; return result; }

passing variables:

We have to ways to pass variables: 1- Pass by value, which is the way we have been using so far. In the pass by value, we actually get a copy of the data, so if we pass a variable called x that contains the value
32

5, we actually copied the value (5) into a local variable inside the add function, this can be considered as a fax machine, when you send a document using it, it sends a copy but NOT THE ORIGINAL DOCUMENT. So any kind of changes you make for the copy you receive through your fax will not affect the original document. 2- Pass by reference: in this method we dont copy the data inside the variable we pass but we just rename the variable with a new name so that every change that you make to your copy of the variable affects directly the original one, simply because they are just the same variable having the same memory space but with 2 different names. You may think about that as a shared document on the internet, any computer may connect and edit that document and any other computer connects later will see the changes all the others made for the document. We use pass by reference when we need to return more than one data. Example: Let us consider a simple swap function that swaps two integer variables: We will swap two values so we need to return the two values after swapping them, we all know that is impossible because a function can never return more than one result so will use pass by reference.

33

The program will look like that: #include <iostream.h> void swap(int &x, int &y); void main () { int x=5; int y=6; swap(x,y); cout<<x<<endl<<y<<endl; } void swap ( int &x, int &y) { int temp=x; x=y; y=temp; }

Here we added the & operator in the declaration of the arguments in the function declaration, to tell the compiler to pass those values by reference and not by value. No other changes are needed; we use the same calling as in call by value.

Notes: When we call a function, we must specify its parameters in


order, so if the function is declared to take an int then a double, it must be called with the int parameter first then the double, A function declared like this: int multiply(int x,double y); Must be called like: multiply (5,66.666);
34

Overloading functions:
Some times, we want our function to act differently if we change the kind of parameters sent to it, so we use function overloading. Function overloading is to rewrite your function with the same name (and its prototyping) with a different no or kind of parameters and according to the number and kind of parameters you call the function with, it will call the right function. As a simple example we will create a function that draws a line of a character on the screen, the function will have 3 shapes: 1- Having no arguments at all, it draws a line of 20 * on the screen. 2- Having one integer parameter, the function will draw the line of the character * using that integer value as the length of the line. 3- Having an integer value and a character value, the function should draw a line of the character it receives on the screen using the integer it received as the line length.

35

The code will look like this: #include <iostream.h> void draw(); void draw(int x); void draw(int x, char y); void main () { draw(); draw(5); draw(5,f); } void draw () { for (int i =0; i<20; i++) cout<<*; cout<<endl; } void draw ( int x) { for (int i =0; i<x; i++) cout<<*; cout<<endl; } void draw (int x, char y) { for (int i =0; i<x; i++) cout<<y; cout<<endl; } The previous code will output 3 lines on the screen, the first of the character * with length 20, the second of the same character with length 5, the third with length 5 and character f.
36

Note: In all the function shapes (overloads), they must have the same name and the same return value. Important Notes: 1- You can pass variables of any type to functions that

include user defined structures (structures will be explained in the next part) and built in data types. 2- You can pass arrays to functions as arguments, but you cant return arrays as return values. 3- Passing arrays to functions is written as if you are making a pass by value, but actually passing arrays to functions is made by reference, so every change that happens for the array inside the functions, affects the original array outside the functions.

Example: #include <iostream.h> Void addtoraay(int x [5]) {for(int i=0;i<5;i++) x[i]+=5; //add 5 to each element of the array; } void main () { int x[5]={0}; //initialize the whole array with zeros. addtoarray(x); //in the function call just write the
//name of the array without index or square brackets

for(int i=0;i<5;i++) cout<<x[i]; }

37

In the previous example we saw how arrays are passed to functions, and proved that they are passed by reference, the result of the previous example will be array of 5s as a result of adding 5 to each element in the array.

38

Structures
In a considerable number of applications, we find data that are related to each other in some way. Data that we feel that should be placed in a single block. Let me give a simple example: If we are creating an application for our faculty, that manages the student affairs. We will need to keep data about each student (name, sex, age, academic year, prior results, etc.). This data must be bound together (encapsulated) in a single block for each and every student. C++ gives us the ability to do so through structures. What is a structure? A structure is a block or a capsule where related data is kept. Note that this data needn't be of the same type we can out char along with int and float without the compiler complaining and thats the main difference between a structure and an array concept wise as for syntax they are totally different.

39

Declaring a structure: Syntax: struct structure_name { int var1; float var2; char var4 //we are here declaring the needed //variables within the structure like the //student (name, sex, . Etc) }; /*don't forget the semicolon or the compiler will not understand that the structure has ended*/ Example struct student { int age; float marks [6]; chat name [100]; }; Declaring a structure variable. What we did in the previous step was declaring a new data type we must declare a structure variable in order to be able to use it. We do this in the same fashion we used with the built in data types (int, float ) Syntax: Structure_name

variable_name;

40

Example: if we declared a structure called student and want to make a structure variable called mohamed we do the following. student mohamed; Accessing the structure members: If we want to access mohamed's age and set it to 20 we type the following: mohamed.age=20; we access the arrays the same way mohamed.marks[1]=5; We can assign all the members on declaring the structure variable student mohamed={5,{5,14,25,35},"Mohamed"}; Operations on structure variables: Unlike built in data types not all the operations are available on structures

You can't do the following: Add, subtract, increment, decrement, multiply, divide or compare structure variables

41

The following staments are wrong if x and y are structure variables: x+y; x*y; x/y; x++; x--; if(x= = y) if(x<y) if(x<=y) if(x>y) if(x>=y) On the other hand we can use the assigning equal with structure variables this is very important as structures may contain dozens of members so if we can't equalize to structure variables it will be vary difficult to make identical structure variables (if we want to swap 2 variables for instance). The following statement is correct x=y; Note that for the above statement to be correct x and y must be of the same structure type (student for example) if they are of different types the compiler will complain.

42

File Streaming (File input output)


Why is file streaming study important? We can fairly say that there is no application developed by any programming language but writes to or reads from files. Files written or read by C++ C++ reads and writes two different types of files: 1-Text files. 2-Data files. We will only be concerned with the text files streaming in our study. What is a file schema?

Schema: It is the way the file is organized or formatted. When you develop a program that will write a file, you must design the way this file will look like so it is as easy to manipulate as possible. Example: If we are developing a program that will write a number of string arrays to a file, we will have to know when each string will end, and when each array of strings will end. Thinking about it we know that each string ends with a NULL bite ( /0 ).So this is the way we will identify the end of string. But how will we know when each array ends???!!

43

We can use a character to identify the end of each array. However, if we use more than one character in a known format it will be even better and nearly faultless.

Let's say that we will end each array with the following characters $$**$$ so the file will be easy to read we will read till we reach the above form filling an array then after this form we start filling the next array and so on.

How C++ writes to files? C++ writes to file using two methods located in the fstream.h header file the two methods are ifstream and it is used for file input and ofstream and is used for file output. How to use ifstream and ofstream? ifstream and ofstream are quite similar to cin and cout. The main difference between them is that ifstream and ofstream can't be used directly (as they are classes and a class is similar to a structure but can carry functions and this is beyond the scope of our study). But we have to make objects of them in a process similar to the declaration of variables, and then use the objects as we use cin and cout but instead of writing to the screen and reading from the key board we will be writing to and reading from a file.

44

Creating an ifstream object:It is simply done by typing ifstream objectName ("file name in full path between double quotations") Where ifstream is the class name (similar to the data type {int,char..} when declaring a variable). objectName stands for the name of the object (like the name of the variable in variable declaration ). Then we will have to define the file where that object will read from (giving its full path).

Reading from a file: Consider that we want to read from a file to a variable x of type integer We will have to follow the following steps:1-We include the header file fstream.h. 2-We create an ifstream object (as seen in the previous topic). 3-read the integer and place it in x;

45

Code to do this:#include <iostream.h> #include <fstream.h> void main () { int x; //for cin and cout //for ifstream

//declaring variable x of type integer ifstream infile ("example.txt"); /*creating an ifstream object and specifying the file to read from notice that you must write the extension [.txt] on the other hand if you don't specify the path to the file, the compiler will look for it in the same folder the program is in and the same goes to writing if you don't specify a path it will write to the folder the program is in*/ infile>>x ; //as you notice it is the same as using cin //and it does read in the same manner } Note that writing to files needs the same steps as reading them. The ofstream is used in the same manner cout is used but it writes to the file.

46

Example writing the variable x to the file example.txt

#include <iostream.h> //for cin and cout #include <fstream.h> //for ifstream void main () { int x=5; //declaring variable x of type integer ofstream ofile ("example.txt" ) ; /*creating an ofstream object and specifying the file to write to notice that you must write the extension [.txt] on the other hand if you don't specify the path to the file, the compiler will look for it in the same folder the program is in and the same goes to writing if you don't specify a path it will write to the folder the program is in*/ ofile <<x ; //as you notice it is the same as using cout //and it does write in the same manner } Important: Whenever you finish writing to or/and reading from a file you need to close it. If you didnt close your file, it will cause your file to be destroyed. To close your file just write the following statement: ObjectName.close(); Example : Ofile.close();

47

Detecting end of file:

As we are reading a file, we must detect its end in order to stop reading. We read files line by line so we usually use a loop to read the entire file These are some conditions that go false if the file ends or any other file reading error happens

Suppose we have the ifstream object called fin We read the file using this fin and want to stop reading if the file ends we right the following while (fin) {// right the reading code here } We can use the command while (fin.good()) Both fin and fin.good will go false if the file ends. We can use the same way in if conditions.

48

A word from the authors: We hope that this series of notes played a role in helping you in understanding the fascinating C++ and would be a brick paving your way to success. Octosoft family

49

Problems
1. Write a c++ program that allows the user to enter the measurement of an angle in degree. The program should be able to display the measurement of the angle in: 1. Degree. 2. Corresponding radian. Note: You can convert temperature from degree to radian by multiplying by pi (the circle constant=22/7) and dividing by 180.

2. Write a c++ program that allows the user to enter the measurement of temperature in degrees Celsius. The program should be able to: Display the measurement of the temperature in: 1. Degrees Celsius. 2. Corresponding degrees Fahrenheit. Note: You can convert temperature from degrees Celsius to degrees Fahrenheit by multiplying by 9/5 and adding 32.

3. Write a c++ program to that allows the user to enter the radius of a circle. The program should calculate and report: 1. The radius. 2. The diameter. 3. The circumference. 4. The area. For the circle whose radius is given as input to the program.

4. Write a c++ that requests the user to enter three integers numbers. The program should calculate and report: 1. The sum. 2. The subtraction. 3. The multiplication. 4. The average of the three numbers.

5. Write a c++ program to calculate the weekly wages of the company's workers. Each worker submits the normal and overtime hours that he worked during the week. The program produces the weekly wage as a result. Payment for one: 1. Normal hour 4 pounds. 2. Overtime hour 6 pounds.

50

Loops and Decisions


1. Write a c++ program that allows the user to enter integer number. The program should produce the next output: 1 1 1 1 . . 1

2 2 3 2 3 4

2 3 4

2. Write a c++ program that allows the user to enter integer number. The program should produce the next output: 1 1 . . 1 1 1 2 3 4 n 2 ... n-1

2 3 2

3. Write a c++ program that allows the user to enter integer number. If the number is equal to 5 the program produces the next output: 1 2 3 4 5 2 3 4 5 4 6 8 6 9 8

4. Write a c++ program to get the factorial for certain number that given by the user. Note: Factorial (5) = 5! = 5*4*3*2*1. 5. Write a c++ program that finds the number chosen by the user after requesting him to enter the remainder of the division of the number upon 3, 5, and 7. 6. Write a c++ program to show the table of multiplication. Note in This Program: If the number of the table number exceeds 9 the output of the program will be in random form. 7. Write a c++ program that reads a single character from 'a' to 'z' OR from 'A' to 'Z' and produces a pyramid of letters. For example, if the input is 'E' the output is:

A ABA ABCBA ABCDCBA ABCDEDCBA

51

8. Write a c++ program to simulate the security system in the mobile.


The program should give the user 3 trials to input his pin code successfully, and then gives him 10 trials to enter his PUK code. Any time the user enters his pin or PUK successfully, the program must terminate. If the user fails to enter his pin or PUK in all trials: The program must instruct the user to call service and terminate. Use minimum code. 9. Write a c++ that requests the user to enter two integers. The program should calculate and report the summation and the average of all integers between and including the two integers. 10. Write a c++ that requests the user to enter numbers of any type. The program should: 1. Calculate and report the sum of the past entries. 2. Terminates when a zero is entered. 11. Write an efficient C++ program to find all series of consecutive positive integers whose sum is exactly 10000.

12. Write a c++ that requests the user to enter the number of the digits he wants to enter to get the sum and the average for them. The program should calculate and report the summation and the average of all numbers.

Functions
1. Write a c++ program for a simple calculator that ask the user to enter a character such that 1. '+' to make Addition operation 2. '-' to make Subtraction operation 3. '*' to make Multiplication operation 4. '/' to make Division operation 5. 'f' OR 'F' To get the Factorial for the given number 6. 'p' OR 'P' To check the given number is Prime or not 7. 'a' OR 'A' To get the Average for some numbers 8. 'o' OR 'O' To get the raise number for a certain power 9. 'e' OR 'E' To Exit from The program . The program should make each process in a separate function.

2. Write a c++ program for a simple calculator that include function calculator that adds, subtracts, multiply, and divide any two numbers. Take into Consideration division upon zero. The calculator should have the ability to cascade the operations. Ex: Your program must be able to execute the next lines the same manner: 5 + 6 5 + 6 = 11 Then the user inputs the rest of his operations: 11 * 5 11 * 5 = 55 So the program adds 5+6 then multiplies the result by 5 and shows the result.

52

The program should put a condition to exit the calculations. 3. Write a c++ function that calculates the factorial of a number given by the user. Note: Factorial (5) =5*4*3*2*1. 4. Write a c++ function, when call it, displays a message telling how many times it has been called. Implement this function in two different ways: 1. Static function. 2. Gloable variable. 5. Write a c++ function to raise a number to a power. Where: The number and the power are given by the user. 6. Write a c++ functions that takes a positive integer number The program should be able to: a. Tells the user if the number is prime or not and return one if the number is prime and zero if not. b. Lists all prime numbers less than or equal to the user number. 7. Write a c++ function to show 1 2 3 5 8 13...... series The function takes the number of the digits in the series as an argument from the main function from the user. 8. Write a c++ program that Indicate the Overloaded function through five Draw function. 1. No Input ==> Print Word Point on the Screen. 2. One Input ==> Calculate the Area of a Circle 3. Two Input ==> Calculate the Area of a Rectangle 4. Three Inputs ==> Calculate the Area of a Triangle 5. Four Input ==> Calculate the Length of a Line Program should use switch statement to get the user choice.

Structures
1. Write a c++ structure declaration to contain the following information about complex number: 1. Real part 2. Imaginary part 3. Magntiyde value 4. Angle value The program should allow the user to: 1. Enter the complex number in the polar form or the Rec form. 2. Make addition or subtraction or multiplication or division process on the complex number. 3. Show the result in both forms. Note: Use Separate function to each process. 2. Write a c++ structure declaration to contain the following information about the date: 1. Years 2. Months 3. Days The program should allow the user to:

53

1. 2. 3. 4.

Enter the Current Date. Enter the Birth Date. Show the age of the person. Refuse the negative date and request another one.

Classes
1. Write a c++ class time that contain the following: a. simple data member : 1. Hour 2. Minute 3.second b. Some functions to: 1. Get the time class members from the user 2. Show the time class members to the user 3. Convert from second to hour, minute and second 4. Convert from hour, minute and second to equivalent second 5. Caculate the difference between two times The program should be choice between the three choices.

54

Você também pode gostar