ARRAY- EXAMPLES (C, C++, JAVA)

Arrays are a basic data structure in C/C++ programming, which allows storing multiple elements of the same type in a sequential block of memory. By working with arrays, you can effectively manage data collections, perform operations such as sorting, searching, and aggregating data. In this section, various examples are presented that illustrate working with arrays, from basic element manipulation to advanced algorithms.
Before you start solving the tasks, please read the lesson on the page: Arrays in Java or, if you are working in C or C++, the lesson on the page Arrays in C/C++.

1. Number of negative numbers

Write a program that first loads the number of elements of the sequence N(<=100), then N elements of the integer sequence A(<=100) and prints how many negative numbers are in it.​

2. The mean of the array

​Write a program that determines the arithmetic mean of positive values ​​of a real sequence A of N(<=100) elements.

3. Određivanje maksimuma i minimuma

​Determining the maximum and minimum from a sequence

4. Number of students with above average height

​Number of students with above average height

5. Weather station

​The weather station created a table of atmospheric pressure values ​​for N days of observation. Write a program that:
a) Loads an array of pressure values
b) Determines the maximum, minimum pressure and ordinal number of corresponding days in a row
c) Determine the mean value of the pressures during the observation

6. Different elements of arrays

Write a program that transforms a loaded array of integers so that each element of the array appears exactly once, preserving the order of the elements (the order of their first appearance).Input
In one standard input line, there are number of elements of the string N (0 <N≤10000), and then, in each of the N lines of the standard input, there is one member of the string.

Output
In each line of the standard output, one element of the transformed sequence is written.

Example
Input
10
1
3
5
3
1
5
7
2
3
5
Output
1
3
5
7
2

7. Road transport company

In the road transport company, during the processing of travel orders, two series were formed in one day:
sequence S[1 ... N] - the mileage of each of the N buses during the day i 
array P[1 ... N] - their fuel consumption
Write a program that:
a) Calculates the total distance traveled and the total consumption for all trips
b) calculates the average distance traveled per bus and the average fuel consumption per bus
c) determines the index of the bus with the maximum (minimum) mileage
d) determines the economy indicator for each bus - consumption in liters per 100 km

8. Removing elements from array

A number is undesirable in an array of integers if it has a total number of elements (eg, in an array of length 10, elements that divide the number 10 are undesirable, and up to 1, 2, 5 and 10).
 It is necessary to find all the unwanted elements in the sequence and remove them. After that, the number of elements can be promoted and some other elements can become undesirable. The process is repeated until a sequence without unwanted elements is obtained.
Write a program that, for a given sequence, determines the sum of the remaining elements, after removing the unwanted ones.
Input
From the standard input, the number n (1≤n≤50000) is entered, and then n
elements of the range from the range from 1 to 100.

Output
On the standard output, print an entire number that represents the sum of the remaining elemenates in a row,
after successive removal of all undesirable elements.

Example
Input
10
1
2
3
4
5
6
7
8
9
10
Output
24
First, the elements 1, 2, 5, and 10 that divide the length 10 are removed, and then the elements 3 and 6 that share the length
6 and eventually the element 4 is removed, so that the elements 7, 8, and 9 remain the sum of 24.
Instruction

9. Cyclic movement for one place

Write a program that loads a sequence of integers and then transforms it by cyclically shifting to assign parts of a sequence from position p to position q until two equal positions are entered. In doing so, perform a cyclic shift to the right if p <q, and the shift to the left is done if p> q.​Input
In a single line of the standard input, there are a number of elements of the sequence n (1 <n≤200), and then, in each of the following lines of the standard input, there is one member of the string. In the following lines two integers are entered, p and q (0≤p, q <n), separated by the void until the order in which the numbers are equal.
Output
In each line of the standard output, one element of the transformed sequence is written.
Example
Input
4 1 2 3 4 2 3 2 0 1 2 0 0
Output
2 1 4 3

4. Translating points in the plane

The coordinates of the N points in the plane are given. Translate points so that their focus is at a coordinate start.​Input
In the first line of the standard input there is a natural number n (1≤n≤100). The following n lines contain two real numbers, which represent the x and y coordinates of the points.
Output
At the standard output, show the coordinates of the points after the translation, for each point in one line of its x and y coordinate, the coordinates should be separated by one void and displayed in two decimal places.
Example
Input
3
0 0
1 0
2 3

