C++ Passing Array to Function
In C++, to reuse the array logic, we can create a function. To pass an array to a function in C++, we need to provide only the array name.
function_name(array_name[]); //passing array to function
Example: Print the minimum number in the given array.
C++
#include <iostream> using namespace std; void printMin( int arr[5]); int main() { int ar[5] = { 30, 10, 20, 40, 50 }; printMin(ar); // passing array to function } void printMin( int arr[5]) { int min = arr[0]; for ( int i = 0; i < 5; i++) { if (min > arr[i]) { min = arr[i]; } } cout << "Minimum element is: " << min << "\n" ; } // Code submitted by Susobhan Akhuli |
Output
Minimum element is: 10
Time complexity: O(n) where n is the size of the array
Space complexity: O(n) where n is the size of the array.
Functions in C++
A function is a set of statements that takes input, does some specific computation, and produces output. The idea is to put some commonly or repeatedly done tasks together to make a function so that instead of writing the same code again and again for different inputs, we can call this function.
In simple terms, a function is a block of code that runs only when it is called.
Syntax:
Example:
C++
// C++ Program to demonstrate working of a function #include <iostream> using namespace std; // Following function that takes two parameters 'x' and 'y' // as input and returns max of two input numbers int max( int x, int y) { if (x > y) return x; else return y; } // main function that doesn't receive any parameter and // returns integer int main() { int a = 10, b = 20; // Calling above function to find max of 'a' and 'b' int m = max(a, b); cout << "m is " << m; return 0; } |
Output
m is 20
Time complexity: O(1)
Space complexity: O(1)