SlideShare a Scribd company logo
1 of 31
Lecture 9
              Arrays and
              Functions



TCP1231 Computer Programming I   1
Objectives

   • To Learn about arrays
   • Explore how to declare and manipulate data
     into arrays
   • Understand the meaning of “array index out of
     bounds”
   • Become familiar with the restrictions on array
     processing




   TCP1231 Computer Programming I       2
Two kinds of Multidimensional
   Arrays
There are two basic ways of implementing 2-
dimensional arrays:
      true two-dimensional arrays, and
      arrays of arrays.

Some languages use one method, some another,
and some both.

C++ allows both methods, and each has its
advantages and disadvantages.
   TCP1231 Computer Programming I   3
Two kinds of Multidimensional
   Arrays
1. True arrays
   • In this case the rows are laid out sequentially in memory.
   • This provides simplicity in memory management and a slight
      speed advantage.
   • This is the kind of array C/C++ creates by default.

1. Arrays of arrays
   • In this style each element of a one-dimensional array is a
      pointer to another array.
   • It's a common way to create an array of C-strings.
   • The disadvantage is that memory management can be a little
      more complex and there is a slight performance overhead.



     TCP1231 Computer Programming I            4
Multidimensional Array Declaration

Syntax

Type Array_Name[Size_Dim_1][Size_Dim_2] . . . [Size_Dim_Last];

Examples

    char page[30][100];
    int matrix[2][3];
    double three_d_picture[10][20][30];

An array declaration, of the form shown, defines one indexed variable for each
combination of array indexes. For instance, the second of the sample declarations
defines the following six indexed variables for the array matrix:

    matrix[0][0], matrix[0][1], matrix[0][2],
    matrix[1][0], matrix[1][1], matrix[0][2]

         TCP1231 Computer Programming I                    5
Multidimensional Array Parameters
When a multidimensional array parameter is given in a function
heading or function declaration, the size of the first dimension
is not given, but the remaining dimension sizes must be given in
square brackets.
Since the first dimension size is not given, we usually need an
additional parameter of type int that gives the size of this first
dimension.
Below is an example of a function declaration with a two-
dimensional array parameter p:

       void get_page(char p[][100], int size_dimension_1);



    TCP1231 Computer Programming I                 6
#include <iostream>
using namespace std;

int main ()
{
   int col, row;

    for (row=0; row <=2; row++)
                                                          a[0,0] a[0,1] a[0,2]
     {
          for (col=0; col <=2; col++)                     a[1,0] a[1,1] a[1,2]
              cout << "a[" <<row << "," << col << "] ";   a[2,0] a[2,1] a[2,2]
          cout << endl;
     }

    system(“pause”);
    return 0;
}




        TCP1231 Computer Programming I                       7
#include <iostream>
using namespace std;                                    Read an array of 3x3
                                                        then print its elements
int main ()
{                                                       input       a[0,0]= 5
   int col, row;                                                    a[0,1]= -6
   int a[3][3];                                                     a[0,2]= 1
   for (row=0; row <=2; row++)
                                                                    a[1,0]= 7
      for (col=0; col <=2; col++)
        {                                                           a[1,1]= 88
           cout << "a[" <<row << "," << col << "]= ";               a[1,2]= 2
           cin >> a[row][col];                                      a[2,0]= 0
        }                                                           a[2,1]= 5
   for (row=0; row <=2; row++)
                                                                    a[2,2]= 9
   {
      for (col=0; col <=2; col++)
            cout << a[row][col] << 't';                output 5         -6      1
      cout << endl;                                            7         88      2
   }                                                           0         5       9
}
       TCP1231 Computer Programming I                           8
#include <iostream>
using namespace std;                                     Read an array of 3x3
                                                         then print Max. No.
