Clasa a X-a · high schoolCitește în română
Grade 10 algorithmsClasa a X-a
The grade 10 part of the collection, chapter by chapter. Read the idea, run the code against the examples and track what you've learned.
- 67algorithms
- 6chapters
- 1grade
67 algorithms
Grade 10Clasa a X-a
0%0%
Subprograms (functions)
Subprograme (funcții) · 11 algorithms
- GCD and LCM functionsFuncție cmmdc și cmmmcThe function cmmdc(a, b) applies Euclid's algorithm by division: while b is not 0, the pair (a, b) becomes (b, a % b). The function cmmmc(a, b)…
- Primality functionFuncție de primalitateWe write the function estePrim(x) once, returning true if x is prime, and call it for every number read. The function looks for a divisor d between…
- Function with an array parameter (the maximum)Funcție cu vector ca parametru (maximul)An array is passed to a function together with the number of elements: int maxim(int v[], int n). The function actually receives the address of the…
- Function returning the reverse of a numberFuncție care întoarce oglinditulThe function oglindit(x) builds the number with the digits of x in reverse order and returns it. With its help, the function palindrom(x) fits on…
- Function for the sum of digitsFuncție pentru suma cifrelorThe function sumaCifre(x) receives the number by value (it works on a copy, so the x in main is not destroyed) and returns the sum of its digits. In…
- Swapping by referenceInterschimbare prin referințăWe compare two functions that try to swap the values of two variables. schimbaValoare(int x, int y) receives copies, so the changes are lost when…
- Minimum and maximum returned by referenceMinim și maxim întoarse prin referințăA function can return a single value with return. When we need several results, we make them reference parameters: void minMax(int v[], int n, int…
- Amicable numbersNumere prieteneTwo numbers a and b are amicable if the sum of the proper divisors of a (the divisors smaller than a) is b and the sum of the proper divisors of b…
- Super-prime numbersNumere superprimeA number is super-prime if all its prefixes are prime. For example 239 is super-prime: 2, 23 and 239 are prime. The function estePrim(x) is reused…
- Palindromes in a rangePalindroame dintr-un intervalA problem solved by splitting it into small functions: oglindit(x) returns the reverse of x, palindrom(x) uses the first one, and main only walks…
- Global and local variablesVariabile globale și variabile localeA global variable (declared outside the functions) is visible from the whole program, starts automatically at 0 and keeps its value between calls. A…
0%
Two-dimensional arrays (matrices)
Tablouri bidimensionale (matrice) · 15 algorithms
- Bordering a matrixBordarea matriceiBordering a matrix means adding a new row and/or column on its edge. Here we add column m + 1, holding the sum of each row, and row n + 1, holding…
- Reading and printing a matrixCitirea și afișarea unei matriceA matrix with n rows and m columns is declared as int a[101][101] and traversed with two nested for loops: the first picks the row i, the second the…
- Main diagonal and secondary diagonalDiagonala principală și diagonala secundarăIn an n x n square matrix indexed from 1, the elements on the main diagonal have i == j, and those on the secondary diagonal have i + j == n + 1. We…
- Row with the maximum sumLinia cu suma maximăWe compute the sum of every row and compare it with the largest sum found so far. The maximum starts from the sum of the first row (not from 0,…
- Generating a serpentine (zigzag) matrixGenerarea matricei în serpentinăWe fill the matrix with the numbers 1, 2, ..., n * m in a zigzag: odd rows from left to right, even rows from right to left. A counter val grows…
- Checking a symmetric matrixVerificarea matricei simetriceA square matrix is symmetric about the main diagonal if a[i][j] == a[j][i] for every i and j (it equals its transpose). It is enough to check the…
- Spiral traversalParcurgerea în spiralăWe keep four borders: top, bottom, left, right. On every lap we walk the top row (to the right), the right column (down), the bottom row (to the…
- Product of two matricesProdusul a două matriceThe product exists only if the number of columns of A equals the number of rows of B. For A (n x m) and B (m x p) the result C has n x p elements,…
- Saddle pointPunct șaA saddle point is an element that is the minimum of its row and the maximum of its column. For every element a[i][j] we check the two conditions…
- Rotating a matrix by 90 degreesRotirea unei matrice cu 90 de gradeWhen rotating clockwise, the first column read from bottom to top becomes the first row. The result matrix b has m rows and n columns, and the…
- Deleting a row and a columnȘtergerea unei linii și a unei coloaneAs with arrays, deleting means moving elements over the deleted one. For row k, every row i from k to n - 1 receives row i + 1, then n decreases by…
- Row sums and column sumsSuma pe linii și pe coloaneFor the sum of row i we keep i fixed and move j from 1 to m. For the sum of column j we do the opposite: j fixed in the outer loop, i varying in the…
- Generating a chessboardGenerarea tablei de șahOn a chessboard, the colour of a square depends only on the parity of i + j: squares with an even i + j have one colour (1), those with an odd i + j…
- Transpose of a matrixTranspusa unei matriceThe transpose of the matrix a (n rows, m columns) has m rows and n columns: row i of the transpose is column i of a, i.e. t[j][i] = a[i][j]. No…
- The four zones of a square matrixCele patru zone ale matricei pătraticeThe two diagonals split a square matrix into four zones (without the elements on the diagonals). With indices from 1: North: i < j and i + j < n + 1…
0%
Character strings
Șiruri de caractere · 16 algorithms
- The longest wordCel mai lung cuvântWe split the sentence into words with strtok and keep the longest word in a separate string, copying it with strcpy (we cannot write celMaiLung = p,…
- Caesar cipherCifrul lui CezarEvery letter is replaced by the letter k positions further in the alphabet, circularly (after 'z' comes 'a'). We turn the letter into its position…
- Palindrome words in a sentenceCuvintele palindrom dintr-o frazăWe combine two things learned before: strtok splits the sentence into words, and the function estePalindrom(p) checks a word with two indices moving…
- Removing the vowelsEliminarea vocalelorWe delete the vowels in the original string itself, with two indices: i reads every character, k shows where the next kept character is written.…
- Extracting the numbers from a textExtragerea numerelor dintr-un textWe walk the text; when we meet a digit, we build the number as in grade 9 (nr = nr * 10 + (s[i] - '0')) while digits follow. The expression s[i] -…
- Letter frequencyFrecvența literelorWe count how many times each letter appears, without distinguishing uppercase from lowercase: tolower(c) - 'a' gives the letter's position in the…
- Splitting into words with strtokÎmpărțirea în cuvinte cu strtokstrtok(s, separators) returns the first word of s; the following calls are made with NULL instead of s and return the other words one by one, until…
- Replacing one word with anotherÎnlocuirea unui cuvânt cu altulA text and two words, old and new, are read (each on its own line). We build the result in a new string: spaces are copied as they are, and every…
- Converting to uppercase and lowercaseTransformarea în majuscule și minusculeIn the ASCII table the uppercase letters 'A'..'Z' and the lowercase 'a'..'z' are a constant distance apart: 'a' - 'A' = 32. A lowercase letter…
- Counting the wordsNumărarea cuvintelorWithout strtok: a word starts where a non-space character follows a space (or sits at the very beginning of the string). We count these…
- Counting the vowelsNumărarea vocalelorFor every character we check whether it appears in the string "aeiouAEIOU" with the function strchr: strchr(vowels, c) returns the address of the…
- Operations with std::stringOperații cu std::stringThe string class from <string> manages its own memory: it is assigned with =, concatenated with +, compared with == and <. getline(cin, s) reads the…
- Walking a string and its lengthParcurgerea unui șir și lungimea luiA C-style string is a char array terminated by the null character '\0'. cin.getline(s, 256) reads the whole line, spaces included (cin >> s would…
- Sorting words alphabeticallySortarea alfabetică a cuvintelorWe split the sentence into words with strtok and copy them into a character matrix cuv[100][31] (every row is a string). We sort with bubble sort;…
- Checking a palindrome stringVerificarea unui șir palindromFirst we keep only the letters, turned into lowercase (so 'Ele fac cafele' becomes 'elefaccafele'). Then we use two indices: st starts at the…
- Checking anagramsVerificarea anagramelorTwo words are anagrams if they have the same letters, the same number of times, in a different order (for example 'roma' and 'amor'). We use a…
0%
The struct type
Tipul struct · 5 algorithms
- Comparing calendar datesCompararea datelor calendaristiceA calendar date has three fields: day, month, year. Two dates are compared first by year, with equal years by month, and with equal months by day;…
- Adding durations (hours, minutes, seconds)Adunarea duratelor (ore, minute, secunde)A duration is kept in a structure with three fields. To add easily, we turn the duration into seconds (h * 3600 + m * 60 + s), add the numbers and…
- Students sorted by average and nameElevi sortați după medie și numeThe struct type groups data of different types under a single name: struct Elev { char nume[31]; double medie; }. A field is accessed with a dot…
- Operations with fractionsOperații cu fracțiiA fraction has two fields, the numerator a and the denominator b, so we represent it with struct Fractie { long long a, b; }. A function can return…
- Points in the planePuncte în planA point has the coordinates x and y: struct Punct { int x, y; }. The distance between two points is sqrt((x1 - x2)^2 + (y1 - y2)^2). For comparisons…
0%
Recursion
Recursivitate · 12 algorithms
- Printing the digits in order, recursivelyAfișarea cifrelor în ordine, recursivWhere we print relative to the recursive call matters. In inOrdine we print AFTER the recursive call: first the call for n / 10 finishes (printing…
- Recursive GCDCmmdc recursivEuclid's algorithm written recursively: gcd(a, 0) = a, and gcd(a, b) = gcd(b, a % b). The recursive call is the last operation in the function (tail…
- Converting to base 2, recursivelyConversia în baza 2, recursivWhen converting by repeated division by 2, the remainders come out in the reverse of the order they must be written in. Recursion solves this by…
- Recursive factorialFactorial recursivThe mathematical definition is already recursive: 0! = 1 and n! = n * (n - 1)!. The function has a stopping condition (n == 0) and a recursive call…
- Recursive FibonacciFibonacci recursivThe Fibonacci sequence: F(0) = 0, F(1) = 1, F(n) = F(n - 1) + F(n - 2). The direct translation has two recursive calls, so the call tree almost…
- The Ackermann functionFuncția AckermannThe Ackermann function has two arguments: A(0, n) = n + 1; A(m, 0) = A(m - 1, 1); A(m, n) = A(m - 1, A(m, n - 1)). Its values grow extremely fast…
- The Manna-Pnueli functionFuncția Manna-PnueliThe function is defined as: f(x) = x - 1 if x >= 12, otherwise f(x) = f(f(x + 2)). The inner call f(x + 2) is computed first, and its result becomes…
- Reversing a string, recursivelyInversarea unui șir de caractere, recursivThe function inverseaza(s, i) handles the characters from position i to the end. If s[i] is not '\0', it first calls itself for the rest of the…
- Number of occurrences in an array, recursivelyNumărul de apariții într-un vector, recursivThe number of occurrences of x among the first n elements is the number of occurrences among the first n - 1 elements, plus 1 if the last element…
- Recursive palindrome checkPalindrom recursivA word is a palindrome if its first and last characters are equal and what remains between them is also a palindrome. The function palindrom(s, st,…
- Power of a number, recursivelyPuterea unui număr, recursivThe direct version uses a^n = a * a^(n - 1) and makes n calls. The fast version halves the exponent: if n is even, a^n = (a^(n/2))^2, otherwise a^n…
- Sum of digits, recursivelySuma cifrelor, recursivThe digit sum of n is its last digit (n % 10) plus the digit sum of the number left after cutting it off (n / 10). Stop: a one-digit number (n < 10)…
0%
Divide and conquer
Divide et impera · 8 algorithms
- Recursive binary searchCăutare binară recursivăThe array is sorted in increasing order. We compare x with the middle element: if they are equal we are done; if x is smaller, we search only the…
- GCD of an array's elements with divide and conquerCmmdc-ul elementelor unui vector prin divide et imperaThe GCD of a portion is the GCD of the left half's GCD and the right half's GCD, because gcd(a, b, c, d) = gcd(gcd(a, b), gcd(c, d)). The base case:…
- Maximum of an array with divide and conquerMaximul unui vector prin divide et imperaThe three stages of the method: we split the portion [st, dr] into two halves at the middle m = (st + dr) / 2 (divide); we find the maximum of each…
- Counting the even elements with divide and conquerNumărul elementelor pare prin divide et imperaThe same pattern as for the sum: the result for the portion [st, dr] is the sum of the results of the two halves. Only the base case differs: a…
- Merge sortSortarea prin interclasare (Merge Sort)We split the array into two halves, sort each half recursively, then merge them: we always compare the first remaining elements of the two halves…
- Quick sortSortarea rapidă (Quick Sort)We pick a pivot (here the middle element) and rearrange the portion so that values <= pivot end up on the left and values >= pivot on the right:…
- Sum of the elements with divide and conquerSuma elementelor prin divide et imperaThe sum of the portion [st, dr] is the sum of the left half [st, m] plus the sum of the right half [m + 1, dr]. A portion with a single element has…
- Towers of HanoiTurnurile din HanoiThere are n disks on rod A, in decreasing order of size, and we want to move them to rod C, using rod B, without ever placing a large disk on a…