Lecture 10
               Arrays,
             Functions &
             Structures


TCP1231 Computer Programming I   1
Objectives

• To Learn about functions and arrays
• Explore how to declare and manipulate arrays
  with functions
• Explore how to declare and manipulate structures
  with functions
• Become familiar with functions, arrays, and
  structures.



  TCP1231 Computer Programming I       2
Functions – Revisited
            (User Defined Function)
• Two components of a function definition
• Function declaration (or function prototype)
   – Shows how the function is called
   – Must appear in the code before the function can be
     called
   – Syntax:
   Type_returned Function_Name(Parameter_List);
   //Comment describing what function does




  TCP1231 Computer Programming I         3
Functions – Revisited
            (User Defined Function)
• Function definition
   – Describes how the function does its task
   – Can appear before or after the function is called
   – Syntax:
       Type_returned Function_Name(Parameter_List)
       {
                //code to make the function work
       }




  TCP1231 Computer Programming I          4
#include <iostream>
using namespace std;                                 int p(int x, int n) {
                                                        int temp=1;
int p(int x, int n);   Function                         for (int i=1; i <= n; i++)       Function
int f(int x);          declaration
                                                           temp= temp * x;               definition
                                                        return temp;
int main() {                                         }
   int no, x, n;
   cout << "Enter a number==> ";                     int f(int x) {
   cin >> no;                                           int temp=1;
   cout << "factorial = "<<f(no);                       for (int i=1; i <= x; i++)
   cout << "nnEnter number 1==> ";                       temp= temp * i;
   cin >> x;                                            return temp;
   cout << "Enter number 2==> ";                     }
   cin >> n;
   cout << "power = "<<p(x,n);

    system(“PAUSE”);
    return 0;                        Function call
}



         TCP1231 Computer Programming I                                              5
Structure and Function Calls

• Structure definition is generally placed outside
  any function definition
   – This makes the structure type available to all code
     that follows the structure definition

• To declare two variables of type CDAccount:

        CDAccount my_account, your_account;

   – My_account and your_account contain distinct
     member variables balance, interest_rate, and term

  TCP1231 Computer Programming I               6
Structures as Arguments

• Structures can be arguments in function calls
   – The formal parameter can be call-by-value
   – The formal parameter can be call-by-reference

• Example:
  void get_data(CDAccount& the_account);

   – Uses the structure type CDAccount as the type
     for a call-by-reference parameter

 TCP1231 Computer Programming I        7
A Structure Definition
//Program to demonstrate the CDAccount structure type.
#include <iostream>
using namespace std;
//Structure for a bank certificate of deposit:
struct CDAccount
{
   double balance;
   double interest_rate;
   int term;      //months until maturity
};                                                           Function declaration:
                                                             To receive struct
                                                             CDAccount as
void get_data(CDAccount& the_account);                       argument

//Postcondition: the_account.balance and the_account.interest_rate
//have been given values that the user entered at the keyboard.


       TCP1231 Computer Programming I                    8
int main( )
{
   CDAccount account;
                                                       Function calling :
   get_data(account);                                  Send account as
                                                       get_data argument

    double rate_fraction, interest;
    rate_fraction = account.interest_rate / 100.0;
    interest = account.balance * rate_fraction * (account.term / 12.0);
    account.balance = account.balance + interest;

    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);
    cout << "When your CD matures in " << account.term << " months,n"
         << "it will have a balance of $" << account.balance << endl;
    return 0;
}


          TCP1231 Computer Programming I                     9
void get_data(CDAccount& the_account)
{
  cout << "Enter account balance: $";
  cin >> the_account.balance;
  cout << "Enter account interest rate: ";                    Function definition :
                                                              Manipulating
  cin >> the_account.interest_rate;                           the_account inside
  cout << "Enter the number of months until                   get_data
                                                              implementation
             maturityn“
     << "(must be 12 or fewer months): ";
  cin >> the_account.term;
}
                        Enter account balance: $100.00
   Sample Output:
                        Enter account interest rate: 10.0
      Output:
                        Enter the number of months until maturity(must
                        be 12 or fewer months): 6
                        When your CD matures in 6 months, it will have
                        a balance of $105.00




        TCP1231 Computer Programming I                   10
Structures as Return Types
• Structures can be the type of a value returned by
  a function
                  students reading(){
• Example:               students rec;
                         cout << "nEnter the student name ==> ";
                         getline(cin, rec.name);
                         cout << "Enter the student ID ==> ";
                         cin >> rec.id;
                         cout << "Enter the student Mark ==> ";
                         cin >> rec.mark;
                         cin.ignore();
                         return rec;
                       }



  TCP1231 Computer Programming I                       11
