Skip to content

Commit

Permalink
Day 9: Array in Function (#205)
Browse files Browse the repository at this point in the history
* changes in day-09

* changes in day 9

* changes in day 11
  • Loading branch information
shaziaakhan authored Jun 11, 2024
1 parent d44ffb3 commit 55a893f
Show file tree
Hide file tree
Showing 2 changed files with 275 additions and 20 deletions.
182 changes: 172 additions & 10 deletions docs/day-09/array-in-function.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,179 @@ sidebar_label: "Array in Function"
slug: array-in-function-in-cpp
---

TASK:

1. What is an Array in Function in C++?
2. Explain the Syntax of an Array in Function in C++.
3. How to Declare and Define an Array in Function in C++?
4. C++ Array in Function Example
5. How to Pass an Array to a Function in C++?
6. How to Return an Array from a Function in C++?
## Arrays in C++ Functions

Add more...
![Function in CPP](../../static/img/day-09/array-in-function.png)

### 1. What are Arrays in Functions?

In C++, an array within a function is a collection of elements with the same data type, stored contiguously in memory. You can use arrays in functions in two ways:

* **Passing arrays as arguments:** Allow functions to operate on the elements of an existing array.
* **Declaring arrays within functions:** Create temporary arrays for specific function tasks.

### 2. Syntax of Arrays in Functions

**Passing Arrays as Arguments:**

There are three common methods:

* **By pointer:**
```c++
void myFunction(int *myArray, int size); // Function parameter
```
* **By sized array (deprecated):**
```c++
void myFunction(int myArray[10]); // Function parameter (deprecated)
```
* **By reference (C++11 and later):**
```c++
void myFunction(const int (&myArray)[10]); // Function parameter (C++11+)
```
**Declaring Arrays within Functions:**
```c++
void myFunction() {
int localArray[5]; // Array declared locally within the function
}
```

## 3. How to Declare and Define an Array in Function in C++?

### Declaring an Array in Function

When declaring an array in the function parameter list, you typically just declare it as a pointer, because arrays decay to pointers when passed to functions.

```cpp
void printArray(int arr[], int size);
```
### Defining a Function that Accepts an Array
Here's how you might define a function that takes an array as an argument:
```cpp
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
```


### 4. C++ Array in Function Example (Passing by Pointer)

```c++
#include <iostream>

void printArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}

int main() {
int myArray[] = {1, 2, 3, 4, 5};
int n = sizeof(myArray) / sizeof(myArray[0]); // Get array size
printArray(myArray, n); // Pass array and its size
return 0;
}
```
This code defines a `printArray` function that takes an integer pointer and the array size as arguments. It then iterates through the array and prints its elements.
## 5. How to Pass an Array to a Function in C++?
To pass an array to a function in C++, you can simply specify the array name (which decays to a pointer) and optionally the size of the array.
```cpp
#include <iostream>
void processArray(int arr[], int size) {
// Process array elements
for (int i = 0; i < size; i++) {
arr[i] *= 2; // Example processing: double each element
}
}
int main() {
int myArray[] = {1, 2, 3, 4, 5};
int size = sizeof(myArray) / sizeof(myArray[0]);
processArray(myArray, size);
// Print the processed array
for (int i = 0; i < size; i++) {
std::cout << myArray[i] << " ";
}
std::cout << std::endl;
return 0;
}
```

## 6. How to Return an Array from a Function in C++?

In C++, you cannot return arrays directly from functions. Instead, you can return a pointer to an array, or use other data structures like `std::vector` or `std::array` from the C++ Standard Library, which are more flexible and safer.

### Example using a pointer:

```cpp
#include <iostream>

int* createArray(int size) {
int* arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i + 1;
}
return arr;
}

int main() {
int size = 5;
int* myArray = createArray(size);

for (int i = 0; i < size; i++) {
std::cout << myArray[i] << " ";
}
std::cout << std::endl;

delete[] myArray; // Don't forget to free the allocated memory
return 0;
}
```
### Example using `std::vector`:
```cpp
#include <iostream>
#include <vector>
std::vector<int> createVector(int size) {
std::vector<int> vec(size);
for (int i = 0; i < size; i++) {
vec[i] = i + 1;
}
return vec;
}
int main() {
int size = 5;
std::vector<int> myVector = createVector(size);
for (int i = 0; i < size; i++) {
std::cout << myVector[i] << " ";
}
std::cout << std::endl;
return 0;
}
```

Using `std::vector` or `std::array` is generally preferred due to better safety, easier memory management, and more features compared to raw arrays.


**Note:** While sized arrays (like `void myFunction(int myArray[10])`) were used in the past, they are generally discouraged due to limitations and potential safety concerns. Prefer using pointers or references for better flexibility and clarity.


IMAGE FILE:
![Function in CPP](../../static/img/day-09/array-in-function.png)
113 changes: 103 additions & 10 deletions docs/day-11/reference-in-cpp.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,110 @@ description: "In this tutorial, we will learn about Reference in C++ programming
sidebar_label: "Reference"
slug: reference-in-cpp
---
## Reference in C++
![String in CPP](../../static/img/day-11/reference-in-cpp.png)

TASK:
## 1. What is a Reference in C++?

1. What is a Reference in C++?
2. Explain the Syntax of a Reference in C++.
3. How to Declare and Define a Reference in C++?
4. C++ Reference Example
5. How to Pass a Reference to a Function in C++?
6. How to Return a Reference from a Function in C++?
A reference in C++ is an alias for another variable. It allows you to create a second name for an existing variable, which you can use to access or modify the original variable. References are often used for parameter passing in functions to avoid copying large objects and for returning multiple values from a function.

## 2. Explain the Syntax of a Reference in C++.

The syntax for declaring a reference involves using the `&` symbol. You place the `&` symbol between the data type and the reference variable name.

```cpp
dataType &referenceName = variableName;
```

## 3. How to Declare and Define a Reference in C++?

### Declaring and Defining a Reference

When you declare and define a reference, you must initialize it at the same time. References cannot be left uninitialized.

```cpp
int original = 10;
int &ref = original; // 'ref' is a reference to 'original'
```

## 4. C++ Reference Example

Here is a simple example demonstrating the use of a reference:

```cpp
#include <iostream>

int main() {
int original = 10;
int &ref = original;

std::cout << "Original: " << original << std::endl; // Outputs: 10
std::cout << "Reference: " << ref << std::endl; // Outputs: 10

ref = 20;
std::cout << "After modifying reference:" << std::endl;
std::cout << "Original: " << original << std::endl; // Outputs: 20
std::cout << "Reference: " << ref << std::endl; // Outputs: 20

return 0;
}
```

## 5. How to Pass a Reference to a Function in C++?

To pass a reference to a function, you use the same `&` syntax in the function parameter list. This allows the function to modify the original variable.

```cpp
#include <iostream>

void increment(int &num) {
num++;
}

int main() {
int value = 5;
increment(value);
std::cout << "Value after increment: " << value << std::endl; // Outputs: 6
return 0;
}
```
## 6. How to Return a Reference from a Function in C++?
You can return a reference from a function, which can be useful for various reasons, such as to modify the returned value or to avoid copying large objects. However, you must ensure that the object being referred to still exists when the reference is used.
### Example of Returning a Reference from a Function
```cpp
#include <iostream>
int& getElement(int arr[], int index) {
return arr[index]; // Returning a reference to the array element
}
int main() {
int myArray[5] = {1, 2, 3, 4, 5};
int &element = getElement(myArray, 2); // Get reference to the third element
std::cout << "Original element: " << element << std::endl; // Outputs: 3
element = 10; // Modify the element through the reference
std::cout << "Modified element: " << myArray[2] << std::endl; // Outputs: 10
return 0;
}
```

### Important Considerations

- **Lifetime of the referred object**: Ensure that the object whose reference is returned is still alive when the reference is used. Returning references to local variables within a function is dangerous because the local variables will be destroyed when the function scope ends.
- **Const references**: Use const references when you don't need to modify the object, which helps in avoiding accidental changes.

```cpp
const int& getElement(const int arr[], int index) {
return arr[index];
}
```
By using references, you can efficiently manage large data and enhance performance by avoiding unnecessary copying of objects.
Add more...
IMAGE FILE:
![String in CPP](../../static/img/day-11/reference-in-cpp.png)

0 comments on commit 55a893f

Please sign in to comment.