SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
Srikanth
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
rohassanie
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
rohassanie
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
rohassanie
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
TAlha MAlik
 
User defined functions
User defined functionsUser defined functions
User defined functions
shubham_jangid
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
Deepak Singh
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3
rohassanie
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
Warui Maina
 

Tendances (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
 

Similaire à Computer Programming- Lecture 10

Data structures / C++ Program examples
Data structures / C++ Program examplesData structures / C++ Program examples
Data structures / C++ Program examples
Kevin III
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
DeepasCSE
 

Similaire à 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
 

Dernier

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
ssuserdda66b
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Dernier (20)

Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 

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