#include <iostream>                          To read info about three students
using namespace std;                          void printing(students rec)
                                              {
struct students{                                cout << "nThe student name: ";
   string name;                                 cout << rec.name;
   int id;                                      cout << "nThe student ID: ";
   double mark;                                 cout << rec.id;
};                                              cout << "nThe student mark: ";
students reading()                              cout << rec.mark;
{                                             }
  students rec;                               int main() {
  cout << "nEnter the student name ==> ";       int i;
  getline(cin, rec.name);                        students info[3];
  cout << "Enter the student ID ==> ";           for (i=0; i<=2; i++)
  cin >> rec.id;                                    info[i]=reading() ;
  cout << "Enter the student Mark ==> ";
  cin >> rec.mark;                                for (i=0; i<=2; i++)
  cin.ignore();                                      printing(info[i]);
  return rec;
}                                                 return 0;
       TCP1231 Computer Programming I         }                12
Arrays in Function

• Indexed variables can be arguments to functions
   – Example: If a program contains these declarations:
                       int i, n, a[10];
                       void my_function(int n);

     Variables a[0] through a[9] are of type int, making
      these calls legal:
                      my_function( a[ 0 ] );
                      my_function( a[ 3 ] );
                      my_function( a[ i ] );


  TCP1231 Computer Programming I               13
Array as Function Arguments

• A formal parameter can be for an entire array
  – Such a parameter is called an array parameter
      • It is not a call-by-value parameter
      • It is not a call-by-reference parameter

     • Array parameters behave much like call-by-
       reference parameters



 TCP1231 Computer Programming I       14
Array Parameter Declaration

• An array parameter is indicated using empty
  brackets in the parameter list such as

          void fill_up(int a[ ], int size);




  TCP1231 Computer Programming I              15
Function with an Array Parameter

#include<iostream>
using namespace std;
                                                                 Function declaration:
                                                                 To receive an array of
void fill_up(int a[], int size);                                 int, a[] as
//Precondition: size is the declared size of the array a.        argument
// The user will type in size integers.
//Postcondition: The array a is filled with size integers
// from the keyboard.

void fill_up(int a[], int size)
{
  cout << "Enter " << size << " numbers:n";
  for (int i = 0; i < size; i++)                                  Function definition :
                                                                  Manipulating a[]
     cin >> a[i];                                                 inside fill_up
  size--;                                                         implementation
  cout << "The last array index used is " << size << endl;
}

    TCP1231 Computer Programming I                          16
Function calls with array

• If function fill_up is declared in this way:
           void fill_up(int a[ ], int size);

  and array score is declared this way:
          int score[5], number_of_scores;

  fill_up is called in this way:
        fill_up(score, number_of_scores);



  TCP1231 Computer Programming I           17
Function call details

• A formal parameter is identified as an array
  parameter by the [ ]'s with no index expression

      void fill_up(int a[ ], int size);

• An array argument does not use the [ ]'s

      fill_up(score, number_of_scores);



  TCP1231 Computer Programming I         18
Array Formal Parameters

• An array formal parameter is a placeholder for
  the argument

   – When an array is an argument in a function call,

     an action performed on the array parameter is
     performed on the array argument

   – The values of the indexed variables can be
     changed by the function

 TCP1231 Computer Programming I         19
Array Parameter Considerations

• Because a function does not know the size of
  an array argument…
   – The programmer should include a formal parameter
     that specifies the size of the array
   – The function can process arrays of various sizes
       • Function fill_up can be used to fill an array of any
         size:

                      fill_up(score, 5);
                      fill_up(time, 10);


  TCP1231 Computer Programming I                 20
Returning An Array

• Recall that functions can return a value of
  type int, double, char, …, or a class type

• Functions cannot return arrays

• We learn later how to return a pointer to an array




  TCP1231 Computer Programming I          21
#include <iostream>                     To read 9 numbers
using namespace std;
void ReadArray(int arr[] ) {
  int i;                                int main() {
  for (i=0; i < 9; i++)                   int i;
  { cout << "a["<<i<<"]=";                int a[9];
     cin >> arr[i];
  }                                      ReadArray(a);
}
                                         for (i=0; i < 9; i++)
                                            cout << a[i] << 't';

                                        system(“pause”);
                                          return 0;
                                        }




       TCP1231 Computer Programming I                  22