int main ()
{                                                        input
   int col, row, max;                                                a[0,0]= 5
   int a[3][3];                                                      a[0,1]= -6
   for (row=0; row <=2; row++)                                       a[0,2]= 1
      for (col=0; col <=2; col++)
                                                                     a[1,0]= 7
        {
            cout << "a[" <<row << "," << col << "]= ";               a[1,1]= 88
            cin >> a[row][col];                                      a[1,2]= 2
        }                                                            a[2,0]= 0
   max=a[0][0];                                                      a[2,1]= 5
   for (row=0; row <=2; row++)
                                                                     a[2,2]= 9
      for (col=0; col <=2; col++)
          if (max< a[row][col])                          output
             max=a[row][col];                                        Max= 88
  cout << "nMax= " << max;
}
       TCP1231 Computer Programming I                            9
#include <iostream>
using namespace std;         Convert Tow-Dimensional Array a(3x3)
                             to One Dimensional Array b(9)
int main ()
{                                                       input
   int col, row, i, j, c=0;                                          a[0,0]= -5
   int a[3][3], b[9];                                                a[0,1]= 4
   for (row=0; row <=2; row++)                                       a[0,2]= 97
      for (col=0; col <=2; col++)
                                                                     a[1,0]= -6
        {
           cout << "a[" <<row << "," << col << "]= ";                a[1,1]= 5
           cin >> a[row][col];                                       a[1,2]= -8
        }                                                            a[2,0]= -1
   for (int i=0; i<3; i++)                                           a[2,1]= 44
      for (int j=0; j<3; j++)
                                                                     a[2,2]= 2
       { b[c]=a[i][j]; c++; }
                                                        output
    for (int i=0 ;i<9; i++)
         cout << b[i] << 't';         -5    4    97    -6 5 -8         -1 44 2
}
        TCP1231 Computer Programming I                          10
#include <iostream>
using namespace std;                   C(4x3) equal A (4x3) + B (4x3)
int main () {
   int a[4][3]= {{12, 4, 9}, { -5, 3, 1}, { 9, 2, -2}, {3, 2, 22}};
   int b[4][3]= {{11, 1, 12},{ 2, 24, 32}, {63, -3, 3}, {4, -4, 4}} ;
   int i, j, c[4][3];

    for (i=0; i<4; i++)
       for ( j=0; j<3; j++)
         c[i][j]= a[i][j] + b[i][j];
     for (i=0; i<4; i++)
     {
        for ( j=0; j<3; j++)
            cout << c[i][j] << 't';            23    5    21
        cout << endl;                           -3   27     33
     }                                          72    -1    1
    system(“pause”);                            7    -2    26
    return 0;
}
         TCP1231 Computer Programming I                       11
#include <iostream>
using namespace std;     C(4x3) equal A (4x3) + B (4x3)
int main () {
   int a[4][3]= {{12, 4, 9}, { -5, 3, 1}, { 9, 2, -2}, {3, 2, 22}};
   int b[4][3]= {{11, 1, 12},{ 2, 24, 32}, {63, -3, 3}, {4, -4, 4}} ;
   int i, j, c[4][3];
                                           cout << "n***** B ******n";     **** A *****
   for (i=0; i<4; i++)                                                       12 4      9
                                           for (i=0; i<4; i++)               -5 3      1
      for ( j=0; j<3; j++)                 {                                 9    2   -2
         c[i][j]= a[i][j] + b[i][j];          for ( j=0; j<3; j++)           3    2   22
                                                  cout << b[i][j] << 't';
                                                                             ***** B *****
   cout << "n***** A ******n";              cout << endl;                  11 1      12
   for (i=0; i<4; i++)                     }                                 2   24 32
   {                                       cout << "n******C ******n";     63 -3 3
      for ( j=0; j<3; j++)                                                   4   -4 4
                                           for (i=0; i<4; i++)
            cout << a[i][j] << 't';       {                                 ***** C *****
      cout << endl;                           for ( j=0; j<3; j++)           23 5      21
   }                                              cout << c[i][j] << 't';   -3 27 33
                                                                             72 -1 1
                                              cout << endl;                  7   -2 26
                                           }
                                        }
       TCP1231 Computer Programming I                               12
