SlideShare a Scribd company logo
1 of 28
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

More Related Content

What's hot

C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2docSrikanth
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6rohassanie
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3rohassanie
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functionsTAlha MAlik
 
User defined functions
User defined functionsUser defined functions
User defined functionsshubham_jangid
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperDeepak Singh
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3 rohassanie
 
computer science sample papers 2
computer science sample papers 2computer science sample papers 2
computer science sample papers 2Swarup Kumar Boro
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementSreedhar Chowdam
 
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
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 

What's hot (20)

Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
 
Pointers
PointersPointers
Pointers
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3
 
computer science sample papers 2
computer science sample papers 2computer science sample papers 2
computer science sample papers 2
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
Functions
FunctionsFunctions
Functions
 
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++ Chapter I
C++ Chapter IC++ Chapter I
C++ Chapter I
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 

Similar to Computer Programming- Lecture 10

power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptsbhargavi804095
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented TechnologiesUmesh Nikam
 
OOP program questions with answers
OOP program questions with answersOOP program questions with answers
OOP program questions with answersQuratulain Naqvi
 
Data structures / C++ Program examples
Data structures / C++ Program examplesData structures / C++ Program examples
Data structures / C++ Program examplesKevin III
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxarjurakibulhasanrrr7
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++cpjcollege
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxDeepasCSE
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxSirRafiLectures
 
C++ lab assignment
C++ lab assignmentC++ lab assignment
C++ lab assignmentSaket Pathak
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptxrebin5725
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxShashiShash2
 

Similar to Computer Programming- Lecture 10 (20)

C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ functions
C++ functionsC++ functions
C++ functions
 
CP 04.pptx
CP 04.pptxCP 04.pptx
CP 04.pptx
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
 
OOP program questions with answers
OOP program questions with answersOOP program questions with answers
OOP program questions with answers
 
Data structures / C++ Program examples
Data structures / C++ Program examplesData structures / C++ Program examples
Data structures / C++ Program examples
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptx
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptx
 
C++ lab assignment
C++ lab assignmentC++ lab assignment
C++ lab assignment
 
C++ practical
C++ practicalC++ practical
C++ practical
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 

Recently uploaded

4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 

Recently uploaded (20)

4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 

Computer Programming- Lecture 10

  • 1. Lecture 10 Arrays, Functions & Structures TCP1231 Computer Programming I 1
  • 2. 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
  • 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 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
  • 6. 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
  • 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 //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
  • 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 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
  • 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 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
  • 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 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
  • 17. 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
  • 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 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
  • 26. #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
  • 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 Computer Programming I 28