#include <iostream>                        To read 9 numbers, then sort
using namespace std;                       them in ascending order
void ReadArray(int arr[] ) {               int main() {
   int i;                                    int i;
   for (i=0; i < 9; i++)                     int a[9];
   { cout << "a["<<i<<"]=";
      cin >> arr[i];                           ReadArray(a);
   }
}                                              for (i=0; i < 9; i++)
// Bubble sort                                    cout << a[i] << 't';
void sorting(int arr[] ) {                     cout << endl;
   int i, j, temp;
   for (i=0; i < 9; i++)                       sorting(a);
      for (j=0; j < 8; j++)
         if (arr[j] > arr[j+1])                for (i=0; i < 9; i++)
         { temp= arr[j];                          cout << a[i] << 't';
            arr[j]= arr[j+1];
            arr[j+1]= temp;                    system(“pause”);
         }                                     return 0;
}                                          }
          TCP1231 Computer Programming I                     23
Functions and
           Multidimensional Array
• When a one-dimensional array is defined as
  a formal parameter, the size of the array
  may be omitted

void Fun(float list[], int size) {
      . . .
    }



 TCP1231 Computer Programming I   24
Multi Dimensional Array as Parameter

• With two-dimensional arrays, the first dimension (number of
  rows) may be omitted, but not the second dimension (number of
  columns).
  void Fun(float table[ ][5], int rows, int
  cols){
      . . .
  }
• You can specify both dimensions if you choose to.
  void Fun(float table[2][5], int rows, int
  cols){
      . . .
  }

    TCP1231 Computer Programming I             25
#include <iostream>
using namespace std;
const int row=3;                     To two dimensional array
const int col=4;                     then display its elements
void Read2Array(int arr[][col] ) {
  int i,j;
  for (i=0; i<row; i++)
     for ( j=0; j<col; j++)
           cin >> arr[i][j];             int main ()
}                                        {
                                            int a[row][col];
void writing(int arr[][col]) {
  int i,j;                                   Read2Array(a);
  for (i=0; i<row; i++)                      writing(a);
  {
     for ( j=0; j<col; j++)                  system(“pause”);
           cout << arr[i][j] << 't';        return 0;
     cout << endl;                       }
  }
}
        TCP1231 Computer Programming I                   26
#include <iostream>                                 To multiply two arrays
using namespace std;
void multi(int a[][3], int b[][4], int c[][4]) {    int main ()
                                                    {
  int i, j, k;                                         int x[3][3]= {{12, 4, 9}, { -5, 3,
  for (i=0; i<3; i++)                               1}, { 9, 2, -2}};
     for ( j=0; j<4; j++)
     {                                                 int y[3][4]= {{11, 1, 12, 1},{ 2,
        c[i][j]=0;                                  24, 32, 4}, {63, -3, 3, 4}} ;
        for ( k=0; k<3; k++)
            c[i][j]= c[i][j] + a[i][k] * b[k][j];       int z[3][4];
     }
}                                                       multi(x, y, z);
void writing(int arr[][4]) {                            writing(z);
  for (int i=0; i<3; i++)
  {                                                     system(“pause”);
     for ( int j=0; j<4; j++)                           return 0;
         cout << arr[i][j] << 't';                 }
     cout << endl;
  }
}       TCP1231 Computer Programming I                                 27
The End



TCP1231 Computer Programming I   28

