SlideShare une entreprise Scribd logo
1  sur  77
Session – I
  Module-1 & Module-2
Prepared by - Neetu Gupta
   ngupta5@amity.edu
neetugupta78@gmail.com
Contents
•   Various programming techniques
•   Procedural approach to OOPs
•   Introduction to OOPS
•   C++ program structure – sample program
•   Input / Output in C++ - cin and cout
•   Variables and data types
•   Operators in C++
•   Control structure in C++ – looping, selection, jump statements
Programming curve
• We can distinguish learning curve of
  programming as :
  – Unstructured programming,
  – procedural programming,
  – modular programming and
  – object-oriented programming.
• Unstructured Programming
  Usually, people start learning programming by writing small and
  simple programs consisting only of one main program. Here ``main
  program'' stands for a sequence of commands or statements which
  modify data which is global throughout the whole program.
                        main program
                            data

Here, the main program directly operates on global data.

Disadvantages :
   Once the program gets sufficiently large. For example, if the same
   statement sequence is needed at different locations within the
   program, the sequence must be copied. This has lead to the idea to
   extract these sequences, name them and offering a technique to
   call and return from these procedures.
• Procedural Programming
With procedural programming you are able to combine returning sequences
   of statements into one single place.

A procedure call is used to invoke the procedure. After the sequence is
   processed, flow of control proceeds right after the position where the call
   was made.

A program can be viewed as a sequence of procedure calls.
Main program is responsible to pass data to the individual
calls, the data is processed by the procedures and, once the program has
    finished, the resulting data is presented.

The flow of data can be illustrated as a hierarchical graph, a tree, as shown in
   below for a program with no sub procedures:
                                  main program
                                      data


                    procedure1        procedure2           procedure3
Modular Programming
• In modular programming procedures of a common
  functionality are grouped together into separate modules.




• Each module can have its own data. This allows each
  module to manage an internal state which is modified by
  calls to procedures of this module. However, there is only
  one state per module and each module exists at most once
  in the whole program.
Object Oriented programming
• Object-oriented programming solves some of
  the problems just mentioned. In contrast to
  the other techniques, here we have a web of
  interacting objects, each house-keeping its
  own state




        Objects of the program interact by sending messages to each other.
OOPS v/s Procedural
OOPS characteristics
• The various characteristics of the Object
  Oriented Methodology

     •   Identity,
     •   Classification,
     •   Inheritance and
     •   Polymorphism
     •   Abstraction
     •   Encapsulation
•   Identity:
     – The term Object Oriented means that we organize the software as a collection
        of discrete objects.
     – An object is a software package that contains the related data and the
        methods. Although objects can be used for any purpose, they are most
        frequently used to represent real-world objects such as products, customers
        and sales orders.
     – The basic idea is to define software objects that can interact with each other
        just as their real world counterparts do, modeling the way a system works and
        providing a natural foundation for building systems to manage that business.

•   Classification
     – In principle, packaging data and procedures together makes perfect sense.
     – Suppose we have many objects of the same type- for example a thousand product
         objects, each of which could report its current price. Data values would differ from one
         product to the next.
     – But the methods for dealing with these data might well be the same. Do we have to
         copy these methods and duplicate them in every object? No, this would be ridiculously
         inefficient.
     – All object-oriented languages provide a simple way of capturing these commonalties in
         a single place. That place is called a class. The class acts as a kind of template for objects
         of similar nature.
• Polymorphism
   – Polymorphism is a Greek word meaning many forms.
   – It is used to express the fact that the same message can be sent to
     many different objects and interpreted in different ways by each
     object.
   – For example, we could send the message "move" to many different
     kinds of objects. They would all respond to the same message, but
     they might do so in very different ways. The move operation will
     behave differently for a window and differently for a chess piece.

• Inheritance
   – It is the sharing of attributes and operations among classes on a
     hierarchical relationship.
   – A class can be defined as a generalized form and then it specialized in
     a subclass.
   – Each subclass inherits all the properties of its superclass and adds its
     own properties in it.
   – For example, a car and a bicycle are subclasses of a class road vehicle,
     as they both inherits all the qualities of a road vehicle and add their
     own properties to it.
• Abstraction
  – In object oriented programming , classes uses the concept
    of Abstraction fro storing data.
  – A class encapsulates the relevant data and functions that
    operate on data by hiding the complex implementation
    details from the user .
  – In other words ,user needs to focus on what a class does
    rather than how it does it.
Start c++ - A sample program
• A typical hello world C++ program will be like

// my first program in C++
#include <iostream>
using namespace std;
int main () {
    cout << "Hello World!";
    return 0;
}

Output is :
      Hello World!