Output
-1.00-1.00
0.00-1.00
1.00 2.00

11. Worker Master

Note: Task from the 1st round of qualifications, SEASON 2022/2023. Taken from takprog.petlja.org/osnovnaskola

After completing some work, master Pera received back n boxes of screws. The boxes were used and may contain different numbers of screws. Master Pera wants to use two boxes with the smallest number of screws. Help master Pera calculate the total number of screws in the two selected boxes.

Input
The first line of the standard input contains the total number of boxes n (2 ≤ n ≤ 30). In the following n lines, the number of screws in each box, k i (1 ≤ k i ≤ 100), is entered sequentially.

Output
Print a whole number representing the sum of screws in the two boxes with the smallest number of screws.

Example 1
Input
5
45
32
9
15
67
Output
24

Example 2
Input
7
764
455
721
231
138
97
333
Output
235

Example 3
Input
5
28
14
30
15
14
Output
28

12. Number of days of measured training

Note: Task from the 1st round of the SEASON 2022/2023 qualification. Adapted from takprog.petlja.org/osnovnaskola

​While preparing for upcoming competitions, an athlete measures the results achieved each day. Since they want to consistently improve their performance, they aim for each day's result to be better than the previous one (a higher number represents a better result). A training day is considered "good" if the result achieved on that day is strictly better than the previous day’s result and strictly worse than the next day's result. For the first day, it is sufficient that the result is strictly worse than the next day’s result, and for the last day, it should be strictly better than the previous day's result.

Write a program that calculates the number of good days.
Input: The first line of standard input contains the number of days nnn (3 ≤ nnn ≤ 100) during which the athlete trained, and the second line contains the results achieved by the athlete on each of these nnn days.
Output: Print the number of good days to standard output.
Example 1:
Input
:
6
100 120 130 110 140 150

Output:
4

Example 2:
Input:
6
10 20 30 40 50 60


Output:
6



13. Exchange the largest with the first element of the array

​Enter the number of elements of the array, and then the elements of that array. Determine the position of the maximum element in the sequence and exchange it with the first one in the sequence.
Example:
Input:
7
3 5 12 -3 4 2 8
​
Output
12 5 3 -3 4 2 8

Solution in C programming language

Enter the number of elements in the array, then enter all elements of the array

Determine the index of the maximum element in the array in the following way

  • Set the maximum to be the value of the first element in the array, then
  • Within a loop, using a for loop, check if the current element in the array might be greater than the current maximum
  • If it is, set that element as the maximum
  • Record the index at the moment of changing the maximum
  • After exiting the loop, the recorded index is the index of the maximum element in the given array

Perform the swap of elements at the first and previously determined maximum position

#include
#include
int main()
{
int n, pozMax, max;
scanf("%d", &n);
int A[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &A[i]);
}

// Determine max
max = A[0];
for (int i = 0; i < n; i++)
{
if (A[i] > max)
{
max = A[i];
pozMax = i;
}
}
// Swap
int temp = A[0];
A[0] = A[pozMax];
A[pozMax] = temp;

// Output after swap
for (int i = 0; i < n; i++)
{
printf("%d ", A[i]);
}

return 0;
}

14. Throwing out the maximum elements of an array

From the sequence A of length n(n<=100), form the sequence B obtained by removing every occurrence of the maximum member from the sequence A. Print the formed sequence B.
​
Example:
Input:
7
5 15 12 -13 15 2 8 15
​
Output
5 12 -13 2 8

Enter the number of elements in the array, and then enter all the elements of that array

Determine the maximum element in the array

  • Set a condition within a for loop to check if the current element in the array is equal to the maximum
  • If it is, copy that element from the array to a new array and increase the position in the new array by 1
#include
#include
int main()
{
int A[100], B[100], n, max, f = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &A[i]);
}

/* Determine the maximum in the array */
max = A[0];
for (int i = 0; i < n; i++)
{
if (A[i] >= max)
{
max = A[i];
}
}

/* Copying to a new array all elements except those equal to the maximum */
for (int i = 0; i < n; i++)
{
if (A[i] < max)
{
B[f] = A[i];
printf("%d\n", B[f]);
f++;
}
}
return 0;
}