Computer Programming- Lecture 10

  • 1.
    Lecture 10 Arrays, Functions & Structures TCP1231 Computer Programming I 1
  • 2.
    Objectives • To Learnabout functions and arrays • Explore how to declare and manipulate arrays with functions • Explore how to declare and manipulate structures with functions • Become familiar with functions, arrays, and structures. TCP1231 Computer Programming I 2
  • 3.
    Functions – Revisited (User Defined Function) • Two components of a function definition • Function declaration (or function prototype) – Shows how the function is called – Must appear in the code before the function can be called – Syntax: Type_returned Function_Name(Parameter_List); //Comment describing what function does TCP1231 Computer Programming I 3
  • 4.
    Functions – Revisited (User Defined Function) • Function definition – Describes how the function does its task – Can appear before or after the function is called – Syntax: Type_returned Function_Name(Parameter_List) { //code to make the function work } TCP1231 Computer Programming I 4
  • 5.
    #include <iostream> using namespacestd; int p(int x, int n) { int temp=1; int p(int x, int n); Function for (int i=1; i <= n; i++) Function int f(int x); declaration temp= temp * x; definition return temp; int main() { } int no, x, n; cout << "Enter a number==> "; int f(int x) { cin >> no; int temp=1; cout << "factorial = "<<f(no); for (int i=1; i <= x; i++) cout << "nnEnter number 1==> "; temp= temp * i; cin >> x; return temp; cout << "Enter number 2==> "; } cin >> n; cout << "power = "<<p(x,n); system(“PAUSE”); return 0; Function call } TCP1231 Computer Programming I 5
  • 6.
    Structure and FunctionCalls • Structure definition is generally placed outside any function definition – This makes the structure type available to all code that follows the structure definition • To declare two variables of type CDAccount: CDAccount my_account, your_account; – My_account and your_account contain distinct member variables balance, interest_rate, and term TCP1231 Computer Programming I 6
  • 7.
    Structures as Arguments •Structures can be arguments in function calls – The formal parameter can be call-by-value – The formal parameter can be call-by-reference • Example: void get_data(CDAccount& the_account); – Uses the structure type CDAccount as the type for a call-by-reference parameter TCP1231 Computer Programming I 7
  • 8.
    A Structure Definition //Programto demonstrate the CDAccount structure type. #include <iostream> using namespace std; //Structure for a bank certificate of deposit: struct CDAccount { double balance; double interest_rate; int term; //months until maturity }; Function declaration: To receive struct CDAccount as void get_data(CDAccount& the_account); argument //Postcondition: the_account.balance and the_account.interest_rate //have been given values that the user entered at the keyboard. TCP1231 Computer Programming I 8
  • 9.
    int main( ) { CDAccount account; Function calling : get_data(account); Send account as get_data argument double rate_fraction, interest; rate_fraction = account.interest_rate / 100.0; interest = account.balance * rate_fraction * (account.term / 12.0); account.balance = account.balance + interest; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "When your CD matures in " << account.term << " months,n" << "it will have a balance of $" << account.balance << endl; return 0; } TCP1231 Computer Programming I 9
  • 10.
    void get_data(CDAccount& the_account) { cout << "Enter account balance: $"; cin >> the_account.balance; cout << "Enter account interest rate: "; Function definition : Manipulating cin >> the_account.interest_rate; the_account inside cout << "Enter the number of months until get_data implementation maturityn“ << "(must be 12 or fewer months): "; cin >> the_account.term; } Enter account balance: $100.00 Sample Output: Enter account interest rate: 10.0 Output: Enter the number of months until maturity(must be 12 or fewer months): 6 When your CD matures in 6 months, it will have a balance of $105.00 TCP1231 Computer Programming I 10
  • 11.
    Structures as ReturnTypes • Structures can be the type of a value returned by a function students reading(){ • Example: students rec; cout << "nEnter the student name ==> "; getline(cin, rec.name); cout << "Enter the student ID ==> "; cin >> rec.id; cout << "Enter the student Mark ==> "; cin >> rec.mark; cin.ignore(); return rec; } TCP1231 Computer Programming I 11
  • 12.
    #include <iostream> To read info about three students using namespace std; void printing(students rec) { struct students{ cout << "nThe student name: "; string name; cout << rec.name; int id; cout << "nThe student ID: "; double mark; cout << rec.id; }; cout << "nThe student mark: "; students reading() cout << rec.mark; { } students rec; int main() { cout << "nEnter the student name ==> "; int i; getline(cin, rec.name); students info[3]; cout << "Enter the student ID ==> "; for (i=0; i<=2; i++) cin >> rec.id; info[i]=reading() ; cout << "Enter the student Mark ==> "; cin >> rec.mark; for (i=0; i<=2; i++) cin.ignore(); printing(info[i]); return rec; } return 0; TCP1231 Computer Programming I } 12
  • 13.
    Arrays in Function •Indexed variables can be arguments to functions – Example: If a program contains these declarations: int i, n, a[10]; void my_function(int n); Variables a[0] through a[9] are of type int, making these calls legal: my_function( a[ 0 ] ); my_function( a[ 3 ] ); my_function( a[ i ] ); TCP1231 Computer Programming I 13
  • 14.
    Array as FunctionArguments • A formal parameter can be for an entire array – Such a parameter is called an array parameter • It is not a call-by-value parameter • It is not a call-by-reference parameter • Array parameters behave much like call-by- reference parameters TCP1231 Computer Programming I 14
  • 15.
    Array Parameter Declaration •An array parameter is indicated using empty brackets in the parameter list such as void fill_up(int a[ ], int size); TCP1231 Computer Programming I 15
  • 16.
    Function with anArray Parameter #include<iostream> using namespace std; Function declaration: To receive an array of void fill_up(int a[], int size); int, a[] as //Precondition: size is the declared size of the array a. argument // The user will type in size integers. //Postcondition: The array a is filled with size integers // from the keyboard. void fill_up(int a[], int size) { cout << "Enter " << size << " numbers:n"; for (int i = 0; i < size; i++) Function definition : Manipulating a[] cin >> a[i]; inside fill_up size--; implementation cout << "The last array index used is " << size << endl; } TCP1231 Computer Programming I 16
  • 17.
    Function calls witharray • If function fill_up is declared in this way: void fill_up(int a[ ], int size); and array score is declared this way: int score[5], number_of_scores; fill_up is called in this way: fill_up(score, number_of_scores); TCP1231 Computer Programming I 17
  • 18.
    Function call details •A formal parameter is identified as an array parameter by the [ ]'s with no index expression void fill_up(int a[ ], int size); • An array argument does not use the [ ]'s fill_up(score, number_of_scores); TCP1231 Computer Programming I 18
  • 19.
    Array Formal Parameters •An array formal parameter is a placeholder for the argument – When an array is an argument in a function call, an action performed on the array parameter is performed on the array argument – The values of the indexed variables can be changed by the function TCP1231 Computer Programming I 19
  • 20.
    Array Parameter Considerations •Because a function does not know the size of an array argument… – The programmer should include a formal parameter that specifies the size of the array – The function can process arrays of various sizes • Function fill_up can be used to fill an array of any size: fill_up(score, 5); fill_up(time, 10); TCP1231 Computer Programming I 20
  • 21.
    Returning An Array •Recall that functions can return a value of type int, double, char, …, or a class type • Functions cannot return arrays • We learn later how to return a pointer to an array TCP1231 Computer Programming I 21
  • 22.
    #include <iostream> To read 9 numbers using namespace std; void ReadArray(int arr[] ) { int i; int main() { for (i=0; i < 9; i++) int i; { cout << "a["<<i<<"]="; int a[9]; cin >> arr[i]; } ReadArray(a); } for (i=0; i < 9; i++) cout << a[i] << 't'; system(“pause”); return 0; } TCP1231 Computer Programming I 22
  • 23.
    #include <iostream> To read 9 numbers, then sort using namespace std; them in ascending order void ReadArray(int arr[] ) { int main() { int i; int i; for (i=0; i < 9; i++) int a[9]; { cout << "a["<<i<<"]="; cin >> arr[i]; ReadArray(a); } } for (i=0; i < 9; i++) // Bubble sort cout << a[i] << 't'; void sorting(int arr[] ) { cout << endl; int i, j, temp; for (i=0; i < 9; i++) sorting(a); for (j=0; j < 8; j++) if (arr[j] > arr[j+1]) for (i=0; i < 9; i++) { temp= arr[j]; cout << a[i] << 't'; arr[j]= arr[j+1]; arr[j+1]= temp; system(“pause”); } return 0; } } TCP1231 Computer Programming I 23
  • 24.
    Functions and Multidimensional Array • When a one-dimensional array is defined as a formal parameter, the size of the array may be omitted void Fun(float list[], int size) { . . . } TCP1231 Computer Programming I 24
  • 25.
    Multi Dimensional Arrayas Parameter • With two-dimensional arrays, the first dimension (number of rows) may be omitted, but not the second dimension (number of columns). void Fun(float table[ ][5], int rows, int cols){ . . . } • You can specify both dimensions if you choose to. void Fun(float table[2][5], int rows, int cols){ . . . } TCP1231 Computer Programming I 25
  • 26.
    #include <iostream> using namespacestd; const int row=3; To two dimensional array const int col=4; then display its elements void Read2Array(int arr[][col] ) { int i,j; for (i=0; i<row; i++) for ( j=0; j<col; j++) cin >> arr[i][j]; int main () } { int a[row][col]; void writing(int arr[][col]) { int i,j; Read2Array(a); for (i=0; i<row; i++) writing(a); { for ( j=0; j<col; j++) system(“pause”); cout << arr[i][j] << 't'; return 0; cout << endl; } } } TCP1231 Computer Programming I 26
  • 27.
    #include <iostream> To multiply two arrays using namespace std; void multi(int a[][3], int b[][4], int c[][4]) { int main () { int i, j, k; int x[3][3]= {{12, 4, 9}, { -5, 3, for (i=0; i<3; i++) 1}, { 9, 2, -2}}; for ( j=0; j<4; j++) { int y[3][4]= {{11, 1, 12, 1},{ 2, c[i][j]=0; 24, 32, 4}, {63, -3, 3, 4}} ; for ( k=0; k<3; k++) c[i][j]= c[i][j] + a[i][k] * b[k][j]; int z[3][4]; } } multi(x, y, z); void writing(int arr[][4]) { writing(z); for (int i=0; i<3; i++) { system(“pause”); for ( int j=0; j<4; j++) return 0; cout << arr[i][j] << 't'; } cout << endl; } } TCP1231 Computer Programming I 27
  • 28.
    The End TCP1231 ComputerProgramming I 28