Ch02 C++ Programming Basics

Embed Size (px)

Citation preview

  • 8/6/2019 Ch02 C++ Programming Basics

    1/62

    Introduction to Programming

    Engr. Rashid Farid [email protected]

    Chapter 02: C++ Programming Basics

    International Islamic University H-10, Islamabad, Pakistan

    http://www.iiu.edu.pk

  • 8/6/2019 Ch02 C++ Programming Basics

    2/62

    Basic Program Construction

    //first.cpp#include

    using namespace std;

    int main()

    {

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    3/62

    Basic Program Construction Because of the parentheses() the compiler

    comes to know that this a function not avariable.

    The parentheses arent always empty. Theyre

    used to hold function arguments (values passed

    from the calling program to the function).

    Line number 2 and 3 are not part of the

    function.

    The word int preceding the function name

    indicates that this particular function has a

    return value of type int. The bodyof a function is surrounded by braces

    (sometimes called curly brackets).

  • 8/6/2019 Ch02 C++ Programming Basics

    4/62

    Basic Program Construction Every function must use this pair of braces

    around the function body.

    A function body can consist of many statements

    but this function has only two statements

    (line nunber 6 and 7)

    You can put several statements on one line and

    one statement in over two or more lines.

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    5/62

    Basic Program Construction We dont recommend these syntax. its

    nonstandard and hard to read. but it doescompile correctly.

    #include is a preprocessor directive, which

    must be written on one line.

    A string constant Welcome to this course\n

    can also be broken into separate lines if uinsert a backslash (\) at the line break or

    divide the string into two separate strings,

    each surrounded by quotes

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    6/62

    Basic Program Construction We dont recommend these syntax. its

    nonstandard and hard to read. but it doescompile correctly.

    #include is a preprocessor directive, which

    must be written on one line.

    A string constant Welcome to this course\n

    can also be broken into separate lines.e.g.

    A programs may consists of many functions but

    themain() function will be executed first.

    If there is no function calledmain() in your

    program, an error will be reported when yourun the program.

    main() function may also call other functions.

  • 8/6/2019 Ch02 C++ Programming Basics

    7/62

  • 8/6/2019 Ch02 C++ Programming Basics

    8/62

    Program Statements There are two statements this program

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    9/62

    Output usingcoutcout

  • 8/6/2019 Ch02 C++ Programming Basics

    10/62

    Output usingcout

    (If you know C, youll recognize

  • 8/6/2019 Ch02 C++ Programming Basics

    11/62

    String Constants The phrase in quotation marks, Welcome to

    this course\n, is an example of a stringconstant.

    A constant, unlike a variable, cannot be given

    a new value as the program runs. Its value is

    set when the program is written, and it

    retains this value throughout the programsexistence.

    The \n character at the end of the string

    constant is an example of an escape sequence.

    The \n causes the next text output to be

    displayed on a new line.

    Line no. 2 and 3 in our program are called

    directives. The first is apreprocessor

    directive,and the second is a using directive.

  • 8/6/2019 Ch02 C++ Programming Basics

    12/62

    Directives Theyre not part of the basic C++ language,

    but theyre necessary anyway.Preprocessor Directives

    #include

    This is not a program statement or a part of a

    function body. It starts with a number sign

    (#). Its called apreprocessor directive.

    Recall thatprogram statements are instruct-

    ions to the computer to do something, such as

    adding two numbers or printing a sentence.

    A preprocessor directive, on the other hand,is an instruction to the compiler. A part of

    the compiler called thepreprocessordeals

    with these directives before it begins the

    real compilation process.

  • 8/6/2019 Ch02 C++ Programming Basics

    13/62

    #include Directive Thepreprocessor directive #include tells the

    compiler to insert another file into yoursource file. In effect, the #include directive

    is replaced by the contents of the file

    indicated.

    Using an #include directive to insert another

    file into your source file is similar topasting a block of text into a document with

    your word processor.

    #include is only one of many preprocessor

    directives, all of which can be identified by

    the initial # sign.

    The type file usually included by #include is

    called a header file.

  • 8/6/2019 Ch02 C++ Programming Basics

    14/62

    Header Files In our program the preprocessor directive

    #include tells the compiler to add the sourcefile IOSTREAM to the FIRST.CPP source file

    before compiling.

    IOSTREAM is an example of a header file

    (sometimes called an include file). Its

    concerned with basic input/output operations,and contains declarations that are needed by

    the cout identifier and the

  • 8/6/2019 Ch02 C++ Programming Basics

    15/62

    usingDirective A C++ program can be divided into different

    namespaces. A namespace is a part of theprogram in which certain names are recognized;

    outside of the namespace theyre unknown.

    The directive using namespace std; says that

    all the program statements that follow are

    within the std namespace. Various program components such as cout are

    declared within this namespace. If we didnt

    use the using directive, we would need to add

    the std name to many program elements.e.g.

    std::cout

  • 8/6/2019 Ch02 C++ Programming Basics

    16/62

    Comments Comments help the person writing a program,

    and anyone else who must read the source file,understand whats going on.

    The compiler ignores comments, so they do not

    add to the file size or execution time of the

    executable program.

    Comments start with a double slash symbol (//)and terminate at the end of the line

    //first.cpp

    #include //preprocessor directive

    using namespace std; //using directive

    int main() //function name main

    { //start function body

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    17/62

    Other Styles of Comments/* this is an old-style comment */

    /* this

    is a

    potentially

    very long

    multilinecomment

    */

    intmain(/* a comment within parentheses*/)

    { /* this is comment into the function body */ }

    1

    2

    3

    4

    5

    6

    78

    9

    10

    11

    1213

    14

    15

    16

  • 8/6/2019 Ch02 C++ Programming Basics

    18/62

    Integer Variable Variables are the most fundamental part of any

    language. A variable has a symbolic name andcan be given a variety of values.

    Variables are located in particular places in

    the computers memory. When a variable is

    given a value, that value is actually placed

    in the memory space assigned to the variable. Integer variables represent integer numbers

    like 1, 30,000, and 27. Such numbers are used

    for counting discrete numbers of objects, like

    11 pencils or 99 bottles of beer.

    integers have no fractional part; you can

    express the idea of four using integers, but

    not four and one-half.

  • 8/6/2019 Ch02 C++ Programming Basics

    19/62

    Defining an Integer Variable Integer variables exist in several sizes, but

    the most commonly used is type int. The amount of memory occupied by the integer

    types is system dependent.

    On a 32-bit system such as Windows, an int

    occupies 4 bytes (which is 32 bits) of memory.

    This allows an int to hold numbers in therange from 2,147,483,648 to 2,147,483,647.

    The type int occupies 4 bytes on current

    Windows computers, it occupied only 2 bytes in

    MS-DOS and earlier versions of Windows.

  • 8/6/2019 Ch02 C++ Programming Basics

    20/62

    Figure: A variable of type int in memory

  • 8/6/2019 Ch02 C++ Programming Basics

    21/62

    Defining an Integer Variable// intvars.cpp

    // demonstrates integer variables

    #include

    using namespace std;

    int main(){

    int var1; //define var1

    int var2; //define var2

    var1 = 20; //assign value to var1

    var2 = var1 + 10; //assign value tovar2

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    22/62

    Code Explanation The statements int var1; int var2; define two

    variables, var1 and var2 of type integer.

    These statements, which are called

    declarations, must terminate with a semicolon

    You must declare a variable before using it.

    However, you can place variable declarationsanywhere in a program. Its not necessary to

    declare variables before the first executable

    statement (as was necessary in C).

    A declaration introduces a variables name

    (such as var1) into a program and specifiesits type (such as int).

    if a declaration also sets aside memory for

    the variable, it is also called a definition.

  • 8/6/2019 Ch02 C++ Programming Basics

    23/62

    Variable Names The statements int var1; int var2; in the

    program are definitions, as well as declara-tions, because they set aside memory for var1

    and var2.

    The program uses variables named var1 and var2

    The names given to variables are called

    identifiers. You can use upper and lowercaseletters, and the digits from 1 to 9. You can

    also use the underscore (_).

    The first character must be a letter or

    underscore. Identifiers can be as long as you

    like, but most compilers will only recognize

    the first few hundred characters. The compiler

    distinguishes between upper- and lowercase

    letters, so Var is not the same as var or VAR.

  • 8/6/2019 Ch02 C++ Programming Basics

    24/62

    keyword You cant use a C++ keyword as a variable

    name. A keywordis a predefined word with aspecial meaning. int, class, if, andwhile are

    examples of keywords. A complete list of

    keywords can be found in Appendix B.

    A variables name should make clear to anyone

    reading the listing variables purpose and howit is used. Thus a variable int age is better

    than something simple like int a or int aa.

    The statements var1 = 20; var2 = var1 + 10;assign values to the two variables.

    The equal sign (=), causes the value on the

    right to be assigned to the variable on the

    left. in the statement var1 = 20; var1, which

    had no value, is given the value 20.

  • 8/6/2019 Ch02 C++ Programming Basics

    25/62

    Integer constant The number 20 is an integer constant.Constants

    dont change during the course of the program. An integer constant consists of numerical

    digits. There must be no decimal point in an

    integer constant, and it must lie within the

    range of integers.

    In the second program line, the plus sign (+)adds the value of var1 and 10, in which 10 is

    another constant. The result of this addition

    is then assigned to var2.

    The statement cout

  • 8/6/2019 Ch02 C++ Programming Basics

    26/62

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    27/62

    The endl Manipulator The last cout statement in the INTVARS program

    ends with an unfamiliar word: endl. Thiscauses a linefeed to be inserted into the

    stream, so that subsequent text is displayed

    on the next line.

    It has the same effect as sending the \n

    character, but is somewhat clearer.

    Its an example of amanipulator. Manipulators

    are instructions to the output stream that

    modify the output in various ways; well see

    more of them as we go along. Strictly

    speaking, endl (unlike \n) also causes the

    output buffer to be flushed, but this happens

    invisibly so for most purposes the two are

    equivalent.

  • 8/6/2019 Ch02 C++ Programming Basics

    28/62

    C++ Data TypesData Type Size Range

    bool 1 byte true(1) or false(0)

    (signed)char 1 byte (-27)~(+27-1) = -128 ~ +127

    unsigned char 1 byte 0 ~ 28-1 = 0 to 255 or

    256 Different ASCII Characters

    short(short int)

    2 bytes (-215)~(+215-1) =-32,768 ~ +32,767

    unsigned short 2 bytes 0 ~ 216-1 = 0 to 65,536

    int

    (signed int)

    4 bytes (-231)~(+231-1) =

    -2147483648 ~ +2147483647unsigned int 4 bytes 0 ~ (232-1) =

    0 ~ 4,29,49,67,296

    long

    (long int)

    4 bytes (-231)~(+231-1) =

    -2147483648 ~ +2147483647

  • 8/6/2019 Ch02 C++ Programming Basics

    29/62

    C++ Data TypesData Type Size Range

    unsigned

    long

    4 bytes 0 ~ 4,29,49,67,296

    float 4 bytes (1.2 10-38 ~ 3.4 1038)

    double 8 byte +(2.2 10-308 ~ 1.7 10308)

    -(2.3 10-308 ~ 1.7 10308)

    specifying type long will guarantee a four-bit

    integer type on a 16-bit system such as MS-DOS

    In 16-bit systems, type int has the same range

    as type short.

    On all systems type short occupies two bytes.

  • 8/6/2019 Ch02 C++ Programming Basics

    30/62

    C++ Data Typeslong v1 = 7678L; // assigns long constant

    // 7678 to v1 of type long

    Many compilers offer integer types that

    explicitly specify the number of bits used.

    They are __int8, __int16, __int32, and __int64

    char data type is used to store numbers thatconfine themselves to a limited range, but it

    is commonly used to storeASCII characters.

    ASCII character set is a way of representing

    English alphabet in a 8-bit space.

    Character constants use single quotation marksaround a character, like a and b. (Note

    that this differs from string constants, which

    use double quotation marks)

  • 8/6/2019 Ch02 C++ Programming Basics

    31/62

    C++ Data Types When the C++

    compilerencounters such a

    character

    constant, it

    translates it into

    the correspondingASCII code.

    The constant a

    appearing in a

    program, for

    example, will betranslated into

    97, as shown in

    Figure.

  • 8/6/2019 Ch02 C++ Programming Basics

    32/62

  • 8/6/2019 Ch02 C++ Programming Basics

    33/62

  • 8/6/2019 Ch02 C++ Programming Basics

    34/62

    Programming Example// charvars.cpp

    // demonstrates character variables

    #include //for cout, etc.

    using namespace std;

    intmain()

    {

    char charvar1 = 'A'; //define character variable

    char charvar2 = '\t'; //define character variable

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    35/62

    Escape sequence '\t' and '\n', are special character with have

    different behavior. These are called escapesequence. The name reflects the fact that the

    backslash causes an escape from the normal

    way characters are interpreted.

    In this case the t is interpreted not as the

    character 't' but as the tab character. A tabcauses printing to continue at the next tab

    stop.

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    36/62

    Escape sequenceThis translates to

    "Run, Forrest, run," she said.

    Sometimes you need to represent a character

    constant that doesnt appear on the keyboard,

    such as the graphics characters above ASCII

    code 127.

    To do this, you can use the '\xdd' representa-

    tion, where each dstands for a hexadecimal

    digit. If you want to print a solid rectangle,

    for example, youll find such a character

    listed as decimal number 178, which ishexadecimal number B2 in the ASCII table.

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    37/62

    ASCII TABLE

    #include

    #include

    using namespace std;

    intmain(){

    unsigned char ch;

    for(ch=0 ; ch

  • 8/6/2019 Ch02 C++ Programming Basics

    38/62

    Input with cin#include //for cout, etc.

    #include

    using namespace std;

    intmain(){

    int A,B,AVG; // run again for float data type

    cout >A;

    cout B;

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    39/62

    Input with cin// fahren.cpp

    // demonstrates cin, newline

    #include

    using namespace std;

    intmain()

    {

    int ftemp; //for temperature in fahrenheit

    cout ftemp;

    int ctemp = (ftemp-32) * 5 / 9;

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    40/62

    Input with cin The statement cin >> ftemp; causes the program to wait

    for the user to type in a number. The resulting number is placed in the variable ftemp. The

    keyword cin (pronounced C in) is an object, predefinedin C++ to correspond to the standard input stream.

    This stream represents data coming from the keyboard(unless it has been redirected).

    echo 100 | first.exe (type in DOS)

    The >>is the extraction or get from operator. It takes

    the value from the stream object on its left and places

    it in the variable on its right.

  • 8/6/2019 Ch02 C++ Programming Basics

    41/62

    Input with cin insertion operator >can be used repeatedly with

    cin, allowing user to enter a series of values.

    Any arrangement of variables, constants, andoperators that specifies a computation is called an

    expression, Thus, alpha+12 and (alpha-37)*beta/2are expressions.

    Statements tell the compiler to do something and

    terminate with a semicolon, while expressionsspecify a computation.

    T

    here can be several expressions in a statement. If both *(multiply) and -(subtract) are present in

    an expression then the multiplication would be

    carried out first, since * has higher priority Than

    * and / have the same precedence. the one on theleft is executed first

  • 8/6/2019 Ch02 C++ Programming Basics

    42/62

    Floating Point Types They have both an integer part, to the left

    of the decimal point, and a fractionalpart, to the right.

    Floating-point variables represent what

    mathematicians call real numbers, which are

    used for measurable quantities such asdistance, area, and temperature. They

    typically have a fractional part.

    There are two kinds of floating-point

    variables in C++: float, double.

    float data type occupies 4 bytes (32bits)

    in memory while double occupies 8 bytes of

    memory.

  • 8/6/2019 Ch02 C++ Programming Basics

    43/62

    Float Example

    // circarea.cpp

    // demonstrates floating point variables

    #include //for cout, etc.

    using namespace std;

    intmain()

    {float rad; //variable of type float

    const float PI = 3.14159F; // type const float

    cout > rad; // get radius

    float area = PI * rad * rad; // find area

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    44/62

    Code Explanation The number 3.14159F is an example of a

    floating-point constant. The decimal point signals that it is a

    floating-point constant, and not an integer.

    The F specifies that its type float, rather

    than double or long double.

    The number is written in normal decimal

    notation.

    With type long double, use the letter L.

    You can also write floating-point constants

    using exponential notation e.g. 1234.56 wouldbe written 1.23456E3.

    The keyword const (for constant) specifies

    that the value of a variable will not change

    throughout the program.

  • 8/6/2019 Ch02 C++ Programming Basics

    45/62

    Quadratic Equation: Y = X2-6X-7

  • 8/6/2019 Ch02 C++ Programming Basics

    46/62

    Float Example: Quadratic Equation

    // A program to calculate Y = X2-6X-7

    #include //for cout, etc.

    using namespace std;

    intmain(){

    float X,Y; //variable of type float

    cout X; // get value of x

    Y = (X*X)-(6*X)-7; // find y

    // display answer

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    47/62

    Calculating Roots ofQuadratic Equation// Calculating Roots

    #include #include

    #include

    using namespace std;

    intmain(){

    double a,b,c,x1,x2; // variable of type float

    cout b >> c; // get first a then b & c

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    48/62

    Assignment #1

    1. What is the correct variable type for storing the

    following data: The number of pages in your text book

    The cost of this book

    The age of a person

    The number of people in the world

    2. Write a program that calculates and prints sum,difference and product of two numbers. Also, usethis program to calculate remainder and quotient indivision of these numbers. Display the output onthe screen.

    3. Write a program that gets 6 integers from the userand displays the sum, average and product ofthese numbers on screen.

  • 8/6/2019 Ch02 C++ Programming Basics

    49/62

    The setw() Manipulator#include

    #include using namespace std;

    intmain(){

    longpop1=2425785, pop2=47, pop3=9761;

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    50/62

    The setw() Manipulator#include

    #include // for setw#include

    using namespace std;

    intmain(){

    longpop1=2425785, pop2=47, pop3=9761;

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    51/62

    The setw() Manipulator The setw manipulator causes the number (or string)

    that follows it in the stream to be printed withina field n characters wide, where n is the argument

    to setw(n).

    The value is right justified within the field.

  • 8/6/2019 Ch02 C++ Programming Basics

    52/62

    The Data Types Range#include

    #include using namespace std;

    intmain(){

    signed char ch = 127;

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    53/62

    The Data Types Range// signtest.cpp tests signed and unsigned integers

    #include using namespace std;

    intmain(){

    int signedVar = 1500000000; //signed

    unsigned int unsignVar = 1500000000; //unsigned

    signedVar = (signedVar * 2)/3; //calculation exceeds range

    unsignVar = (unsignVar * 2)/3; //calculation within range

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    54/62

    Type Conversion// shows mixed expressions

    #include using namespace std;

    intmain(){

    int count = 7;

    float avgWeight = 155.5F;

    double totalWeight = count * avgWeight;

    /* the lower-type variable is converted to the type of the

    higher-type variable. Thus the int value of count is

    converted to type float and stored in a temporaryvariable before being multiplied by the float variableavgWeight. The result (still of type float) is thenconverted to double so that it can be assigned to the

    double variable totalWeight *********/cout

  • 8/6/2019 Ch02 C++ Programming Basics

    55/62

    Type Conversion

  • 8/6/2019 Ch02 C++ Programming Basics

    56/62

    Type Cast In C++ the term applies to data conversions

    specified by the programmer, as opposed to theautomatic data conversions.

    Sometimes a programmer needs to convert a value

    from one type to another in a situation where thecompiler will not do it automatically or without

    complaining.

    Heres a statement that uses a C++ cast to change a

    variable of type int into a variable of type char:

    aCharVar = static_cast(anIntVar);

    Here the variable to be cast (anIntVar) is placed

    in parentheses and the type its to be changed to(char) is placed in angle brackets.

  • 8/6/2019 Ch02 C++ Programming Basics

    57/62

    Type Conversion// cast.cpp

    // tests signed and unsigned integers#include

    using namespace std;

    intmain()

    {

    int intVar = 1500000000; //1,500,000,000

    intVar = (intVar * 10) / 10; //result too largecout

  • 8/6/2019 Ch02 C++ Programming Basics

    58/62

    The Remainder Operator (%)// remaind.cpp demonstrates remainder operator

    #include using namespace std;

    intmain(){

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    59/62

    Arithmetic Assignment Operators, += , -= , *= , /= , %=

    // demonstrates arithmetic assignment operators

    #include using namespace std;

    intmain(){

    int ans = 27;

    ans += 10; //same as: ans = ans + 10;

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    60/62

    Increment Operators, ++ , --

    // increm.cpp demonstrates the increment operator

    #include

    using namespace std;

    intmain(){

    int count = 10;

    cout

  • 8/6/2019 Ch02 C++ Programming Basics

    61/62

    Linker and Compiler

  • 8/6/2019 Ch02 C++ Programming Basics

    62/62

    Assignment #2

    Answer all questions from Q1 to Q25 andExercise 1 to 12 of Chapter2.