Lab 4
Lab 4
Lab 4
Lab 4
Array
In this lab, we will learn about arrays, a fundamental data structure in C/C++ that allows us to
store multiple values of the same type in a single variable.
Instructions
1. Declaring and Initializing Arrays
An array is a collection of elements, all of the same type, stored in contiguous memory locations.
The syntax for declaring an array includes specifying the type, the array name, and the size.
dataType arrayName[size];
For example:
1 int arr [5];
• Regular for-loop:
1 for ( int i = 0; i < 5; i ++)
2 {
3 cout << arr [ i ] << " " ;
4 }
5. Multidimensional Arrays
C/C++ allows Multidimensional Arrays, commonly used for 2D Arrays (matrices) or 3D Arrays.
Bellow are some examples for 2D Array:
Exercises
Exercise 1. Find the smallest even and largest odd number
Write a program to find the smallest even and largest odd number in an array.
Input:
Output:
Example:
Input Output
5 2
1 2 3 4 5 5
Input:
Output:
Example:
Input Output
5 2 4
1 5 3 4 2
Input:
Output:
Example:
Input Output
5 1 2 3 4 5
3 1 2 5 4
Input:
• The number of elements in array - n; and the number k that need to be deleted.
Output:
• Notes: If the array has no elements left after deletion, output Empty.
Example:
Input Output
11 4 1 2 3 5
4 4 1 4 2 4 3 4 5 4 4
Input:
Output:
Example:
Input Output
5 5 4 3 2 1
1 2 3 4 5
Input:
Output:
Example:
Input Output
4 Not decreasing
1 2 3 4
Input:
Output:
• If there are many results with the same length, print any.
Example:
Input Output
6 3 4 8
5 3 4 8 6 7
Input:
Output:
Example:
Input Output
9 4 -1 2 1
-2 1 -3 4 -1 2 1 -5 4
Input:
Example:
Input Output
11 1: 5
3 2 1 1 1 2 1 1 3 2 2 2: 4
3: 2
Input:
• The number of elements in the first array - n, and the second array - m.
Output:
Example:
Input Output
2 2 1 2 3 4
1 3
2 4
Input:
• The matrix where each row is on a line and each element is separated by a space.
Output:
Example:
Input Output
2 2 2 5
2 4
5 6
Input:
• The matrix where each row is on a line and each element is separated by a space.
Output:
Example:
Input Output
2 2 1 2
3 1 3 4
4 2
Input:
• The matrix where each row is on a line and each element is separated by a space.
Output:
• Notes: If the matrix has no elements left after deletion, output Empty.
Example:
Input Output
2 2 2 1 2
1 2
3 4
Input:
• The matrix where each row is on a line and each element is separated by a space.
Output:
• Notes: If the matrix has no elements left after deletion, output Empty.
Example:
Input Output
2 2 2 1
1 2 3
3 4
Input:
• The matrix where each row is on a line and each element is separated by a space.
Output:
Example:
Input Output
2 2 3 1
1 2 4 2
3 4
The end.