A Summary of C++ Course

download A Summary of C++ Course

of 55

Transcript of A Summary of C++ Course

  • 8/3/2019 A Summary of C++ Course

    1/55

    Digitally signed

    by Hosam 358

  • 8/3/2019 A Summary of C++ Course

    2/55

    1

    Int roduction 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 programmingworld.

    The course does not go so deep in the details of the C++ and its related topicslike object oriented programming, but it just includes the basics of anyprogramming 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 its1-accuracy and2-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 canunderstand, those instructions tell the computer how to behave in a specificproblem

    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 computerunderstands is the machine language which is just a set of 0s and 1s, so inorder to write a single command for the computer you may need to write something 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 pointthe need for a simpler and more advanced language aroused.

  • 8/3/2019 A Summary of C++ Course

    3/55

    2

    In order to make programming easier we needed to develop new languagesnearer to our spoken languages like English, and the more the language is nearto English, the higher its level is.Now we have two kinds of languages:

    1- Languages near to the computer language, which are called low-levellanguages.

    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 Englishwords, We still need something to translate what we wrote almost in English intothe language the computer understands (machine language), and that is the ruleof the compiler.

    The compiler is an intermediate level between your program and thecomputer. It translates the words and phrases you write into machine languageso the computer will understand it and execute it.Now you can write your program in a simple way near to English language andrely 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++:Lets consider the simplest program represented next:

    #include

    void main ()

    {

    cout

  • 8/3/2019 A Summary of C++ Course

    4/55

    3

    The main program body is a function called: main ()

    The main is the function that represents the whole program, when thecomputer runs the program, it searches for the main and begin with the first lineof code inside it and closes when it reaches the last line, an empty program maylook like this:

    void main ()

    {

    }

    Statement:Inside our example programs main, we find the line of code: cout

  • 8/3/2019 A Summary of C++ Course

    5/55

    4

    The data we use may be the length of a square in a geometric program or theage of a student in a school database program; the functions on the data mayinclude the process of getting the area of the square or the average age ofschool students.

    In order to use data in our programs, we must save them a place in thecomputer memory, so that we may save, edit, retrieve and manipulate the dataquickly during the program runs, to do this we have to declare variables.

    Variablesis places for data in memory, we reserve a place for our data, andcall 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 spaceand 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 ofmemory space and it is usually used to hold fractional numbers like 2.4,3.55 .

    3- charand this type is a very special type as it may be used to representnumbers or characters as we will see in moments, this type takes 1 byteof memory space.

    4- double and this is a data type that carries fractional data just like floatbut 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 ornumbers, 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 andended by the semicolon.

  • 8/3/2019 A Summary of C++ Course

    6/55

    5

    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 namemust 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 ofyour 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 agood 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 arerepresented and manipulated in the computer as numbers for example, thecapital 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 usingthe 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 usea special syntax for each case,

    1-Output using cout:To output a value we write the keyword cout then we use the operator

  • 8/3/2019 A Summary of C++ Course

    7/55

    6

    To print the contents of a data variable we put the name of the variable without

    quotationmarks after the operator

  • 8/3/2019 A Summary of C++ Course

    8/55

    7

    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 constantvalue, 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 bethe name of a variable; it cannot be an expression the following code is notallowed in C++:

    x1+x2= x1*x2/2; // error

    Arithmetic Precedence:The order of arithmetic operations in a complicated expression is the same asthe order in math, the multiplication and division is made first, then addition orsubtraction.

    If you want to force part of a complicated expression to be done, first you useparentheses.

  • 8/3/2019 A Summary of C++ Course

    9/55

    8

    Example: Determine the result of the following code:

    #include void main()

    {

    int x1=5;

    int x2=6;

    int result;

    result=x1*5+x2;

    cout

  • 8/3/2019 A Summary of C++ Course

    10/55

    9

    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 thecomputer to use a special data type in the temporary data memory we use thecast syntax.The cast syntax consists of the desired data type put between parenthesesbefore 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

  • 8/3/2019 A Summary of C++ Course

    11/55

    10

    Statements

    In programming languages, we use many commands. Each does some thing for usdepending on its type. We use any of them where and when we need depending on ourprogram logic.

    These statements are separated into 3 basic types:

    1) Conditional statements.2) Iteration or Loopstatements.3) Jump statements.

    Operators:

    We use some useful operators with these statements and they are separated into 2 maintypes:

    1)Arithmetic operators:

    2) Logic operators:

    > Greater than

    >= Greater than or equal

  • 8/3/2019 A Summary of C++ Course

    12/55

    11

    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 becomestruethe 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) ifstatement: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 betweenbraces. 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

  • 8/3/2019 A Summary of C++ Course

    13/55

    12

    Some times, you need to execute certain code if the condition is true or to execute anothercode 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

  • 8/3/2019 A Summary of C++ Course

    14/55

    13

    -The if-else ladder:

    Code A Code B

    if(mark>=85) if(mark>=85){ grade=A;

    grade=A;

    } if(mark=75)

    else if(mark=75) grade=B;

    {

    grade=B; if(mark=65)

    } grade=C;

    else if(mark=65){

    grade=C; if(mark=50)

    } grade=D;

    else if(mark=50)

    { if(mark=85) then its true, the compiler executes the code associated with thatcondition block (grade=A;) and skips all other conditions (no need to check all otherconditions that the first one is true) and goes directly to the first statement after the if-elseladder block.

    But for code B, the compiler checks the first expression (mark>=85) then its true so itexecutes the code associated with that condition (grade=A;) and goes to the nextstatement i.e. it goes to the next if block, it checks the condition (mark=75)its false so it skips the if block and continues to the next statement (the next ifblock) andso on. That means: code A checks only one condition, but code B checks all conditions, andfor 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

  • 8/3/2019 A Summary of C++ Course

    15/55

    14

    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 togetherby logic operators ((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

  • 8/3/2019 A Summary of C++ Course

    16/55

    15

    switch(variable or expression)

    {

    case 1st value:

    your code;

    break;

    case 2nd value:

    your code;

    break;

    case 3rd value:

    your code;break;

    .

    .

    .

    .

    .

    case nthvalue :

    your code;

    break;

    default:

    your code;

    }

    The compiler enters the switch block and checks case bycase. If a case is matched, itexecutes the code associated with it, then break; statement results the compiler to exit theswitch block.

    Notes about switch statement:

    1) The variable you switch should be ONLY a (char) or (int) type. Also the expressionyou 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 (ormore) different switch statements they can have the same value.

    3) break; statement results to exit the switch block when it finishes executing thecode associated with the matched case. However break; statement is optional, youmay not use it. If a case is not ended with a break; statement the compiler

  • 8/3/2019 A Summary of C++ Course

    17/55

    16

    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 statementis already finished.

    Example:

    int i;

    cin>>i;

    switch(i)

    {

    case 1:

    cout

  • 8/3/2019 A Summary of C++ Course

    18/55

    17

    1) while loop:

    The basic form ofwhile loop is

    while(expression or condition)

    {

    your code;

    }

    Here the compiler first checks the condition. If its true, it executes the code written betweenbraces, 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 writtenbetween braces and goes directly to the first statement after the loop block. However, if thecondition of the loop is false, before the first iteration, it skips all code written betweenbraces. So the condition must becomes false to exit from the loop, then you need to changethe loop condition to become false in the code written inside braces for the next iteration tonot be executed. If you didnt change the loop condition to become false, the loop will iterateforever 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

  • 8/3/2019 A Summary of C++ Course

    19/55

    18

    The basic form ofdo-while loop is:

    do

    {

    your code;

    }while(expression or condition);

    Note: you m ust not forget the (;) after the while statement.

    Also, here you must change the condition to become false, so it doesnt result in an infiniteloop.

    Example:

    //This code displays numbers entered by user until zero is entered

    int I;

    do

    {

    cin>>I;

    cout

  • 8/3/2019 A Summary of C++ Course

    20/55

    19

    The compiler first initializes the control variable, then checks the condition if its true itcontinues. It then executes the code written and changes the control variable by the valueidentified by the step statement.After this it checks the condition again if its true it continues and so on, if its false it exitsfrom the loop and goes directly to the first statement after the loop block. The step can beincrimination or discrimination and by any value. Note that if the condition is false beforethe first iteration it wont iterate at all.

    Example:

    //This code displays numbers from 0 through 9

    for(int i=0;i

  • 8/3/2019 A Summary of C++ Course

    21/55

    20

    7)You can make a time delay loop by using forloop as a counter which its condition istrue for a large number of iterations, and its code is an empty statement (; only).

    Example:

    for(int i=0;i

  • 8/3/2019 A Summary of C++ Course

    22/55

    21

    2) continue; :

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

    3) goto :

    goto statement is used in any part of your program without any conditions. It causesthe compiler to jump from one statement to any other one in your code. It breaks thenormal sequence of your program compiling, therefore its strongly recommended NOTTO 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 compilershould go, therefore you must write a specific word before the statement you wish to goto.

    start: cout

  • 8/3/2019 A Summary of C++ Course

    23/55

    22

    Arrays & Str ings

    One-dimensional arrays:

    Some times, you wish to make a list. List of variables, numbers or characters that themembers of the list are related to each other. Its just like when you go to a market, youmake a list of things to buy and you divide these things into groups, each group have a nameand all its members are of the same kind (food, clothes, toys, etc). You can consider eachgroup as a list of things related to each other and have a common name. In programminglanguages you can do the same, you can group some variables or constants together with acommon 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 DataType rules are applied to the arrays.

    You must specify the type of your array, all the array members must be of the same type, alsoyou need to give your array a valid name, and to specify the size of your array. The size of anarray is the number or members the array can contain.

    The basic form of creating an array is:

    Data_type valid_name [size];

    Example:

    int list[5];

    float numbers[20];

    We now get a closer look to the memory:List (array) int

    The compiler holds a location in the memory forthe array. It holds sequent locations for all array members 0and 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 1can deal with any member of the array separately, these indexesstarts with zero (0) and ends with (size-1) so the index of the first 2member 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. 3Inside the code you can't use another variable as the size of the arrayeven if you assigned a value for this variable before you use it as the 4size of the array (this will give a compile error), but you still can dothis using the pointers technique.

    index

  • 8/3/2019 A Summary of C++ Course

    24/55

    23

    Note: You must distinguish between the member index and the value stored in this memberlocation.

    Notes:

    1) You can deal with any member of the array separately by specifying its index asfollows:

    array_name [index]

    and use this with any statement, but you cant use the array as a unit except for arrayof (char) as we will see later in this notes.

    //this code is WRONG

    array_name=10; X

    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 (forloop is preferred)Example:

    for(int i=0;i>list[i];

    }

    c) fill thewhole array at the declaration statement, you can also leave the sizepart empty and the compiler will calculate it:

    data_type array_name [size]={ , , , , ,} ;

    data_type array_name []={, , , , , };

  • 8/3/2019 A Summary of C++ Course

    25/55

    24

    d) fill thewhole 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 thearray members or use single statement to display only one member.

    Example:for(i=0;i

  • 8/3/2019 A Summary of C++ Course

    26/55

    25

    0

    1

    2

    3

    4

    5

    name

    null byte

    Example:

    char name[6]=Ahmed;

    As we said string is an array of characters, and then we deal with characters, therefore weuse 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 themember index just like arrays. But you must put the member value between singlequotes ( ) 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 willalso count the null byte as follows:

    char name[6]={A} ;

    char phone_no[]=5555555;

    A

    h

    m

    e

    d\0

  • 8/3/2019 A Summary of C++ Course

    27/55

    26

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

    cin>>name;

    cout

  • 8/3/2019 A Summary of C++ Course

    28/55

    27

    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>name[i];

    However, you can make multi dimensional array not only 2. It depends on how you canimagine 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 thepart of functions.

  • 8/3/2019 A Summary of C++ Course

    29/55

    28

    Function s in C++

    Introduction:

    For the very early programming languages, we used to writeall code in one code block, write all the code line afteranother in the same place and in order and the compilerused 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 thatcode cant be written in one block, and it must be broken intosmaller blocks of code, simpler to use, simpler to debug andto 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 wehave.

    What is a function?!

    The function is simply a block that contains code to docertain operation, you can think about it as a factory that wegive what we want and the material to make it, and receivethe result.

  • 8/3/2019 A Summary of C++ Course

    30/55

    29

    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 namemust never include spaces or be a reserved word (youobey 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 itto the function to operate correctly, like the 2 numbers to beadded in a simple add function.

    The arguments are written after the function name inbrackets with commas separating each one from another, ouradd function should look like this:

    int Add (int x, int y)

    As you see you must write the kinds of the data the functionexpects 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 functionreturns after it finishes its job, you may think about that asthe 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).

  • 8/3/2019 A Summary of C++ Course

    31/55

    30

    Notes:

    1. The variables we declare in a function cant be useddirectly in another (local variables), same for the datadeclared in the main, but it has to be passed first to thesecond function as arguments.

    2.A function may take any number of arguments, and itsarguments may be of different kinds of data types, likeint, float, double and so on.

    If the function we created doesnt need to take any

    arguments, we leave the two brackets empty or writevoidin 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 followingthe 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 ourfactory for example. If you define a function with returntype int, it must have a return statement returning a

    variable of type int too (like our example, result is a variableof type int).

  • 8/3/2019 A Summary of C++ Course

    32/55

    31

    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 presenceof your function and will raise an error, this problem has 2ways to be solved:

    1-Write the whole function before the main function.2-Write a prototyping for the function before themain function.

    The prototyping for any function is just like itsdeclaration 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 willgive a simple example and go step by step in the code:

    1-First you must write your main. Declare your functionwith its code between braces following its declaration, thecode will look like that

    #include

    void main ()

    {

    }

    int add (int x, int y)

    {

    int result= x+y;

    return result;

    }

  • 8/3/2019 A Summary of C++ Course

    33/55

    32

    2- The second step is to write a prototyping for thefunction you want to use, before the place you will use

    it in, here we want to use it in the main, so we willwrite its prototyping before the main and right afterthe include statements .

    3-the last step is to call the function and give it thedata it needs as arguments, the call consists of thefunction name followed by the data it needsbetween brackets

    add (5,6);

    The complete code will be:

    #include

    int add (int x, int y);

    void main ()

    {

    int myresult=add(5,6);

    cout

  • 8/3/2019 A Summary of C++ Course

    34/55

    33

    5, we actually copied the value (5) into a local variableinside the addfunction, this can be considered as a fax

    machine, when you send a document using it, it sendsa copy but NOT THE ORIGINAL DOCUMENT. So anykind of changes you make for the copy you receivethrough your fax will not affect the original document.

    2-Pass by reference: in this method we dont copy thedata inside the variable we pass but we just renamethe variable with a new name so that every change

    that you make to your copy of the variable affectsdirectly the original one, simply because they arejust the same variable having the same memoryspace but with 2 different names.You may think about that as a shared document onthe internet, any computer may connect and editthat document and any other computer connectslater will see the changes all the others made for thedocument.

    We use pass by reference when we need to returnmore 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 isimpossible because a function can never returnmore than one result so will use pass by reference.

  • 8/3/2019 A Summary of C++ Course

    35/55

    34

    The program will look like that:

    #include void swap(int &x, int &y);

    void main ()

    {

    int x=5;

    int y=6;

    swap(x,y);

    cout

  • 8/3/2019 A Summary of C++ Course

    36/55

    35

    Overloading functions:

    Some times, we want our function to act differently if wechange the kind of parameters sent to it, so we use functionoverloading.

    Function overloading is to rewrite your function with thesame name (and its prototyping) with a different no or kindof parameters and according to the number and kind ofparameters you call the function with, it will call the right

    function.

    As a simple example we will create a function that draws aline of a character on the screen, the function will have 3shapes:

    1-Having no arguments at all, it draws a line of 20 * onthe screen.

    2-Having one integer parameter, the function will drawthe line of the character * using that integer value as

    the length of the line.

    3-Having an integer value and a character value, thefunction should draw a line of the character it receiveson the screen using the integer it received as the line

    length.

  • 8/3/2019 A Summary of C++ Course

    37/55

    36

    The code will look like this:

    #include 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

  • 8/3/2019 A Summary of C++ Course

    38/55

  • 8/3/2019 A Summary of C++ Course

    39/55

    38

    In the previous example we saw how arrays are passed tofunctions, and proved that they are passed by reference, the

    result of the previous example will be array of 5s as a resultof adding 5 to each element in the array.

  • 8/3/2019 A Summary of C++ Course

    40/55

    39

    Structures

    In a considerable number of applications, we find

    data that are related to each other in some way. Data thatwe feel that should be placed in a single block.

    Let me give a simple example:

    If we are creating an application for our faculty, thatmanages the student affairs. We will need to keep dataabout each student (name, sex, age, academic year, prior

    results, etc.). This data must be bound together(encapsulated) in a single block for each and everystudent.

    C++ gives us the ability to do so through structures.

    W hat is a structure?

    A structure is a block or a capsule where related datais kept.

    Note that this data needn't be of the same type wecan out charalong with int and float without thecompiler complaining and thats the maindifference between a structure and an arrayconcept wise as for syntax they are totallydifferent.

  • 8/3/2019 A Summary of C++ Course

    41/55

    40

    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 newdata type we must declare a structure variable in order tobe able to use it. We do this in the same fashion we usedwith the built in data types (int, float )

    Syntax:Structure_name variable_name;

  • 8/3/2019 A Summary of C++ Course

    42/55

    41

    Example: if we declared a structure called student andwant to make a structure variable called mohamed we dothe following.

    student mohamed;

    Accessing the structure m em bers:

    If we want to access mohamed's age and set it to 20we 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 structurevariable

    student mohamed={5,{5,14,25,35},"Mohamed"};

    Operations on structure var iables:

    Unlike built in data types not all the operations areavailable on structures

    You can't do the following:

    Add, subtract, increment, decrement, multiply, divide orcompare structure variables

  • 8/3/2019 A Summary of C++ Course

    43/55

    42

    The following staments are wrong if x and y arestructure variables:

    x+y;

    x*y;

    x/y;

    x++;

    x--;

    if(x= = y)

    if(x=y)

    On the other hand w e can use the assigning equal with structure variables this is very important asstructures may contain dozens of members so if we can'tequalize to structure variables it will be vary difficult tomake identical structure variables (if we want to swap 2

    variables for instance).

    The follow ing statement is corr ect

    x=y;

    Note that for the above statement to be correct xand ymu st be of the sam e structure type (student

    for example) if they are of different types thecompiler w ill complain.

  • 8/3/2019 A Summary of C++ Course

    44/55

    43

    File Stream ing (File input ou tput)

    W hy is file streaming study im portant?

    We can fairly say that there is no application developed byany programming language but writes to or reads fromfiles.

    Files w ritten o r r ead 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 inour study.

    W hat 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 mustdesign the way this file will look like so it is as easy tomanipulate as possible.

    Example:

    If we are developing a program that will write a number ofstring arrays to a file, we will have to know when eachstring will end, and when each array of strings will end.

    Thinking about it we know that each string ends with aNULL bite ( /0 ).So this is the way we will identify the endof string.But how will we know when each array ends???!!

  • 8/3/2019 A Summary of C++ Course

    45/55

    44

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

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

    How C++ wr ites to files?

    C++ writes to file using two methods located in thefstream.h header file the two methods are ifstreamand it is used for file input and ofstreamand is used forfile output.

    How to use ifstreamand ofstream?ifstream and ofstream are quite similar to cin andcout. The main difference between them is that ifstreamand ofstream can't be used directly (as they are classesand a class is similar to a structure but can carry functionsand this is beyond the scope of our study). But we have to

    make objects of them in a process similar to the declarationof variables, and then use the objects as we use cin andcout but instead of writing to the screen and reading fromthe key board we will be writing to and reading from a file.

  • 8/3/2019 A Summary of C++ Course

    46/55

    45

    Crea ting an ifstreamobject:-

    It is simply done by typing

    ifstream objectName("file name in full pathbetween double quotations")

    Where ifstream is the class name (similar to the datatype {int,char..} when declaring a variable). objectNamestands for the name of the object (like the name of thevariable in variable declaration ).

    Then we will have to define the file where that object willread from (giving its full path).

    Reading from a file:

    Consider that we want to read from a file to a variable x oftype 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;

  • 8/3/2019 A Summary of C++ Course

    47/55

    46

    Code to do this:-

    #include //for cin and cout

    #include //for ifstream

    void main ()

    {

    int x;

    //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 readingthem.

    The ofstream is used in the same manner cout is usedbut it writes to the file.

  • 8/3/2019 A Summary of C++ Course

    48/55

    47

    Exam ple writing the variable xto the file example.txt

    #include //for cin and cout

    #include //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 handif 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

  • 8/3/2019 A Summary of C++ Course

    49/55

    48

    Detecting en d of file:

    As we are reading a file, we must detect its end inorder to stop reading.

    We read files line by line so we usually use a loop toread the entire file

    These are some conditions that go false if the fileends 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 stopreading 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.goodwill go false if the file ends.

    We can use the same way in ifconditions.

  • 8/3/2019 A Summary of C++ Course

    50/55

    49

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

    Octosoft family

  • 8/3/2019 A Summary of C++ Course

    51/55

    50

    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.

  • 8/3/2019 A Summary of C++ Course

    52/55

    51

    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 2

    1 2 3

    1 2 3 4

    .

    .

    1 2 3 4 n

    2. Write a c++ program that allows the user to enter integer number.

    The program should produce the next output:

    1 2 3 4 n

    1 2 ... n-1

    .

    .

    1 2 3

    1 2

    1

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

    3 6 9

    4 8

    5

    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

    ABCDCBAABCDEDCBA

  • 8/3/2019 A Summary of C++ Course

    53/55

    52

    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 toenter 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 theresult.

  • 8/3/2019 A Summary of C++ Course

    54/55

    53

    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 value4. 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. Months3. Days

    The program should allow the user to:

  • 8/3/2019 A Summary of C++ Course

    55/55

    1. Enter the Current Date.

    2. Enter the Birth Date.

    3. Show the age of the person.

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