Functions
What is a function?
• A program can be thought of as consisting
  subparts, such as obtaining the input data,
  calculating the output data and displaying the
  output data.

• C++, like most programming languages, has
  facilities to name and code each of these subparts
  separately.

• In C++ these subparts are called functions.

  TCP1231 Computer Programming I        13
Predefined Functions




TCP1231 Computer Programming I   14
//Computes the size of a dog house that can be purchased given the
//user’s budget
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
             const double COST_PER_SQ_FT = 10.50;
             double budget, are, length_side;
             cout << "Enter rhe amount budgeted for your dog house $";
             cin >> budget;
             area = budget/COST_PER_SQ_FT;
             length_side = sqrt(area);
             cout.setf(ios::fixed);
             cout.setf(ios::showpoint);
             cout.precision(2);
             cout << "For a price of $" << budget << endl
                << "I can build for you a luxurious square dog housen"
                << "that is " << length_side
                << "feet on each side.n";
                                    Enter the amount budgeted for your dog house: $ 25.00
             return 0;              For a price of $ 25.00
                                    I can build you a luxurious square dog house
}            TCP1231 Computer Programming I feet on each side. 15
                                    that is 1.54
Programmer-Defined Functions
• We can define our own functions, either in the
  same file as the main part of our program of in a
  separate file so that the functions can be used by
  several different programs.




  TCP1231 Computer Programming I          16
Functions
There are two components to define a function:

1. Function declaration (or function prototype)
       * Shows how the function is called
       * Must appear in the code before the function can be called
       * Normally placed before the main part of your program

2. Function definition (or function body)
       * Describes how the function does its task
       * Can appear before or after the function is called
       * Normally placed after the main part of your program or in
         a separate file.


    TCP1231 Computer Programming I                17
Function Declaration
•   Syntax:
           data_type Function_Name(Parameter_List);


                                        parameter list


data type   function name parameters type formal parameters name


        double total(int number, double price);
        // Compute total cost including 5% sales tax on            ;
        // number_par items at cost of price_par each



    TCP1231 Computer Programming I                   18
Function Definition
•   Syntax:
       data_type Function_Name(Parameter_List);


                                         function header

    double total(int number, double price)
    {
        double tax= 0.05;                                   function
        double subtotal;                                    body
        subtotal= number * price_par - tax;
        return subtotal;
    }

                                              return statement
    TCP1231 Computer Programming I                    19
