C++ Assignment NO.1

Embed Size (px)

Citation preview

  • 7/31/2019 C++ Assignment NO.1

    1/21

    C++ ASSIGNMENT NO: 1

    Preprocessor directives are lines included in the code of our programs that are not

    program statements but directives for the preprocessor. These lines are always preceded by

    a hash sign (#). The preprocessor is executed before the actual compilation of code begins,therefore the preprocessor digests all these directives before any code is generated by the

    statements. No semicolon (;) is expected at the end of a preprocessor directive.

    e.g.#include, #include, #defineetc.

    The main function is the point by where all C++ programs start their execution,

    independently of its location within the source code. It does not matter whether there areother functions with other namesdefined before or after it - the instructions containedwithin this function's definition will always be the first ones to be executed in any C++program. For that same reason, it is essential that all C++ programs have a mainfunction.

    e.g. int main (), void main ()etc.

    The statements in the main function are enclosed with in the parenthesis { }. All thestatements inside these parentheses are executed first then the other user defined functions

    statements.

    A statement is a simple or compound expression that can actually produce some effect. In

    fact, this statement performs the only action that generates a visible effect in our first

    program. An output stream is used coutis declared in the iostream standard file, so that'swhy we needed to include that specific file and to declare that we were going to use this

    specific output stream earlier in our code. All the statement ends with a semicolon character(;). This character is used to mark the end of the statement and in fact it must be included at

    the end of all expression statements in all C++ programs (one of the most common syntax

    errors is indeed to forget to include some semicolon after a statement).

    A variable is a meaningful name of data storage location in computer memory. When

    using a variable you refer to memory address of computer.There are two types of global variables:

  • 7/31/2019 C++ Assignment NO.1

    2/21

    Local variables Global variables

    The scope of local variables is limited to the block enclosed in braces ({ }) where theyare declared. For example, if they are declared at the beginning of the body of a function (like

    in function main) their scope is between its declaration point and the end of that function. Inthe example above, this means that if another function existed in addition to main, the local

    variables declared in maincould not be accessed from the other function and vice versa.

    Global variable is a variable declared in the main body of the source code, outside all

    functions. Global variables can be referred from anywhere in the code, even inside functions,

    whenever it is after its declaration.

    The name of variable can be called identifier or variable name in a friendly way. It has to

    follow these rules:

    The name can contain letters, digits and the underscore but the first letter has to be aletter or the underscore. Be avoided underscore as the first letter because it can be

    clashed with standard system variables.

    The length of name can be up to 247 characters but 31 characters are usuallyadequate. Keywords cannot be used as a variable name.

    Of course, the variable name should be meaningful to the programming context.

    To declare a variable you specify its name and kind of data type it can store. The variable

    declaration always ends with a semicolon, for example:

    int a; char ch;

    You can declare variables at any point of your program before using it. You should declare

    your variables closest to their first point of use so the source code is easier to maintain. In

    C++ programming language, declaring a variable is also defining a variable.

    You can also initialize a variable when you declare it, for example:

    int a=10;

  • 7/31/2019 C++ Assignment NO.1

    3/21

    char ch= a;

    When we store data in a C++ program, such as a whole number or a character, we

    have to tell the compiler which type of data we want to store. The data type will havecharacteristics such as the range of values that can be stored and the operations that can beperformed on variables of that type.

    There are five basic data types in C++:

    Integer (int) {16 bits(2 bytes) -32768 to 32767} short int {16 bits(2 bytes) -32768 to 32767} long int {32 bits(4 bytes) -2147483648 to 2147483647} unsigned int {16 bits(2 bytes) 0 to 65535}

    Floating point (float) {32bits(4 bytes) 3.4x10-38 to 3.4x10+38} long float {64 bits(8 bytes) 1.7x10-308 to 1.7x10+308}

    Double precision (double) {64 bits(8 bytes) 1.7x10-308 to 1.7x10+308} long double {80 bits(10 bytes) 3.4x10-4932 to 3.4x10+4932}

    Character (char) {8 bits(1 byte) capacity from 1-65535 bytes}

    #include

    void main()

    {

    int AB, YZ;

    float D;

    char LMN[15];

    double sum;}

    A quantity that cannot change its value during execution is known as constant. Theyare used to express particular values within the source code of a program. We use these to

  • 7/31/2019 C++ Assignment NO.1

    4/21

    give concrete values to variables or to express messages we wanted our programs to printout.

    Constants have four types in C++:

    i)

    Integer constantsii) Floating point constantsiii) Character constantsiv) String constants

    are constant data elements that have no fractional parts or exponents. They

    always begin with a digit. You can specify integer constants in decimal, octal, or hexadecimal

    form. They can specify signed or unsigned types and long or short types.

    constants specify values that must have a fractional part. These values contain

    decimal points ( ) and can contain exponents. Floating-point constants have a "mantissa,"

    which specifies the value of the number, an "exponent," which specifies the magnitude of the

    number, and an optional suffix that specifies the constant's type. The mantissa is specified as

    a sequence of digits followed by a period, followed by an optional sequence of digits

    representing the fractional part of the number.

    are one or more members of the "source character set," the character set

    in which a program is written, surrounded by single quotation marks ('). They are used to

    represent characters in the "execution character set," the character set on the machine where

    the program executes.

    consists of zero or more characters from the source character set surrounded by

    double quotation marks ( ). A string literal represents a sequence of characters that, taken

    together, form a null-terminated string.

    String literals may contain any graphic character from the source character set except the

    double quotation mark ("), backslash ( ), or newline character. They may contain the sameescape sequences described in C++ Character Constants.

    C++ strings have these types:

    Array of [n], where nis the length of the string (in characters) plus 1 for theterminating \0 that marks the end of the string.

    Array of , for wide-character strings.

    #includ //include and iostream

    Main()

    [ //Parenthesis is wrong

    int r;

    http://msdn.microsoft.com/en-us/library/6aw8xdf2(v=vs.80).aspxhttp://msdn.microsoft.com/en-us/library/6aw8xdf2(v=vs.80).aspx
  • 7/31/2019 C++ Assignment NO.1

    5/21

    const float a=5.6; //a is declared but not used

    r=2;

    abc=2*p*r; //p is used but not declared

    cout>>"Result is ="

  • 7/31/2019 C++ Assignment NO.1

    6/21

    Character combinations consisting of a backslash ( ) followed by a letter or by acombination of digits are called "escape sequences." To represent a newline character, single

    quotation mark, or certain other characters in a character constant, you must use escapesequences. An escape sequence is regarded as a single character and is therefore valid as a

    character constant.

    Escape sequences are typically used to specify actions such as carriage returns and

    tab movements on terminals and printers. They are also used to provide literalrepresentations of nonprinting characters and characters that usually have special meanings,

    such as the double quotation mark ( ). e.g. \n, \t, \a, \b etc.

    #include

    #include

    void main()

    {

    clrscr();cout

  • 7/31/2019 C++ Assignment NO.1

    7/21

    Manipulators are functions specifically designed to be used in conjunction with theinsertion () operators on stream objects. They are still regular

    functions and can also be called as any other function using a stream object as argument.Manipulators are used to change formatting parameters on streams and to insert or extract

    certain special characters.

    Program for this output:

    1 2 3 4 5 1 2 3 4 5 6 7 8 9 0 1

    C I T Y U N I V E R S I T Y

    #include#include

    #include

    void main()

    {

    clrscr();

    cout

  • 7/31/2019 C++ Assignment NO.1

    8/21

    Cin is an object of class istream that represents the standard input stream. By

    default, most systems get their standard input from the keyboard; therefore cin is generally

    expected to get information from the user, although there are many cases where this can be

    redirected to some other source.

    Because cin is an object of class istream, we can retrieve characters from cin either as

    formatted data using the extraction operator (>>) or as unformatted data using

    the read member function, among others.

    #include

    #include

    void main()

    {clrscr();

    int a, b, c, sum, pro;

    couta;

    coutb;

    coutc;

    sum=a+b+c;

    pro=a*b*c;

    cout

  • 7/31/2019 C++ Assignment NO.1

    9/21

    is used to increase the value of variable by one. It works withsingle operator. This can only increase the value of variables. It cannot increase the value

    of constants and expressions. x++ and y++ are valid statements but 5++ is an invalid

    statements.

    The functionality of the following statements is same. All these statements are equivalent.These statements increase the value of x by 1.

    x++;x=x+1;

    x+=1;

    In the prefix form of increment operator, the increment operator is written before the

    variable.

    ++x;Let . In this situation the meaning of this statement is this, that it increases the value

    of by and after that it assigns that value to a.

    In the postfix form of increment operator, the increment operator is written after thevariable.

    x++;Let In this situation the meaning of this statement is this, that it assigns the value

    of to and after that increases the value of .

    is used to decrease the value of variable by one. It works with

    single operator. This can only decrease the value of variables. It cannot decrease the valueof constants and expressions. a-- and b-- are valid statements but 10-- is an invalidstatements.

    The functionality of the following statements is same. All these statements are equivalent.

    These statements decrease the value of x by 1.

    x--;x=x-1;

    x-=1;

    In the prefix form of decrement operator, the decrement operator is written before the

    variable.--x;Let . In this situation the meaning of this statement is this, that it decreases the value

    of by and after that it assigns that value to a.

  • 7/31/2019 C++ Assignment NO.1

    10/21

    In the postfix form of decrement operator, the decrement operator is written after the

    variable.

    x--;

    Let In this situation the meaning of this statement is this, that it assigns the valueof to and after that decreases the value of .

    #include

    #include

    void main()

    {

    clrscr();

    int a, b; //decleration of a & b as integer type variables

    a=7; //Assigning 7 to a

    b=5; //Assigning 5 to b

    cout

  • 7/31/2019 C++ Assignment NO.1

    11/21

    There is often need to compare two values in program. Such as whether the value in

    one a variable is greater than the value in the other variable. Depending upon the situation

    we can perform different operation for different cases.

    Relational Operators (also known as Comparison Operators) are used to compare two

    values. The result of comparison is a Boolean value.

    The Boolean value can either be true or false. In c and c++, 1 represents true and 0 represent

    false. However in c++ the data type bool has been introduced, which holds only two values

    either true or false. The value true in bool corresponds to 1 and 0 corresponds to false.

    #include

    #include

    #include

    void main (){

    clrscr();

    cout

  • 7/31/2019 C++ Assignment NO.1

    12/21

    The ability to control the flow of your program, letting it makes decisions on what

    code to execute. The statement allows you to control a program enters a section of code

    or not based on whether a given condition is true or false. One of the important functions of

    the statement is that it allows the program to select an action based upon the user's input.For example, by using an statement to check a user entered password, your program can

    decide whether a user is allowed access to the program.

    Without a conditional statement such as the statement, programs would run almost

    the exact same way every time. statements allow the flow of the program to be changed,and so they allow algorithms and more interesting code.

    #include

    main()

    {

    int a,b;

    a=100;

    b=50;if(a>b)

    cout

  • 7/31/2019 C++ Assignment NO.1

    13/21

    The else statement is a type of control structure. A control structure is a instruction,statement or group of statements which determines the sequence of execution of otherstatements. The basic operation of if else statement is that a statement or group of

    statements is executed under , if the value of expression is true and if the expression is false,

    statements under are evaluated. Statement associated either with or are executednot both group of statements are executed. The clause is optional.

    #include

    #include

    void main()

    {

    clrscr();

    int a, b , i;

    char ch; i=1;

    do{

    couta;

    coutb;

    if(a>b)

    cout

  • 7/31/2019 C++ Assignment NO.1

    14/21

    #include

    #include

    void main()

    {clrscr();

    int num1, num2;

    coutnum1;

    if(num1%2==0)

    cout

  • 7/31/2019 C++ Assignment NO.1

    15/21

    If statement inside the body of another if statement is called the nested if statement.

    The first if statement is called the outer if statement and the second if statement inside the

    outer if statement is called as inner if statement.

    First the outer if condition is checked and if it is correct then the control goes in the inner if

    condition and if this is correct too then the inner statement respective output is generated.

    if(condition){

    if(condition){

    statements to execute}

    statements to execute

    }

    #include

    #include

    void main()

    {

    clrscr();

    int a, b, c;

    couta;

    coutb;

    coutc;

    if(a>b)

    if(a>c)

    cout

  • 7/31/2019 C++ Assignment NO.1

    16/21

    else

    if(b>c)

    cout

  • 7/31/2019 C++ Assignment NO.1

    17/21

    cin>>c;

    if(a>b && a>c)

    coutc)

    coutb)

    cout

  • 7/31/2019 C++ Assignment NO.1

    18/21

    Loop means that the set of statements are executed repeatedly until and unless the

    condition is true. The execution will continue until the condition goes false.

    There are three types of loop:

    While loop Do-while loop

    For loop

    It is a conditional loop, it is used to execute a set of statements which are in theparenthesis of the while condition. It will execute the statements to a given condition comes

    false.

    int i=5;

    While(a>0)

    {

    Statement

    StatementStatement

    Statement

    i++;

    }

    For example:In the above syntax is initialized and assigned a value of . The given condition is that

    the value entered in is greater than , so the loop will continue executing the followingstatements until the value of become the loop will terminate and execute the statements

    outside the loop.

    This is also a conditional loop, it is just like while loop but first the statements are

    executed then the condition is tested either true or false. If true it will again execute the

    statements under the but if it is false it will terminate and execute the outer statements.

    do

    {

    Statement(s)

    }

    while(condition);

    The condition in the while will be ended with a statement terminator otherwise it willnot execute the statements and give error. In this loop at least on time the statements are

    executed.

  • 7/31/2019 C++ Assignment NO.1

    19/21

    For loop is also conditional loop, in this loop the statements are executed at a given

    condition. It is just like while loop but syntax is change. This loop is also known as counter

    loop.

    for(initialization ; condition ; increment or decrement)

    {

    Statement(s)

    }

    The variable is initialized then condition and then increment or decrement according

    to the need. If a variable is declared before the loop there is no need of initialization again inthe loop. The loop will start from the initializes value and continue executing the statements

    inside the loop until the given condition goes false.

    #include#include

    void main()

    {

    int a=1;

    while(a

  • 7/31/2019 C++ Assignment NO.1

    20/21

    #include

    #include

    void main()

    {

    clrscr();int num, res;

    coutnum;

    do

    {

    res=num%8;

    cout

  • 7/31/2019 C++ Assignment NO.1

    21/21

    cout