Sample program explained
// my first program in C++ - Line 1
   This is a comment line. All lines beginning with two slash signs (//) are
   considered comments

#include <iostream> - Line 2
• They are not regular code lines with expressions but indications for the
    compiler's preprocessor. Here the directive tells the preprocessor to
    include the iostream standard file required for input/out library in C++.
using namespace std; - Line 3
• All the elements of the standard C++ library are declared within a
    namespace with name std.
int main () – Line 4
• This line corresponds to the beginning of the definition of the main
    function. The main function is the point by where all C++ programs start
    their execution. The body of the main function enclosed in braces ({})
cout << "Hello World!"; - Line 4
• It is a C++ statement.
• cout is the name of the standard output stream in C++, and the meaning
   of the entire statement is to insert a sequence of characters (in this case
   the Hello World sequence of characters) into the standard output stream
   i.e cout, which usually corresponds to the screen.
• cout is declared in the iostream standard file within the std namespace, so
   that's why we needed to include that specific file and to declare that we
   were going to use this specific namespace earlier in our code.

return 0; - Line 5
• The return statement causes the main function to finish.
• return may be followed by a return code like zero here.
• A return code of 0 for the main function is generally interpreted as the
   program worked as expected without any errors during its execution. This
   is the most usual way to end a C++ console program.
Comments
• Comments are parts of the source code
  disregarded by the compiler. They simply do
  nothing.
• Their purpose is only to allow the programmer to
  insert notes or descriptions embedded within the
  source code.
C++ supports two ways to insert comments:
• // line comment
• /* block comment */
• line comment, discards everything from
  where the pair of slash signs (//) is found up to
  the end of that same line.
            cout << "Hello World! "; // prints Hello World!
• block comment, discards everything between
  the /* characters and the first appearance of
  the */ characters, with the possibility of
  including more than one line.

          /* following line print the text
          Hello world! On screen*/
          cout << "Hello World! ";
#include <iostream>
using namespace std;
int main () {
   cout << "Hello World! ";
   // prints Hello World!
    cout << "I'm a C++ program";
   // prints I'm a C++ program
   return 0;
}
Output is
  Hello World! I'm a C++ program

• Here nothing between /* */ or // till end of line is
  considered by compiler
Data Types
• In programming, we store the variables in our
  computer's memory, but the computer has to
  know what kind of data we want to store in
  them, since it is not going to occupy the same
  amount of memory to store a simple number
  than to store a single letter or a large number,
  and they are not going to be interpreted the
  same way.
• Depending upon the type of data it can store and
  the memory requirement, the data types are
  classified in C++ as:
Summary of C ++Data Types
Name          Description                  Size*    Range*
              Character or small                    signed: -128 to 127
char                                       1byte
              integer.                              unsigned: 0 to 255

short int                                           signed: -32768 to 32767
              Short Integer.               2bytes
(short)                                             unsigned: 0 to 65535

                                                    signed: -2147483648 to
                                                    2147483647
int           Integer.                     4bytes
                                                    unsigned: 0 to
                                                    4294967295
                                                    signed: -2147483648 to
long int                                            2147483647
              Long integer.                4bytes
(long)                                              unsigned: 0 to
                                                    4294967295
              Boolean value. It can take
bool          one of two values: true or   1byte    true or false
              false.
float         Floating point number.       4bytes   +/- 3.4e +/- 38 (~7 digits)
              Double precision floating             +/- 1.7e +/- 308 (~15
double                                     8bytes
              point number.                         digits)
              Long double precision                 +/- 1.7e +/- 308 (~15
long double                                8bytes
              floating point number.                digits)
Variables
• We can define a variable as a portion of memory to store a value
• Each variable needs an identifier (name) that distinguishes it from
  the others.
• A valid identifier is a sequence of one or more letters, digits or
  underscore characters (_). Neither spaces nor punctuation marks or
  symbols can be part of an identifier. Only letters, digits and single
  underscore characters are valid.
• A Variable identifiers always have to begin with a letter or
  underscore (_)
• The C++ language is a "case sensitive" language. It means that an
  identifier in capital letters is not equivalent to one with the same
  name but in small letters.
  Like RESULT variable is not the same as the result variable or the
  Result variable. These are three different variable identifiers.
Declaration of variables

• We must first declare a variable specifying which data type
  we want it to be.
• The syntax to declare a new variable is
                       datatype variable-name;
• Example could be
                       int a;
                       float mynumber;


Here,
The first one declares a variable of type int with the identifier a.
The second one declares a variable of type float with the
  identifier mynumber.
• We can declare more than one variable of the same
  type, in a single statement by separating their
  identifiers with commas. For example:
                     int a, b, c;
• The integer data types char, short, long and int can
  be either signed or unsigned based on the range of
  numbers needed
   – Signed types can represent both +ve and –ve values,
   – unsigned types can only represent +ve values (and zero)
              unsigned short int num; // only +ve values
              signed int balance; // +ve & -ve values
// PROGRAM - operating with variables
#include <iostream>
using namespace std;
int main () {
   // declaring variables:
   int a, b, result;
   // process:
   a = 5;
   b = 2;
   a = a + 1;
   result = a - b;
   // print out the result:
   cout << “Result: ” << result;
   // terminate the program:
   return 0;
}
Output is: Result: 4
Constants
• Constants are expressions with a fixed value.
• Constants are values which remain same
  through out the execution of a program.
• In c++ there are various ways to use
  constants, as:
  – Literals
  – Defined constants (# define)
  – Declared constants ( const)
Literal Constants
• They are used to express particular values within the
  source code of a program.
• For example,
               a = 5;
  Here, 5 in this piece of code was a literal constant.
• Literal constants can be divided in
     •       Integer Numerals,
     •       Floating-Point Numerals,
     •       Characters,
     •       Strings and
     •       Boolean Values.
Defined constants ( # define)
• You can define your own names for constants that you
  use very often without having to resort to memory-
  consuming variables
• It can be done by using the #define preprocessor
  directive. Its format is:
              #define identifier value
• For example:
              #define PI 3.14159
              #define NEWLINE 'n'
  This defines two new constants: PI and NEWLINE. Once
  they are defined, you can use them in the rest of the
  code as if they were any other regular constant
// PROGRAM - defined constants: calculate circumference
#include <iostream>
using namespace std;
#define PI 3.14159
#define NEWLINE 'n'
int main () {
     double r=5.0; // radius
     double circle;
     circle = 2 * PI * r;
     cout << circle;
     cout << NEWLINE;
     return 0;
}
Output is: 31.4159

•   Only thing that the compiler preprocessor does when it encounters
    #define directives is to literally replace any occurrence of their identifier
    (in the previous example, these were PI and NEWLINE) by the code to
    which they have been defined (3.14159 and 'n' respectively).
Declared constants (const)

• With the const prefix you can declare constants
  with a specific type in the same way as you would
  do with a variable
            const int pathwidth = 100;
            const char tabulator = 't';
• Here, pathwidth and tabulator are two typed
  constants. They are treated just like regular
  variables except that their values cannot be
  modified after their definition. If modified it will
  be a compilation error like
      pathwidth= 200; // Compilation error
Basic Input/Output
• C++ uses a convenient abstraction called
  streams to perform input and output
  operations in sequential media such as the
  screen or the keyboard.
• A stream is an object where a program can
  either insert or extract characters to/from it.
• The standard C++ library includes the header
  file iostream, where the standard input and
  output stream objects are declared.
Standard Output Stream- cout
• By default, the standard output of a program
  is the screen, and the C++ stream object
  defined to access it is cout.
• cout is used in conjunction with the insertion
  operator, which is written as <<
• A brief example can be
       cout << "Output sentence"; // prints Output sentence on screen
       cout << 120; // prints number 120 on screen
       cout << x; // prints the content of x on screen
• The insertion operator (<<) may be used more than once
  in a single statement. The below statement would print
  the message Hello, I am a C++ statement on the screen.
      cout << "Hello, " << "I am " << "a C++ statement";


• The utility of repeating the insertion operator (<<) is
  demonstrated when we want to print out a combination
  of variables and constants or more than one variable.
  Here, age and zipcode are variables. :
      cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;


Output is:
        Hello, I am 50 years old and my zipcode is 90065
If age = 50 and zipcode = 90065
• Notice that cout does not add a line break after its output
  unless we explicitly indicate it, therefore, the following
  statements:
               cout << "This is a sentence.";
               cout << “ This is another sentence.";
Output is :
  This is a sentence. This is another sentence.

• In order to perform a line break on the output we must
  explicitly insert a new-line character n
               cout << "First sentence.n";
               cout << "Second sentence.nThird sentence.";
Output is:
  First sentence.
  Second sentence.
  Third sentence.
Standard Input stream- cin
• cin can only process the input from the
  keyboard once the RETURN key has been
  pressed.
• Therefore, even if you request a single
  character, the extraction from cin will not
  process the input until the user presses
  RETURN
• You must always consider the type of the
  variable that you have mentioned with cin. If
  you request an integer you will get an integer,
  if you request a character you will get a
  character etc.
// PROGRAM - i/o
#include <iostream>
using namespace std;
int main () {
      int i;
      cout << "Please enter an integer value: ";
      cin >> i;
      cout << "The value you entered is " << i;
      cout << " and its double is " << i*2 << ".n";
      return 0;
}
Output is :
      Please enter an integer value: 702
      The value you entered is 702 and its double is 1404.
• You can also use cin to request more than one
  datum input from the user:
            cin >> a >> b;

is equivalent to:
            cin >> a;
            cin >> b;

• In both above cases the user must give two data,
  one for variable a and another one for variable b
  that may be separated by any valid blank
  separator: a space, a tab character or a newline.
Operators in C++
• Once we know of the existence of variables
  and constants, we can begin to operate with
  them to make complex programs to solve
  problems.
• For that purpose, C++ provides a various
  range of operators.
• C++ provide various operators which operate
  on different type of data type variables and
  constants.
Assignment Operator
• Assignment (=) operator
The assignment operator assigns a value to a variable.
   a = 5;
• This statement assigns the integer value 5 to the variable a.
• The part at the left of the assignment operator (=) is known
  as the lvalue (left value) and the right one as the rvalue
  (right value).
• The lvalue has to be a variable whereas the rvalue can be
  either a constant, a variable, the result of an operation or
  any combination of these.
Assignment operator - Example
#include <iostream>
using namespace std;
int main () {
    int a, b;
    a = 10;
    b = 4;
    b:4 a =
    b = 7;
    cout << "a:“ << a;
    cout << " b:“ << b;
    return 0;
}
output is:
        a:4 b:7
Arithmetic operators

• The basic five arithmetical operations supported by the
  C++ language are:
      +   : represents mathematical addition
      -   : represents mathematical subtraction
      *   : represents mathematical multiplication
      /   : represents mathematical division
      % : represents modulo (Gives remainder of
                               division of two values)
             a = 11 % 3;

  here, variable a will contain the value 2, since 2 is the
  remainder from dividing 11 between 3.
Relational operators
• In order to evaluate a comparison between two
  expressions we can use the relational operators.
  The result of a relational operation is a Boolean
  value that can only be true or false
           == Equal to
           != Not equal to
           > Greater than
           < Less than
           >= Greater than or equal to
           <= Less than or equal to
Relational operators - Example
Suppose that a=2, b=3 and c=6,
(a == 5) // evaluates to false since a is not equal to 5.
(a*b >= c) // evaluates to true since (2*3 >= 6) is true.
(b+4 > a*c) // evaluates to false since (3+4 > 2*6)
((b=2) == a) // evaluates to true.
(a != b) // evaluates to true
Logical operators
Three logical operators : !, &&, ||
• ! : NOT
C++ operator to perform the Boolean operation NOT, it has only one
   operand, located at its right, and the only thing that it does is to
   inverse the value of it, producing false if its operand is true and true
   if its operand is false.

Example:
!(5 == 5) // false because the expression at its right (5 == 5) is true.
!(6 <= 4)        // true because (6 <= 4) would be false.
!true            // evaluates to false
!false           // evaluates to true.
Logical operators
• &&: AND
The operator && corresponds with Boolean logical operation AND.
  This operation results true if both its two operands are true, and
  false otherwise. The following panel shows the result of operator
  && evaluating the expression a && b:

 a                   b                  A && b
 true                true               true
 true                false              false
 false               true               false
 false               false              false


( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
Logical operators
• || operator - OR
The operator || corresponds with Boolean logical operation OR.
This operation results true if either one of its two operands is true,
   thus being false only when both operands are false themselves.
   Here are the possible results

  a                   b                    a||b
  true                true                 true
  true                false                false
  false               true                 false
  false               false                false

( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
Conditional operator
• The conditional operator evaluates an expression returning a value
  if that expression is true and a different one if the expression is
  evaluated as false. Its format is:

                   condition ? result1 : result2

• If condition is true the expression will return result1, if it is not
  it will return result2.

        7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
        7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
        5>3 ? a : b // returns the value of a, since 5 is greater than 3.
        a>b ? a : b // returns whichever is greater, a or b.
// conditional operator
#include <iostream>
using namespace std;
int main () {
     int a,b,c;
     a=2;
     b=7;
     c = (a>b) ? a : b;
     cout << “C:” << c;
     return 0;
}

Output is:
          c: 7
• In this example a was 2 and b was 7, so the expression being evaluated (a>b) was
   not true, thus the first value specified after the question mark was discarded in
   favor of the second value (the one after the colon) which was b, with a value of 7.
Comma operator ( , )

• The comma operator (,) is used to separate two or more
  expressions that are included where only one expression is
  expected.
• When the set of expressions has to be evaluated for a
  value, only the rightmost expression is considered.
  For example, the following code:
      a = (b=3, b+2);

  It would first assign the value 3 to b, and then assign b+2 to
  variable a. So, at the end, variable a would contain the
  value 5 while variable b would contain value 3.
Increment/Decrement operators
• The increment operator (++) increases by one the value stored in a
  variable.
• The following two statements are similar:
                c++;    // using increment operator
                c=c+1;
Both increases the value of c by 1;

• The decrement operator (--) decreases by one the value stored in a
  variable.
• The following two statements are similar:
               c--;    // using decrement operator
               c=c-1;
Both decreases the value of c by 1;
Increment/Decrement operators
• These operators can be used both as a prefix or as a suffix.
  i.e. can be written either before the variable (++a) or after
  it (a++).

If the operator is used as a prefix (++a) the value is increased
    before the result of the expression is evaluated and
    therefore the increased value is considered in the outer
    expression;

If it is used as a suffix (a++) the value stored in a is increased
    after being evaluated and therefore the value stored
    before the increase operation is evaluated in the outer
    expression.
Increment/Decrement operators
Notice the difference in below example :

    Example 1                       Example 2
    B=3;                            B=3;
    A=++B;                          A=B++;
    // A contains 4, B contains 4   // A contains 3, B contains 4



In Example 1, B is increased before its value is
  copied to A. While in Example 2, the value of B
  is copied to A and then B is increased.
sizeof() operator
• This operator accepts one parameter, which can
  be either a type or a variable itself and returns
  the size in bytes of that type or object:
      a = sizeof (char);
  This will assign the value 1 to a because char is a
  one-byte long type.

• The value returned by sizeof is a constant, so it is
  always determined before program execution.
Explicit type casting operator

• Type casting operators allow you to convert a
  data of a one type to another type.

• The simplest one, which has been inherited
  from the C language, is to precede the
  expression to be converted by the new type
  enclosed between parentheses (()):
Explicit type casting operator -
                   Example
Below code converts the float number 3.14 to an integer value (3), the
   remainder is lost.
            int i;
            float f = 3.14;
            i = (int) f;

Here the typecasting operator was (int).
• Another way to do the same thing in C++ is using the
  functional notation: preceding the expression to be
  converted by the type and enclosing the expression
  between parentheses:

    i = int ( f );
Precedence of operators

• When writing complex expressions with
  several operands, we may have some doubts
  about which operand is evaluated first and
  which later. For example, in this expression:
           a=5+7%2
we may doubt if it really means:
     a = 5 + (7 % 2) // with a result of 6, or
     a = (5 + 7) % 2 // with a result of 0
Precedence of operators

• There is an established order with the priority of
  each operator, and not only the arithmetic ones
  (those whose preference come from
  mathematics) but for all the operators which can
  appear in C++. From greatest to lowest priority,
  the priority order is as follows:

• Grouping defines the precedence order in which
  operators are evaluated in the case that there
  are several operators of the same level in an
  expression.
Precedence with associativity
Level   Operator                        Description          Grouping
1       ::                              scope                Left-to-right

        () [] . -> ++ -- dynamic_cast
2       static_cast reinterpret_cast    postfix              Left-to-right
        const_cast typeid


        ++ -- ~ ! sizeof new delete     unary (prefix)
                                        indirection and
3                                                           Right-to-left
        *&                              reference
                                        (pointers)
        +-                              unary sign operator
4       (type)                          type casting         Right-to-left
5       .* ->*                          pointer-to-member Left-to-right
6       */%                             multiplicative       Left-to-right
7       +-                              additive             Left-to-right
8       << >>                           shift                Left-to-right
Level   Operator           Description   Grouping
9       < > <= >=          relational    Left-to-right
10      == !=              equality      Left-to-right
11      &                  bitwise AND   Left-to-right
12      ^                  bitwise XOR   Left-to-right
13      |                  bitwise OR    Left-to-right
14      &&                 logical AND   Left-to-right
15      ||                 logical OR    Left-to-right
16      ?:                 conditional   Right-to-left
        = *= /= %= += -=
17                         assignment    Right-to-left
        >>= <<= &= ^= |=
18      ,                  comma         Left-to-right
Statements
• A C++ program is made up of various up of
  statements, where a Statement is a part of your
  program that can be executed.
• Every statement in your program alone or in
  combination specifies an action to performed by
  your program.
• Inheriting from c, c++ provides variety of
  statements to help you attain any function with
  maximum flexibility and efficiency.
• A program is formed by a sequence of one or
  more statements.
Kinds of Statements
• The following are the major generic kinds of statements
  with examples in typical imperative languages:

3. Simple statements
• A simple statement is a single line of code which is
   executed independently irrespective of other statements
   in a program.
• The various types of single statements could be:

   Assignment: A:= A + 1   // expression
   call: CLEARSCREEN()     // call to a function
   return: return 5;       // return from a function
   goto: goto 1            // jump to statement labeled 1
Kinds of Statements
1. Compound statements
• A compound statement consists of zero or more
   statements enclosed in curly braces ({ }).
• A compound statement can be used anywhere a
   statement is expected. Compound statements are
   commonly called "blocks.“
• The various types of compound statements could be :
        –   if-statement:
        –   switch-statement
        –   while-loop
        –   do-loop
        –   for-loop
Control Statements
• A program is usually not limited to a linear sequence of
  instructions. During its process it may bifurcate, repeat
  code or take decisions. For that purpose, C++ provides
  control structures that serve to specify what has to be done
  by our program, when and under which circumstances.

• With the introduction of control structures we are going to
  have to introduce a new concept: the compound-statement
  or block. A block is a group of statements which are
  separated by semicolons (;) like all C++ statements, but
  grouped together in a block enclosed in braces: { }:

  { statement1; statement2; statement3; }
If statement
• if keyword is used to execute a statement or
  block only if a condition is fulfilled. Its form is:

      if (condition) statement

• If this condition is true, statement is executed.
  If it is false, statement is ignored (not
  executed) and the program continues right
  after this conditional structure.
If statement - Example
• For example, the following code fragment prints x is 100
  only if the value stored in the x variable is indeed 100:
       if (x == 100)
               cout << "x is 100";
• If we want more than a single statement to be executed in
  case that the condition is true we can specify a block using
  braces { }:

       if (x == 100) {
               cout << "x is ";
               cout << x;
       }
If-else statement
• We can specify what we want to doif the
  condition is not fulfilled by using the keyword
  else.
• The else is used in conjunction with if is:
      if (condition)
       statement1
     else
       statement2
If-else statement – Example
                  http://www.cplusplus.com/doc/tutorial/control/




• Following code prints on the screen x is 100 if
  indeed x has a value of 100, but if it has not
  -and only if not- it prints out x is not 100.
      if (x == 100)
             cout << "x is 100";
      else
             cout << "x is not 100";
while loop statement
• Its purpose is to repeat statement(s) a certain number of
  times or while a condition is true. The format is:

       while (condition)
              statement;
or
       while (condition)
       {
              statement1;
              statement2;
              ……..
       }
while loop statement - Example
• // print the number from n to 1
#include <iostream>
using namespace std;
int main ()
{
    int n;
    cout << "Enter the starting number > ";
    cin >> n;
    while (n>0) {
           cout << n << ", ";
           --n;
    }
    return 0;
}
while loop statement - Example
In the above example while loop begins,
• if the value entered by the user fulfills the
   condition n>0 (that n is greater than zero) the
   block that follows the condition will be executed
   and repeated while the condition (n>0) remains
   being true i.e. till n=0;

Output will be as:
 Enter the starting number > 8
 8, 7, 6, 5, 4, 3, 2, 1
do-while loop
• Its functionality is exactly the same as the while loop, except that
  condition in the do-while loop is evaluated after the execution of
  statement instead of before, granting at least one execution of
  statement even if condition is never fulfilled. Its format is:

              do statement           while (condition);
or
                do
                {
                          statement ;
                          ………………..
                }
                while (condition);
do-while loop - Example
do-while loop - Example
• The above code is executed at least once.
• As you see above the condition while(n!=0) is
  checked at the end of loop. That means the loop
  executes once before checking the condition for
  the first time.
Output is
        Enter number (0 to end): 12345
        You entered: 12345
        Enter number (0 to end): 160277
        You entered: 160277
        Enter number (0 to end): 0
        You entered: 0
for loop
• Its format is:

      for (initialization; condition; increase)
      statement;

• Its function is to repeat statement while condition
  remains true, like the while loop. But in addition, the
  for loop provides specific locations to contain an
  initialization statement and an increase statement. So
  this loop is specially designed to perform a repetitive
  action with a counter which is initialized and increased
  on each iteration.
for loop - Working
for loop works in the following way:
• initialization is executed. Generally it is an initial
  value setting for a counter variable. This is
  executed only once.
• condition is checked. If it is true the loop
  continues, otherwise the loop ends and
  statement is not executed.
• statement is executed. It can be either a single
  statement or a block enclosed in braces { }.
• finally, increase field is executed and the loop
  gets back to step 2.
for loop - Example
• // countdown using a for loop
#include <iostream>
using namespace std;
int main () {
    for (int n=10; n>0; n--)
   {
        cout << n << ", ";
   }
   return 0;
}
for loop - Example
• Output is:
     10, 9, 8, 7, 6, 5, 4, 3, 2, 1

n initializes with a value of 10, the condition is n>0
   is checked.
The value of n is cout.
The value of n is decreased by 1. and condition is
   checked again.
The loop condition becomes false when n=0. In this
   case, the control jumps out of loop.

Contenu connexe

Tendances

Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programmingNeelesh Shukla
 
Unit 5-hive data types – primitive and complex data
Unit 5-hive data types – primitive and complex dataUnit 5-hive data types – primitive and complex data
Unit 5-hive data types – primitive and complex datavishal choudhary
 
C++ Object Oriented Programming
C++  Object Oriented ProgrammingC++  Object Oriented Programming
C++ Object Oriented ProgrammingGamindu Udayanga
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programmingnirajmandaliya
 
Model-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax DefinitionModel-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax DefinitionEelco Visser
 
Java platform
Java platformJava platform
Java platformVisithan
 
Chapter1pp
Chapter1ppChapter1pp
Chapter1ppJ. C.
 
Maths&programming forartists wip
Maths&programming forartists wipMaths&programming forartists wip
Maths&programming forartists wipkedar nath
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++M Hussnain Ali
 
Python for katana
Python for katanaPython for katana
Python for katanakedar nath
 
Mel for beginners
Mel for beginnersMel for beginners
Mel for beginnerskedar nath
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)indiangarg
 
Object Oriented Programming lecture 1
Object Oriented Programming lecture 1Object Oriented Programming lecture 1
Object Oriented Programming lecture 1Anwar Ul Haq
 
implementing oop_concept
 implementing oop_concept implementing oop_concept
implementing oop_conceptAmit Gupta
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsMukesh Tekwani
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.pptTareq Hasan
 

Tendances (20)

1 puc programming using c++
1 puc programming using c++1 puc programming using c++
1 puc programming using c++
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
Unit 5-hive data types – primitive and complex data
Unit 5-hive data types – primitive and complex dataUnit 5-hive data types – primitive and complex data
Unit 5-hive data types – primitive and complex data
 
C++ Object Oriented Programming
C++  Object Oriented ProgrammingC++  Object Oriented Programming
C++ Object Oriented Programming
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
Model-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax DefinitionModel-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax Definition
 
Java platform
Java platformJava platform
Java platform
 
Chapter1pp
Chapter1ppChapter1pp
Chapter1pp
 
Maths&programming forartists wip
Maths&programming forartists wipMaths&programming forartists wip
Maths&programming forartists wip
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Andy On Closures
Andy On ClosuresAndy On Closures
Andy On Closures
 
Python for katana
Python for katanaPython for katana
Python for katana
 
Mel for beginners
Mel for beginnersMel for beginners
Mel for beginners
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)
 
Object Oriented Programming lecture 1
Object Oriented Programming lecture 1Object Oriented Programming lecture 1
Object Oriented Programming lecture 1
 
implementing oop_concept
 implementing oop_concept implementing oop_concept
implementing oop_concept
 
pebble - Building apps on pebble
pebble - Building apps on pebblepebble - Building apps on pebble
pebble - Building apps on pebble
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs concepts
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
 

En vedette (7)

F6dc1 session6 c++
F6dc1 session6 c++F6dc1 session6 c++
F6dc1 session6 c++
 
Operating systems
Operating systemsOperating systems
Operating systems
 
VISUAL BASIC
VISUAL BASIC VISUAL BASIC
VISUAL BASIC
 
File management
File managementFile management
File management
 
106da session5 c++
106da session5 c++106da session5 c++
106da session5 c++
 
Computer fundamentals
Computer fundamentalsComputer fundamentals
Computer fundamentals
 
C96e1 session3 c++
C96e1 session3 c++C96e1 session3 c++
C96e1 session3 c++
 

Similaire à 73d32 session1 c++

Similaire à 73d32 session1 c++ (20)

Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
 
c#.pptx
c#.pptxc#.pptx
c#.pptx
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
 
C++ Basics
C++ BasicsC++ Basics
C++ Basics
 
Intro To C++ - Class 14 - Midterm Review
Intro To C++ - Class 14 - Midterm ReviewIntro To C++ - Class 14 - Midterm Review
Intro To C++ - Class 14 - Midterm Review
 
C question
C questionC question
C question
 
Unit 1 introduction to c++.pptx
Unit 1 introduction to c++.pptxUnit 1 introduction to c++.pptx
Unit 1 introduction to c++.pptx
 
Software Engineering
Software EngineeringSoftware Engineering
Software Engineering
 
Principal of objected oriented programming
Principal of objected oriented programming Principal of objected oriented programming
Principal of objected oriented programming
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Object oriented programming 7 first steps in oop using c++
Object oriented programming 7 first steps in oop using  c++Object oriented programming 7 first steps in oop using  c++
Object oriented programming 7 first steps in oop using c++
 
PRINCE PRESENTATION(1).pptx
PRINCE PRESENTATION(1).pptxPRINCE PRESENTATION(1).pptx
PRINCE PRESENTATION(1).pptx
 
C++ first s lide
C++ first s lideC++ first s lide
C++ first s lide
 
Programming using C++ - slides.pptx
Programming using C++ - slides.pptxProgramming using C++ - slides.pptx
Programming using C++ - slides.pptx
 
Programming Language
Programming  LanguageProgramming  Language
Programming Language
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
venkatesh.pptx
venkatesh.pptxvenkatesh.pptx
venkatesh.pptx
 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examples
 

Plus de Mukund Trivedi (20)

System development life cycle (sdlc)
System development life cycle (sdlc)System development life cycle (sdlc)
System development life cycle (sdlc)
 
Process of design
Process of designProcess of design
Process of design
 
New file and form 2
New file and form 2New file and form 2
New file and form 2
 
File organisation
File organisationFile organisation
File organisation
 
Evaluation
EvaluationEvaluation
Evaluation
 
Database
DatabaseDatabase
Database
 
Case tools
Case toolsCase tools
Case tools
 
Evaluation
EvaluationEvaluation
Evaluation
 
Dfd final
Dfd finalDfd final
Dfd final
 
Sad
SadSad
Sad
 
C++ file
C++ fileC++ file
C++ file
 
Ff40fnatural resources (1)
Ff40fnatural resources (1)Ff40fnatural resources (1)
Ff40fnatural resources (1)
 
Ff40fnatural resources
Ff40fnatural resourcesFf40fnatural resources
Ff40fnatural resources
 
F58fbnatural resources 2 (1)
F58fbnatural resources 2 (1)F58fbnatural resources 2 (1)
F58fbnatural resources 2 (1)
 
F58fbnatural resources 2
F58fbnatural resources 2F58fbnatural resources 2
F58fbnatural resources 2
 
Ee2fbunit 7
Ee2fbunit 7Ee2fbunit 7
Ee2fbunit 7
 
E212d9a797dbms chapter3 b.sc2 (2)
E212d9a797dbms chapter3 b.sc2 (2)E212d9a797dbms chapter3 b.sc2 (2)
E212d9a797dbms chapter3 b.sc2 (2)
 
E212d9a797dbms chapter3 b.sc2 (1)
E212d9a797dbms chapter3 b.sc2 (1)E212d9a797dbms chapter3 b.sc2 (1)
E212d9a797dbms chapter3 b.sc2 (1)
 
E212d9a797dbms chapter3 b.sc2
E212d9a797dbms chapter3 b.sc2E212d9a797dbms chapter3 b.sc2
E212d9a797dbms chapter3 b.sc2
 
B1ce9 assignmentbsc
B1ce9 assignmentbscB1ce9 assignmentbsc
B1ce9 assignmentbsc
 

Dernier

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 

Dernier (20)

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 

73d32 session1 c++

  • 1. Session – I Module-1 & Module-2 Prepared by - Neetu Gupta ngupta5@amity.edu neetugupta78@gmail.com
  • 2. Contents • Various programming techniques • Procedural approach to OOPs • Introduction to OOPS • C++ program structure – sample program • Input / Output in C++ - cin and cout • Variables and data types • Operators in C++ • Control structure in C++ – looping, selection, jump statements
  • 3. Programming curve • We can distinguish learning curve of programming as : – Unstructured programming, – procedural programming, – modular programming and – object-oriented programming.
  • 4. • Unstructured Programming Usually, people start learning programming by writing small and simple programs consisting only of one main program. Here ``main program'' stands for a sequence of commands or statements which modify data which is global throughout the whole program. main program data Here, the main program directly operates on global data. Disadvantages : Once the program gets sufficiently large. For example, if the same statement sequence is needed at different locations within the program, the sequence must be copied. This has lead to the idea to extract these sequences, name them and offering a technique to call and return from these procedures.
  • 5. • Procedural Programming With procedural programming you are able to combine returning sequences of statements into one single place. A procedure call is used to invoke the procedure. After the sequence is processed, flow of control proceeds right after the position where the call was made. A program can be viewed as a sequence of procedure calls. Main program is responsible to pass data to the individual calls, the data is processed by the procedures and, once the program has finished, the resulting data is presented. The flow of data can be illustrated as a hierarchical graph, a tree, as shown in below for a program with no sub procedures: main program data procedure1 procedure2 procedure3
  • 6. Modular Programming • In modular programming procedures of a common functionality are grouped together into separate modules. • Each module can have its own data. This allows each module to manage an internal state which is modified by calls to procedures of this module. However, there is only one state per module and each module exists at most once in the whole program.
  • 7. Object Oriented programming • Object-oriented programming solves some of the problems just mentioned. In contrast to the other techniques, here we have a web of interacting objects, each house-keeping its own state Objects of the program interact by sending messages to each other.
  • 9. OOPS characteristics • The various characteristics of the Object Oriented Methodology • Identity, • Classification, • Inheritance and • Polymorphism • Abstraction • Encapsulation
  • 10. Identity: – The term Object Oriented means that we organize the software as a collection of discrete objects. – An object is a software package that contains the related data and the methods. Although objects can be used for any purpose, they are most frequently used to represent real-world objects such as products, customers and sales orders. – The basic idea is to define software objects that can interact with each other just as their real world counterparts do, modeling the way a system works and providing a natural foundation for building systems to manage that business. • Classification – In principle, packaging data and procedures together makes perfect sense. – Suppose we have many objects of the same type- for example a thousand product objects, each of which could report its current price. Data values would differ from one product to the next. – But the methods for dealing with these data might well be the same. Do we have to copy these methods and duplicate them in every object? No, this would be ridiculously inefficient. – All object-oriented languages provide a simple way of capturing these commonalties in a single place. That place is called a class. The class acts as a kind of template for objects of similar nature.
  • 11. • Polymorphism – Polymorphism is a Greek word meaning many forms. – It is used to express the fact that the same message can be sent to many different objects and interpreted in different ways by each object. – For example, we could send the message "move" to many different kinds of objects. They would all respond to the same message, but they might do so in very different ways. The move operation will behave differently for a window and differently for a chess piece. • Inheritance – It is the sharing of attributes and operations among classes on a hierarchical relationship. – A class can be defined as a generalized form and then it specialized in a subclass. – Each subclass inherits all the properties of its superclass and adds its own properties in it. – For example, a car and a bicycle are subclasses of a class road vehicle, as they both inherits all the qualities of a road vehicle and add their own properties to it.
  • 12. • Abstraction – In object oriented programming , classes uses the concept of Abstraction fro storing data. – A class encapsulates the relevant data and functions that operate on data by hiding the complex implementation details from the user . – In other words ,user needs to focus on what a class does rather than how it does it.
  • 13. Start c++ - A sample program • A typical hello world C++ program will be like // my first program in C++ #include <iostream> using namespace std; int main () { cout << "Hello World!"; return 0; } Output is : Hello World!
  • 14. Sample program explained // my first program in C++ - Line 1 This is a comment line. All lines beginning with two slash signs (//) are considered comments #include <iostream> - Line 2 • They are not regular code lines with expressions but indications for the compiler's preprocessor. Here the directive tells the preprocessor to include the iostream standard file required for input/out library in C++. using namespace std; - Line 3 • All the elements of the standard C++ library are declared within a namespace with name std. int main () – Line 4 • This line corresponds to the beginning of the definition of the main function. The main function is the point by where all C++ programs start their execution. The body of the main function enclosed in braces ({})
  • 15. cout << "Hello World!"; - Line 4 • It is a C++ statement. • cout is the name of the standard output stream in C++, and the meaning of the entire statement is to insert a sequence of characters (in this case the Hello World sequence of characters) into the standard output stream i.e cout, which usually corresponds to the screen. • cout is declared in the iostream standard file within the std namespace, so that's why we needed to include that specific file and to declare that we were going to use this specific namespace earlier in our code. return 0; - Line 5 • The return statement causes the main function to finish. • return may be followed by a return code like zero here. • A return code of 0 for the main function is generally interpreted as the program worked as expected without any errors during its execution. This is the most usual way to end a C++ console program.
  • 16. Comments • Comments are parts of the source code disregarded by the compiler. They simply do nothing. • Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code. C++ supports two ways to insert comments: • // line comment • /* block comment */
  • 17. • line comment, discards everything from where the pair of slash signs (//) is found up to the end of that same line. cout << "Hello World! "; // prints Hello World! • block comment, discards everything between the /* characters and the first appearance of the */ characters, with the possibility of including more than one line. /* following line print the text Hello world! On screen*/ cout << "Hello World! ";
  • 18. #include <iostream> using namespace std; int main () { cout << "Hello World! "; // prints Hello World! cout << "I'm a C++ program"; // prints I'm a C++ program return 0; } Output is Hello World! I'm a C++ program • Here nothing between /* */ or // till end of line is considered by compiler
  • 19. Data Types • In programming, we store the variables in our computer's memory, but the computer has to know what kind of data we want to store in them, since it is not going to occupy the same amount of memory to store a simple number than to store a single letter or a large number, and they are not going to be interpreted the same way. • Depending upon the type of data it can store and the memory requirement, the data types are classified in C++ as:
  • 20. Summary of C ++Data Types Name Description Size* Range* Character or small signed: -128 to 127 char 1byte integer. unsigned: 0 to 255 short int signed: -32768 to 32767 Short Integer. 2bytes (short) unsigned: 0 to 65535 signed: -2147483648 to 2147483647 int Integer. 4bytes unsigned: 0 to 4294967295 signed: -2147483648 to long int 2147483647 Long integer. 4bytes (long) unsigned: 0 to 4294967295 Boolean value. It can take bool one of two values: true or 1byte true or false false. float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits) Double precision floating +/- 1.7e +/- 308 (~15 double 8bytes point number. digits) Long double precision +/- 1.7e +/- 308 (~15 long double 8bytes floating point number. digits)
  • 21. Variables • We can define a variable as a portion of memory to store a value • Each variable needs an identifier (name) that distinguishes it from the others. • A valid identifier is a sequence of one or more letters, digits or underscore characters (_). Neither spaces nor punctuation marks or symbols can be part of an identifier. Only letters, digits and single underscore characters are valid. • A Variable identifiers always have to begin with a letter or underscore (_) • The C++ language is a "case sensitive" language. It means that an identifier in capital letters is not equivalent to one with the same name but in small letters. Like RESULT variable is not the same as the result variable or the Result variable. These are three different variable identifiers.
  • 22. Declaration of variables • We must first declare a variable specifying which data type we want it to be. • The syntax to declare a new variable is datatype variable-name; • Example could be int a; float mynumber; Here, The first one declares a variable of type int with the identifier a. The second one declares a variable of type float with the identifier mynumber.
  • 23. • We can declare more than one variable of the same type, in a single statement by separating their identifiers with commas. For example: int a, b, c; • The integer data types char, short, long and int can be either signed or unsigned based on the range of numbers needed – Signed types can represent both +ve and –ve values, – unsigned types can only represent +ve values (and zero) unsigned short int num; // only +ve values signed int balance; // +ve & -ve values
  • 24. // PROGRAM - operating with variables #include <iostream> using namespace std; int main () { // declaring variables: int a, b, result; // process: a = 5; b = 2; a = a + 1; result = a - b; // print out the result: cout << “Result: ” << result; // terminate the program: return 0; } Output is: Result: 4
  • 25. Constants • Constants are expressions with a fixed value. • Constants are values which remain same through out the execution of a program. • In c++ there are various ways to use constants, as: – Literals – Defined constants (# define) – Declared constants ( const)
  • 26. Literal Constants • They are used to express particular values within the source code of a program. • For example, a = 5; Here, 5 in this piece of code was a literal constant. • Literal constants can be divided in • Integer Numerals, • Floating-Point Numerals, • Characters, • Strings and • Boolean Values.
  • 27. Defined constants ( # define) • You can define your own names for constants that you use very often without having to resort to memory- consuming variables • It can be done by using the #define preprocessor directive. Its format is: #define identifier value • For example: #define PI 3.14159 #define NEWLINE 'n' This defines two new constants: PI and NEWLINE. Once they are defined, you can use them in the rest of the code as if they were any other regular constant
  • 28. // PROGRAM - defined constants: calculate circumference #include <iostream> using namespace std; #define PI 3.14159 #define NEWLINE 'n' int main () { double r=5.0; // radius double circle; circle = 2 * PI * r; cout << circle; cout << NEWLINE; return 0; } Output is: 31.4159 • Only thing that the compiler preprocessor does when it encounters #define directives is to literally replace any occurrence of their identifier (in the previous example, these were PI and NEWLINE) by the code to which they have been defined (3.14159 and 'n' respectively).
  • 29. Declared constants (const) • With the const prefix you can declare constants with a specific type in the same way as you would do with a variable const int pathwidth = 100; const char tabulator = 't'; • Here, pathwidth and tabulator are two typed constants. They are treated just like regular variables except that their values cannot be modified after their definition. If modified it will be a compilation error like pathwidth= 200; // Compilation error
  • 30. Basic Input/Output • C++ uses a convenient abstraction called streams to perform input and output operations in sequential media such as the screen or the keyboard. • A stream is an object where a program can either insert or extract characters to/from it. • The standard C++ library includes the header file iostream, where the standard input and output stream objects are declared.
  • 31. Standard Output Stream- cout • By default, the standard output of a program is the screen, and the C++ stream object defined to access it is cout. • cout is used in conjunction with the insertion operator, which is written as << • A brief example can be cout << "Output sentence"; // prints Output sentence on screen cout << 120; // prints number 120 on screen cout << x; // prints the content of x on screen
  • 32. • The insertion operator (<<) may be used more than once in a single statement. The below statement would print the message Hello, I am a C++ statement on the screen. cout << "Hello, " << "I am " << "a C++ statement"; • The utility of repeating the insertion operator (<<) is demonstrated when we want to print out a combination of variables and constants or more than one variable. Here, age and zipcode are variables. : cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode; Output is: Hello, I am 50 years old and my zipcode is 90065 If age = 50 and zipcode = 90065
  • 33. • Notice that cout does not add a line break after its output unless we explicitly indicate it, therefore, the following statements: cout << "This is a sentence."; cout << “ This is another sentence."; Output is : This is a sentence. This is another sentence. • In order to perform a line break on the output we must explicitly insert a new-line character n cout << "First sentence.n"; cout << "Second sentence.nThird sentence."; Output is: First sentence. Second sentence. Third sentence.
  • 35. • cin can only process the input from the keyboard once the RETURN key has been pressed. • Therefore, even if you request a single character, the extraction from cin will not process the input until the user presses RETURN • You must always consider the type of the variable that you have mentioned with cin. If you request an integer you will get an integer, if you request a character you will get a character etc.
  • 36. // PROGRAM - i/o #include <iostream> using namespace std; int main () { int i; cout << "Please enter an integer value: "; cin >> i; cout << "The value you entered is " << i; cout << " and its double is " << i*2 << ".n"; return 0; } Output is : Please enter an integer value: 702 The value you entered is 702 and its double is 1404.
  • 37. • You can also use cin to request more than one datum input from the user: cin >> a >> b; is equivalent to: cin >> a; cin >> b; • In both above cases the user must give two data, one for variable a and another one for variable b that may be separated by any valid blank separator: a space, a tab character or a newline.
  • 38. Operators in C++ • Once we know of the existence of variables and constants, we can begin to operate with them to make complex programs to solve problems. • For that purpose, C++ provides a various range of operators. • C++ provide various operators which operate on different type of data type variables and constants.
  • 39. Assignment Operator • Assignment (=) operator The assignment operator assigns a value to a variable. a = 5; • This statement assigns the integer value 5 to the variable a. • The part at the left of the assignment operator (=) is known as the lvalue (left value) and the right one as the rvalue (right value). • The lvalue has to be a variable whereas the rvalue can be either a constant, a variable, the result of an operation or any combination of these.
  • 40. Assignment operator - Example #include <iostream> using namespace std; int main () { int a, b; a = 10; b = 4; b:4 a = b = 7; cout << "a:“ << a; cout << " b:“ << b; return 0; } output is: a:4 b:7
  • 41. Arithmetic operators • The basic five arithmetical operations supported by the C++ language are: + : represents mathematical addition - : represents mathematical subtraction * : represents mathematical multiplication / : represents mathematical division % : represents modulo (Gives remainder of division of two values) a = 11 % 3; here, variable a will contain the value 2, since 2 is the remainder from dividing 11 between 3.
  • 42. Relational operators • In order to evaluate a comparison between two expressions we can use the relational operators. The result of a relational operation is a Boolean value that can only be true or false == Equal to != Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to
  • 43. Relational operators - Example Suppose that a=2, b=3 and c=6, (a == 5) // evaluates to false since a is not equal to 5. (a*b >= c) // evaluates to true since (2*3 >= 6) is true. (b+4 > a*c) // evaluates to false since (3+4 > 2*6) ((b=2) == a) // evaluates to true. (a != b) // evaluates to true
  • 44. Logical operators Three logical operators : !, &&, || • ! : NOT C++ operator to perform the Boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its operand is false. Example: !(5 == 5) // false because the expression at its right (5 == 5) is true. !(6 <= 4) // true because (6 <= 4) would be false. !true // evaluates to false !false // evaluates to true.
  • 45. Logical operators • &&: AND The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true, and false otherwise. The following panel shows the result of operator && evaluating the expression a && b: a b A && b true true true true false false false true false false false false ( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
  • 46. Logical operators • || operator - OR The operator || corresponds with Boolean logical operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves. Here are the possible results a b a||b true true true true false false false true false false false false ( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
  • 47. Conditional operator • The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false. Its format is: condition ? result1 : result2 • If condition is true the expression will return result1, if it is not it will return result2. 7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5. 7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2. 5>3 ? a : b // returns the value of a, since 5 is greater than 3. a>b ? a : b // returns whichever is greater, a or b.
  • 48. // conditional operator #include <iostream> using namespace std; int main () { int a,b,c; a=2; b=7; c = (a>b) ? a : b; cout << “C:” << c; return 0; } Output is: c: 7 • In this example a was 2 and b was 7, so the expression being evaluated (a>b) was not true, thus the first value specified after the question mark was discarded in favor of the second value (the one after the colon) which was b, with a value of 7.
  • 49. Comma operator ( , ) • The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. • When the set of expressions has to be evaluated for a value, only the rightmost expression is considered. For example, the following code: a = (b=3, b+2); It would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would contain the value 5 while variable b would contain value 3.
  • 50. Increment/Decrement operators • The increment operator (++) increases by one the value stored in a variable. • The following two statements are similar: c++; // using increment operator c=c+1; Both increases the value of c by 1; • The decrement operator (--) decreases by one the value stored in a variable. • The following two statements are similar: c--; // using decrement operator c=c-1; Both decreases the value of c by 1;
  • 51. Increment/Decrement operators • These operators can be used both as a prefix or as a suffix. i.e. can be written either before the variable (++a) or after it (a++). If the operator is used as a prefix (++a) the value is increased before the result of the expression is evaluated and therefore the increased value is considered in the outer expression; If it is used as a suffix (a++) the value stored in a is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the outer expression.
  • 52. Increment/Decrement operators Notice the difference in below example : Example 1 Example 2 B=3; B=3; A=++B; A=B++; // A contains 4, B contains 4 // A contains 3, B contains 4 In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and then B is increased.
  • 53. sizeof() operator • This operator accepts one parameter, which can be either a type or a variable itself and returns the size in bytes of that type or object: a = sizeof (char); This will assign the value 1 to a because char is a one-byte long type. • The value returned by sizeof is a constant, so it is always determined before program execution.
  • 54. Explicit type casting operator • Type casting operators allow you to convert a data of a one type to another type. • The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses (()):
  • 55. Explicit type casting operator - Example Below code converts the float number 3.14 to an integer value (3), the remainder is lost. int i; float f = 3.14; i = (int) f; Here the typecasting operator was (int). • Another way to do the same thing in C++ is using the functional notation: preceding the expression to be converted by the type and enclosing the expression between parentheses: i = int ( f );
  • 56. Precedence of operators • When writing complex expressions with several operands, we may have some doubts about which operand is evaluated first and which later. For example, in this expression: a=5+7%2 we may doubt if it really means: a = 5 + (7 % 2) // with a result of 6, or a = (5 + 7) % 2 // with a result of 0
  • 57. Precedence of operators • There is an established order with the priority of each operator, and not only the arithmetic ones (those whose preference come from mathematics) but for all the operators which can appear in C++. From greatest to lowest priority, the priority order is as follows: • Grouping defines the precedence order in which operators are evaluated in the case that there are several operators of the same level in an expression.
  • 58. Precedence with associativity Level Operator Description Grouping 1 :: scope Left-to-right () [] . -> ++ -- dynamic_cast 2 static_cast reinterpret_cast postfix Left-to-right const_cast typeid ++ -- ~ ! sizeof new delete unary (prefix) indirection and 3 Right-to-left *& reference (pointers) +- unary sign operator 4 (type) type casting Right-to-left 5 .* ->* pointer-to-member Left-to-right 6 */% multiplicative Left-to-right 7 +- additive Left-to-right 8 << >> shift Left-to-right
  • 59. Level Operator Description Grouping 9 < > <= >= relational Left-to-right 10 == != equality Left-to-right 11 & bitwise AND Left-to-right 12 ^ bitwise XOR Left-to-right 13 | bitwise OR Left-to-right 14 && logical AND Left-to-right 15 || logical OR Left-to-right 16 ?: conditional Right-to-left = *= /= %= += -= 17 assignment Right-to-left >>= <<= &= ^= |= 18 , comma Left-to-right
  • 60. Statements • A C++ program is made up of various up of statements, where a Statement is a part of your program that can be executed. • Every statement in your program alone or in combination specifies an action to performed by your program. • Inheriting from c, c++ provides variety of statements to help you attain any function with maximum flexibility and efficiency. • A program is formed by a sequence of one or more statements.
  • 61. Kinds of Statements • The following are the major generic kinds of statements with examples in typical imperative languages: 3. Simple statements • A simple statement is a single line of code which is executed independently irrespective of other statements in a program. • The various types of single statements could be: Assignment: A:= A + 1 // expression call: CLEARSCREEN() // call to a function return: return 5; // return from a function goto: goto 1 // jump to statement labeled 1
  • 62. Kinds of Statements 1. Compound statements • A compound statement consists of zero or more statements enclosed in curly braces ({ }). • A compound statement can be used anywhere a statement is expected. Compound statements are commonly called "blocks.“ • The various types of compound statements could be : – if-statement: – switch-statement – while-loop – do-loop – for-loop
  • 63. Control Statements • A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances. • With the introduction of control structures we are going to have to introduce a new concept: the compound-statement or block. A block is a group of statements which are separated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in braces: { }: { statement1; statement2; statement3; }
  • 64. If statement • if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is: if (condition) statement • If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional structure.
  • 65. If statement - Example • For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100: if (x == 100) cout << "x is 100"; • If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces { }: if (x == 100) { cout << "x is "; cout << x; }
  • 66. If-else statement • We can specify what we want to doif the condition is not fulfilled by using the keyword else. • The else is used in conjunction with if is: if (condition) statement1 else statement2
  • 67. If-else statement – Example http://www.cplusplus.com/doc/tutorial/control/ • Following code prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x is not 100. if (x == 100) cout << "x is 100"; else cout << "x is not 100";
  • 68. while loop statement • Its purpose is to repeat statement(s) a certain number of times or while a condition is true. The format is: while (condition) statement; or while (condition) { statement1; statement2; …….. }
  • 69. while loop statement - Example • // print the number from n to 1 #include <iostream> using namespace std; int main () { int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; --n; } return 0; }
  • 70. while loop statement - Example In the above example while loop begins, • if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true i.e. till n=0; Output will be as: Enter the starting number > 8 8, 7, 6, 5, 4, 3, 2, 1
  • 71. do-while loop • Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. Its format is: do statement while (condition); or do { statement ; ……………….. } while (condition);
  • 72. do-while loop - Example
  • 73. do-while loop - Example • The above code is executed at least once. • As you see above the condition while(n!=0) is checked at the end of loop. That means the loop executes once before checking the condition for the first time. Output is Enter number (0 to end): 12345 You entered: 12345 Enter number (0 to end): 160277 You entered: 160277 Enter number (0 to end): 0 You entered: 0
  • 74. for loop • Its format is: for (initialization; condition; increase) statement; • Its function is to repeat statement while condition remains true, like the while loop. But in addition, the for loop provides specific locations to contain an initialization statement and an increase statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration.
  • 75. for loop - Working for loop works in the following way: • initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once. • condition is checked. If it is true the loop continues, otherwise the loop ends and statement is not executed. • statement is executed. It can be either a single statement or a block enclosed in braces { }. • finally, increase field is executed and the loop gets back to step 2.
  • 76. for loop - Example • // countdown using a for loop #include <iostream> using namespace std; int main () { for (int n=10; n>0; n--) { cout << n << ", "; } return 0; }
  • 77. for loop - Example • Output is: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 n initializes with a value of 10, the condition is n>0 is checked. The value of n is cout. The value of n is decreased by 1. and condition is checked again. The loop condition becomes false when n=0. In this case, the control jumps out of loop.