15. Elements of a real sequence of numbers

Given a sequence of real numbers. Determine:
a) the ratio of the sum of the elements of the sequence, up to the first maximum, and the sum of the elements after the first maximum
b) the product of elements between the maximum and minimum elements
c) the arithmetic mean of the elements between the last maximum and "central". The assumption is that the number of elements is odd

16. Totals after division

NOTE: Problem from the 1st round of qualifications, season 2022/23. Retrieved from dms.rs/informatika-osnovne-skole/
Required Knowledge: Data types in C++, Operators in C++, Conditional Statements in C/C++, Loops, Arrays in C/C++
Optional: Maximum Sum of Subarray
A sequence of integers of length n is given. The sequence needs to be split into two parts. After splitting, determine how many pairs of numbers exist such that one number is from the left part and the other is from the right part, and their sum is an even number. Find the maximum number of such pairs that can be obtained by splitting the sequence.
Input: The input contains an integer n (2 ≤ n ≤ 50,000). Then, in the next line, the elements of the sequence a[i] (0 ≤ a[i] ≤ 100) are provided, separated by spaces.
Output: Print one integer representing the required value.
Example 1:
Input:
8
1 7 3 4 6 5 8 0

Output
7


Explanation: The maximum number of pairs is obtained by splitting the sequence into parts 1 7 3 4 6 and 5 8 0. The pairs are (1,5), (7,5), (3,5), (4,8), (4,0), (6,8), and (6,0).
Example 2:
Input:
7
1 9 3 11 12 4 8

Output
4

Solution: See task 12 on the website: Qualifications for district competitions

Multidimensional arrays-matrices

What are Multidimensional Arrays?
Multidimensional arrays are arrays that contain more than one dimension, meaning they can be used to represent multiple dimensions of data. The most common example of multidimensional arrays are two-dimensional arrays, which are often used to represent tables, matrices, or grids. Multidimensional arrays can have three, four, or more dimensions, depending on the complexity of the problem being solved.

Purpose of Multidimensional Arrays:
Representation of Tables and Matrices: Multidimensional arrays are ideal for working with tables of data, such as matrices in math or layouts in games.
​
Graphics Displays: Used to represent pixels in images, where each dimension can represent colors or layers.
Simulations and Models: Enable the creation of complex models and simulations, such as 3D graphics or simulations in scientific research.

Examples of Multidimensional Arrays

C++ Example:#include <iostream>

int main() {
 //
Declaration and initialization of a two-dimensional array
int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

//
Print matrix elements
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
std::cout << matrix[i][j] << " ";
        }
std::cout << std::endl;
    }

return 0;
}
In this Java example, matrix is ​​also a two-dimensional array with the same functionality as in the C++ example. Each array element is accessed using row and column indices.
​
Conclusion
Multidimensional arrays are a powerful tool for working with more complex data structures. By using multidimensional arrays, you can efficiently organize and manipulate data in multiple dimensions, which is useful in a variety of applications from scientific simulations to graphical display.
You can find more examples about two-dimensional arrays on the following page: Two dimensional array-matrix

FAQ Section for Arrays

​Frequently Asked Questions:


What is array indexing and how does it work?
  • ​Answer: Array indexing allows access to each element in the array using an index. Indexes in most programming languages, including Java and C++, start at 0. This means that the first element of an array has index 0, the second element has index 1, and so on. For example, in the C++ array int array[5], array[0] accesses the first element, while array[4] accesses the fifth element.


What happens if I try to access an index that is out of range of the array?
  • ​​Answer: Accessing an index outside the range of an array can cause an error in the program. In C++, this can lead to unpredictable results and errors, while in Java, accessing an index outside the range of an array (eg array[10] for a 5-element array) throws an ArrayIndexOutOfBoundsException. Always check that the index is in a valid range before accessing an array element.


How can I initialize an array with different values ​​at different indices?
  • Answer: You can initialize an array by directly assigning values ​​to specific indices after declaring the array. For example, in Java: int[] array = new int[5]; array[0] = 1; array[1] = 2;. In C++: int array[5] = {1, 2, 0, 0, 0}; or you can use a loop to set the value.