#include <iostream>
using namespace std;                                                      function declaration
double total_cost(int number_par, double price_par);
//Computes the total cost, including 5% sales tax, on number_par
//items at a cost of price_par each.
int main()
{
             double price, bill;
             int number;
             cout << "Enter the number of items purchased: ";
             cin >> number;                                           function call
             cout << "Enter the price per item $";
             cin >> price;
             bill = total_cost(number, price);                  Enter the number of items purchased: 2
                                                                Enter the price per item: $10.10
             cout.setf(ios::fixed);                             2 items at $10.10 each.
             cout.setf(ios::showpoint);
             cout.precision(2);                                 Final bill, including tax, is $21.21
             cout << number << " items at "
                << "$" << price << " each.n”
                << "Final bill, including tax, is $" << bill
                << endl;
             return 0;                                                function heading
}
double total_cost(int number_par, double price_par)
{
           const double TAX_RATE = 0.05; //5% sales tax                                    function
           double subtotal;                                        function body           definition
             subtotal = price_par * number_par;
             TCP1231 Computer Programming I
             return (subtotal + subtotal*TAX_RATE);                            20
The Return Statement

•   A return statement consists of the keyword return followed by
    an expression.

•   When a return statement is executed, the function call ends

•   Returns the value calculated by the function

•   A void function is does not necessarily contain a return
    statement, however it may optionally have one or more return
    statement.


    TCP1231 Computer Programming I                 21
The Return Statement

•   Syntax
          return expression;
         • expression performs the calculation
             or
         • expression is a variable containing the calculated
            value

•   Example
              return (subtotal + subtotal * tax);
              or
              return subtotal + subtotal * tax;

    TCP1231 Computer Programming I               22
Function Call
• A function call is an expression consisting of the
  function name followed by arguments enclosed in
  parentheses.

• If there is more than one argument, the arguments
  are separated by commas.

• A function call is an expression that can be used
  like any other expression of the type specified for
  the value returned by the function.


  TCP1231 Computer Programming I         23
The Function Call
Syntax

Function_Name(Argument_List);

where the Argument_list is a comma-separated list of arguments:

Argument_1, Argument_2, . . ., Argument_Last

Examples

                                     arguments list
               function name

                   bill = total(number, price);

         return value assigned to bill
    TCP1231 Computer Programming I                    24
Void-Function

What is a void-function?

• Subtasks are implemented as functions in C++.

• In C++, a function must either return a single
  value or return no values at all.

• A function that returns no value is called a void
  function.



  TCP1231 Computer Programming I       25
Void-Function
 void Function_Name(Parameter_List);

There are two main differences between void-function
definitions and the definitions of functions that return one value:

1. Keyword void replaces the data type of the function
2. No return statement




     TCP1231 Computer Programming I                  26
Syntax for a void Function Declaration

    void Function Declaration                                           arguments list
                                                function name
    void Function_Name(Parameter_List);
    Function_Declaration_Comment                     print (average, min, max);
    void Function Definition

     void Function_Name(Parameter_List)      function header
     {
          Declaration_1
          Declaration_2                            void print (int number, double price)
body      ...
                                                   {
          Declaration_Last
          Executable_Statement_1
                                                     double tax= 0.05;
          Executable_Statement_2                     double subtotal;
          ...
          Executable_Statement_Last                   subtotal= number * price_par -
     }                                             tax;
                                                      cout << subtotal;
                                                   }
         TCP1231 Computer Programming I                          27
#include <iostream>
using namespace std;
                                          Multiply a number by itself
int sqr(int x) // to duplicate a number
{
   int y;
   y= x*x;
   return y;
}
int main ()
{
   int a, b;
   a=3;                                     3    9
   b=sqr(a);
   cout << a << 't' <<b;

    system(“pause”);
    return 0;
}
       TCP1231 Computer Programming I                28
#include <iostream>
using namespace std;

double XtothepowerN(int x, int n)     x to the power of n
// to find X to the power of n
{
    double p=1;
    for (int i=1; i<= n; i++)
       p=p * x;
    return p;
}
int main ()
{
   int b;                                  the result is 81
    b=XtothepowerN(3,4);
    cout << "the result is " << b;
    return 0;
}

         TCP1231 Computer Programming I             29
A function is like a small program
• To understand functions, keep the following three points in mind:

    – A function definition is like a small program and calling the
      function is the same thing as running this “small program”.

    – A function uses formal parameters, rather than cin, for input. The
      arguments to the function are the input and they are plugged in for
      the formal parameters.

    – A function does not normally send any output to the screen, but it
      does send a kind of “output” back to the program. The function
      returns a value, which is like the “output” for the function. The
      function uses a return statement instead of a cout statement for
      this “output”.



  TCP1231 Computer Programming I                         30
THE END




TCP1231 Computer Programming I   31

More Related Content

What's hot

FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6rohassanie
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2docSrikanth
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2rohassanie
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperDeepak Singh
 
User defined functions
User defined functionsUser defined functions
User defined functionsshubham_jangid
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009Deepak Singh
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
CBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question PaperCBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question PaperMalathi Senthil
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programsharman kaur
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3rohassanie
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 

What's hot (20)

Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
Pointers
PointersPointers
Pointers
 
Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
CBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question PaperCBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question Paper
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 
Cbse marking scheme 2006 2011
Cbse marking scheme 2006  2011Cbse marking scheme 2006  2011
Cbse marking scheme 2006 2011
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 

Similar to Computer Programming- Lecture 9

ماترێکس به‌ کوردی ئارام
ماترێکس به‌ کوردی ئارامماترێکس به‌ کوردی ئارام
ماترێکس به‌ کوردی ئارامAram Jamal
 
2 d array(part 2) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
2 d array(part 2) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS2 d array(part 2) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
2 d array(part 2) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CSAAKASH KUMAR
 
lecture7.ppt
lecture7.pptlecture7.ppt
lecture7.pptEdFeranil
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings imtiazalijoono
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for SpeedYung-Yu Chen
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...ssuserd6b1fd
 
Introduction to cpp (c++)
Introduction to cpp (c++)Introduction to cpp (c++)
Introduction to cpp (c++)Arun Umrao
 
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...Dr. Volkan OBAN
 
Lecture no 3
Lecture no 3Lecture no 3
Lecture no 3hasi071
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cythonAnderson Dantas
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 
2 d array(part 1) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
2 d array(part 1) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS2 d array(part 1) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
2 d array(part 1) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CSAAKASH KUMAR
 

Similar to Computer Programming- Lecture 9 (20)

ماترێکس به‌ کوردی ئارام
ماترێکس به‌ کوردی ئارامماترێکس به‌ کوردی ئارام
ماترێکس به‌ کوردی ئارام
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
 
C++ TUTORIAL 5
C++ TUTORIAL 5C++ TUTORIAL 5
C++ TUTORIAL 5
 
C++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLESC++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLES
 
2 d array(part 2) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
2 d array(part 2) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS2 d array(part 2) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
2 d array(part 2) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
 
C++ practical
C++ practicalC++ practical
C++ practical
 
lecture7.ppt
lecture7.pptlecture7.ppt
lecture7.ppt
 
array2d.ppt
array2d.pptarray2d.ppt
array2d.ppt
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
Introduction to cpp (c++)
Introduction to cpp (c++)Introduction to cpp (c++)
Introduction to cpp (c++)
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
 
Lecture no 3
Lecture no 3Lecture no 3
Lecture no 3
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cython
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
CS.3.Arrays.pdf
CS.3.Arrays.pdfCS.3.Arrays.pdf
CS.3.Arrays.pdf
 
R programming language
R programming languageR programming language
R programming language
 
2 d array(part 1) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
2 d array(part 1) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS2 d array(part 1) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
2 d array(part 1) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
 

Recently uploaded

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 

Recently uploaded (20)

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 

Computer Programming- Lecture 9

  • 1. Lecture 9 Arrays and Functions TCP1231 Computer Programming I 1
  • 2. Objectives • To Learn about arrays • Explore how to declare and manipulate data into arrays • Understand the meaning of “array index out of bounds” • Become familiar with the restrictions on array processing TCP1231 Computer Programming I 2
  • 3. Two kinds of Multidimensional Arrays There are two basic ways of implementing 2- dimensional arrays:  true two-dimensional arrays, and  arrays of arrays. Some languages use one method, some another, and some both. C++ allows both methods, and each has its advantages and disadvantages. TCP1231 Computer Programming I 3
  • 4. Two kinds of Multidimensional Arrays 1. True arrays • In this case the rows are laid out sequentially in memory. • This provides simplicity in memory management and a slight speed advantage. • This is the kind of array C/C++ creates by default. 1. Arrays of arrays • In this style each element of a one-dimensional array is a pointer to another array. • It's a common way to create an array of C-strings. • The disadvantage is that memory management can be a little more complex and there is a slight performance overhead. TCP1231 Computer Programming I 4
  • 5. Multidimensional Array Declaration Syntax Type Array_Name[Size_Dim_1][Size_Dim_2] . . . [Size_Dim_Last]; Examples char page[30][100]; int matrix[2][3]; double three_d_picture[10][20][30]; An array declaration, of the form shown, defines one indexed variable for each combination of array indexes. For instance, the second of the sample declarations defines the following six indexed variables for the array matrix: matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[0][2] TCP1231 Computer Programming I 5
  • 6. Multidimensional Array Parameters When a multidimensional array parameter is given in a function heading or function declaration, the size of the first dimension is not given, but the remaining dimension sizes must be given in square brackets. Since the first dimension size is not given, we usually need an additional parameter of type int that gives the size of this first dimension. Below is an example of a function declaration with a two- dimensional array parameter p: void get_page(char p[][100], int size_dimension_1); TCP1231 Computer Programming I 6
  • 7. #include <iostream> using namespace std; int main () { int col, row; for (row=0; row <=2; row++) a[0,0] a[0,1] a[0,2] { for (col=0; col <=2; col++) a[1,0] a[1,1] a[1,2] cout << "a[" <<row << "," << col << "] "; a[2,0] a[2,1] a[2,2] cout << endl; } system(“pause”); return 0; } TCP1231 Computer Programming I 7
  • 8. #include <iostream> using namespace std; Read an array of 3x3 then print its elements int main () { input a[0,0]= 5 int col, row; a[0,1]= -6 int a[3][3]; a[0,2]= 1 for (row=0; row <=2; row++) a[1,0]= 7 for (col=0; col <=2; col++) { a[1,1]= 88 cout << "a[" <<row << "," << col << "]= "; a[1,2]= 2 cin >> a[row][col]; a[2,0]= 0 } a[2,1]= 5 for (row=0; row <=2; row++) a[2,2]= 9 { for (col=0; col <=2; col++) cout << a[row][col] << 't'; output 5 -6 1 cout << endl; 7 88 2 } 0 5 9 } TCP1231 Computer Programming I 8
  • 9. #include <iostream> using namespace std; Read an array of 3x3 then print Max. No. int main () { input int col, row, max; a[0,0]= 5 int a[3][3]; a[0,1]= -6 for (row=0; row <=2; row++) a[0,2]= 1 for (col=0; col <=2; col++) a[1,0]= 7 { cout << "a[" <<row << "," << col << "]= "; a[1,1]= 88 cin >> a[row][col]; a[1,2]= 2 } a[2,0]= 0 max=a[0][0]; a[2,1]= 5 for (row=0; row <=2; row++) a[2,2]= 9 for (col=0; col <=2; col++) if (max< a[row][col]) output max=a[row][col]; Max= 88 cout << "nMax= " << max; } TCP1231 Computer Programming I 9
  • 10. #include <iostream> using namespace std; Convert Tow-Dimensional Array a(3x3) to One Dimensional Array b(9) int main () { input int col, row, i, j, c=0; a[0,0]= -5 int a[3][3], b[9]; a[0,1]= 4 for (row=0; row <=2; row++) a[0,2]= 97 for (col=0; col <=2; col++) a[1,0]= -6 { cout << "a[" <<row << "," << col << "]= "; a[1,1]= 5 cin >> a[row][col]; a[1,2]= -8 } a[2,0]= -1 for (int i=0; i<3; i++) a[2,1]= 44 for (int j=0; j<3; j++) a[2,2]= 2 { b[c]=a[i][j]; c++; } output for (int i=0 ;i<9; i++) cout << b[i] << 't'; -5 4 97 -6 5 -8 -1 44 2 } TCP1231 Computer Programming I 10
  • 11. #include <iostream> using namespace std; C(4x3) equal A (4x3) + B (4x3) int main () { int a[4][3]= {{12, 4, 9}, { -5, 3, 1}, { 9, 2, -2}, {3, 2, 22}}; int b[4][3]= {{11, 1, 12},{ 2, 24, 32}, {63, -3, 3}, {4, -4, 4}} ; int i, j, c[4][3]; for (i=0; i<4; i++) for ( j=0; j<3; j++) c[i][j]= a[i][j] + b[i][j]; for (i=0; i<4; i++) { for ( j=0; j<3; j++) cout << c[i][j] << 't'; 23 5 21 cout << endl; -3 27 33 } 72 -1 1 system(“pause”); 7 -2 26 return 0; } TCP1231 Computer Programming I 11
  • 12. #include <iostream> using namespace std; C(4x3) equal A (4x3) + B (4x3) int main () { int a[4][3]= {{12, 4, 9}, { -5, 3, 1}, { 9, 2, -2}, {3, 2, 22}}; int b[4][3]= {{11, 1, 12},{ 2, 24, 32}, {63, -3, 3}, {4, -4, 4}} ; int i, j, c[4][3]; cout << "n***** B ******n"; **** A ***** for (i=0; i<4; i++) 12 4 9 for (i=0; i<4; i++) -5 3 1 for ( j=0; j<3; j++) { 9 2 -2 c[i][j]= a[i][j] + b[i][j]; for ( j=0; j<3; j++) 3 2 22 cout << b[i][j] << 't'; ***** B ***** cout << "n***** A ******n"; cout << endl; 11 1 12 for (i=0; i<4; i++) } 2 24 32 { cout << "n******C ******n"; 63 -3 3 for ( j=0; j<3; j++) 4 -4 4 for (i=0; i<4; i++) cout << a[i][j] << 't'; { ***** C ***** cout << endl; for ( j=0; j<3; j++) 23 5 21 } cout << c[i][j] << 't'; -3 27 33 72 -1 1 cout << endl; 7 -2 26 } } TCP1231 Computer Programming I 12
  • 13. Functions What is a function? • A program can be thought of as consisting subparts, such as obtaining the input data, calculating the output data and displaying the output data. • C++, like most programming languages, has facilities to name and code each of these subparts separately. • In C++ these subparts are called functions. TCP1231 Computer Programming I 13
  • 15. //Computes the size of a dog house that can be purchased given the //user’s budget #include <iostream> #include <cmath> using namespace std; int main() { const double COST_PER_SQ_FT = 10.50; double budget, are, length_side; cout << "Enter rhe amount budgeted for your dog house $"; cin >> budget; area = budget/COST_PER_SQ_FT; length_side = sqrt(area); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "For a price of $" << budget << endl << "I can build for you a luxurious square dog housen" << "that is " << length_side << "feet on each side.n"; Enter the amount budgeted for your dog house: $ 25.00 return 0; For a price of $ 25.00 I can build you a luxurious square dog house } TCP1231 Computer Programming I feet on each side. 15 that is 1.54
  • 16. Programmer-Defined Functions • We can define our own functions, either in the same file as the main part of our program of in a separate file so that the functions can be used by several different programs. TCP1231 Computer Programming I 16
  • 17. Functions There are two components to define a function: 1. Function declaration (or function prototype) * Shows how the function is called * Must appear in the code before the function can be called * Normally placed before the main part of your program 2. Function definition (or function body) * Describes how the function does its task * Can appear before or after the function is called * Normally placed after the main part of your program or in a separate file. TCP1231 Computer Programming I 17
  • 18. Function Declaration • Syntax: data_type Function_Name(Parameter_List); parameter list data type function name parameters type formal parameters name double total(int number, double price); // Compute total cost including 5% sales tax on ; // number_par items at cost of price_par each TCP1231 Computer Programming I 18
  • 19. Function Definition • Syntax: data_type Function_Name(Parameter_List); function header double total(int number, double price) { double tax= 0.05; function double subtotal; body subtotal= number * price_par - tax; return subtotal; } return statement TCP1231 Computer Programming I 19
  • 20. #include <iostream> using namespace std; function declaration double total_cost(int number_par, double price_par); //Computes the total cost, including 5% sales tax, on number_par //items at a cost of price_par each. int main() { double price, bill; int number; cout << "Enter the number of items purchased: "; cin >> number; function call cout << "Enter the price per item $"; cin >> price; bill = total_cost(number, price); Enter the number of items purchased: 2 Enter the price per item: $10.10 cout.setf(ios::fixed); 2 items at $10.10 each. cout.setf(ios::showpoint); cout.precision(2); Final bill, including tax, is $21.21 cout << number << " items at " << "$" << price << " each.n” << "Final bill, including tax, is $" << bill << endl; return 0; function heading } double total_cost(int number_par, double price_par) { const double TAX_RATE = 0.05; //5% sales tax function double subtotal; function body definition subtotal = price_par * number_par; TCP1231 Computer Programming I return (subtotal + subtotal*TAX_RATE); 20
  • 21. The Return Statement • A return statement consists of the keyword return followed by an expression. • When a return statement is executed, the function call ends • Returns the value calculated by the function • A void function is does not necessarily contain a return statement, however it may optionally have one or more return statement. TCP1231 Computer Programming I 21
  • 22. The Return Statement • Syntax return expression; • expression performs the calculation or • expression is a variable containing the calculated value • Example return (subtotal + subtotal * tax); or return subtotal + subtotal * tax; TCP1231 Computer Programming I 22
  • 23. Function Call • A function call is an expression consisting of the function name followed by arguments enclosed in parentheses. • If there is more than one argument, the arguments are separated by commas. • A function call is an expression that can be used like any other expression of the type specified for the value returned by the function. TCP1231 Computer Programming I 23
  • 24. The Function Call Syntax Function_Name(Argument_List); where the Argument_list is a comma-separated list of arguments: Argument_1, Argument_2, . . ., Argument_Last Examples arguments list function name bill = total(number, price); return value assigned to bill TCP1231 Computer Programming I 24
  • 25. Void-Function What is a void-function? • Subtasks are implemented as functions in C++. • In C++, a function must either return a single value or return no values at all. • A function that returns no value is called a void function. TCP1231 Computer Programming I 25
  • 26. Void-Function void Function_Name(Parameter_List); There are two main differences between void-function definitions and the definitions of functions that return one value: 1. Keyword void replaces the data type of the function 2. No return statement TCP1231 Computer Programming I 26
  • 27. Syntax for a void Function Declaration void Function Declaration arguments list function name void Function_Name(Parameter_List); Function_Declaration_Comment print (average, min, max); void Function Definition void Function_Name(Parameter_List) function header { Declaration_1 Declaration_2 void print (int number, double price) body ... { Declaration_Last Executable_Statement_1 double tax= 0.05; Executable_Statement_2 double subtotal; ... Executable_Statement_Last subtotal= number * price_par - } tax; cout << subtotal; } TCP1231 Computer Programming I 27
  • 28. #include <iostream> using namespace std; Multiply a number by itself int sqr(int x) // to duplicate a number { int y; y= x*x; return y; } int main () { int a, b; a=3; 3 9 b=sqr(a); cout << a << 't' <<b; system(“pause”); return 0; } TCP1231 Computer Programming I 28
  • 29. #include <iostream> using namespace std; double XtothepowerN(int x, int n) x to the power of n // to find X to the power of n { double p=1; for (int i=1; i<= n; i++) p=p * x; return p; } int main () { int b; the result is 81 b=XtothepowerN(3,4); cout << "the result is " << b; return 0; } TCP1231 Computer Programming I 29
  • 30. A function is like a small program • To understand functions, keep the following three points in mind: – A function definition is like a small program and calling the function is the same thing as running this “small program”. – A function uses formal parameters, rather than cin, for input. The arguments to the function are the input and they are plugged in for the formal parameters. – A function does not normally send any output to the screen, but it does send a kind of “output” back to the program. The function returns a value, which is like the “output” for the function. The function uses a return statement instead of a cout statement for this “output”. TCP1231 Computer Programming I 30
  • 31. THE END TCP1231 Computer Programming I 31