​What are common mistakes when working with arrays?
  • Answer: Some of the common mistakes include:
    Index Out of Range: Attempt to access indices that are less than 0 or greater than the size of the array minus 1.
    Inappropriate array size: The array may be too short for the data you want to store, which may lead to errors in the program.
    Forgetting to initialize an array: Accessing an array without initializing it can lead to unpredictable results.


How can I use multidimensional arrays?
  • Answer: Multidimensional arrays, like two-dimensional arrays, are used to represent data in multiple dimensions. For example, a two-dimensional array can be used to represent a table. In Java: int[][] matrix = {{1, 2}, {3, 4}};. In C++: int matrix[2][2] = {{1, 2}, {3, 4}};. Elements are accessed using two indexes, one for the row and one for the column.


How do I work with dynamic arrays?
  • Answer: In Java, dynamic arrays are typically used through classes such as ArrayList, which allow automatic resizing. In C++, you can use std::vector to dynamically add and remove elements. For example, in Java: ArrayList<Integer> list = new ArrayList<>(); list.add(1);. In C++: std::vector<int> vec; vec.push_back(1);.

What are the best practices for working with arrays?
  • Answer: Some of the best practices include:
    Bounds checking: Always check that indices are in a valid range before accessing array elements.
    Using loops to work with arrays: Use loops to iterate through arrays, which makes the code cleaner and easier to maintain.
    Array initialization: Always initialize an array before using it to avoid unpredictable results.

Collections in Java: Basics and Comparison with Arrays

Introduction to CollectionsCollections in Java are used to store, manage, and manipulate groups of objects. They provide a unified architecture for working with different types of collections, such as lists, sets, queues, and maps. This framework is highly versatile and allows developers to perform complex operations with ease.
Basics of CollectionsJava Collections Framework includes several key interfaces and classes that define various types of collections:
  • List: An ordered collection that allows duplicate elements. Common implementations include:
    • ArrayList: A resizable array implementation.
    • LinkedList: A doubly-linked list implementation.
    • Vector: A synchronized resizable array.
  • Set: A collection that does not allow duplicate elements. Common implementations include:
    • HashSet: A set based on a hash table.
    • LinkedHashSet: A hash table and linked list implementation with predictable iteration order.
    • TreeSet: A set based on a tree structure that provides sorted order.
  • Queue: A collection used to hold elements before processing. Common implementations include:
    • LinkedList: Implements both List and Queue interfaces.
    • PriorityQueue: A queue that orders elements based on their priority.
  • Map: A collection of key-value pairs, where each key maps to exactly one value. Common implementations include:
    • HashMap: A map based on a hash table.
    • LinkedHashMap: A hash table and linked list implementation with predictable iteration order.
    • TreeMap: A map based on a tree structure that provides sorted order.
Comparison with ArraysArrays and collections are both used to store data but differ in several key ways:
  • Size: Arrays have a fixed size, which must be defined at creation time. Collections can dynamically resize as elements are added or removed.
  • Functionality: Collections provide more advanced operations compared to arrays. They come with built-in methods for searching, sorting, and manipulating data, while arrays only offer basic operations.
  • Flexibility: Collections are generally more flexible than arrays. Operations such as adding, removing, and updating elements are more straightforward with collections.
Advantages and DisadvantagesAdvantages of Collections:
  • Dynamic Sizing: Collections can grow or shrink as needed, unlike arrays with a fixed size.
  • Rich API: Collections offer a rich set of methods for various operations, such as filtering, sorting, and searching.
  • Data Structure Variety: Collections include various data structures to meet different needs, such as linked lists, trees, and hash tables.
Disadvantages of Collections:
  • Overhead: Collections may introduce additional overhead in terms of memory and performance compared to arrays.
  • Complexity: The rich feature set of collections can add complexity to your code.
ConclusionWhile arrays are useful for fixed-size, simple storage needs, collections provide more powerful and flexible options for managing data. Understanding when to use each can help you write more efficient and maintainable code.

External Resources and Links

Related ResourcesHere are some valuable external resources to deepen your understanding of collections in Java:Books
  • "Java: The Complete Reference" by Herbert Schildt: A well-known book covering Java programming, including a thorough explanation of the Collections Framework.
  • "Effective Java" by Joshua Bloch: This book provides best practices and insights into using Java effectively, including a section on collections.
Online Courses