Resume work on K&R book

This commit is contained in:
t0xa 2026-02-06 20:23:03 +03:00
parent b104a6f6cf
commit 4e9c86da84
63 changed files with 20 additions and 1408 deletions

Binary file not shown.

View file

@ -1,40 +0,0 @@
#include <stdbool.h>
#include <stdio.h>
#define N 7
#define FN 40
void print_bool_array(bool *x, size_t size) {
printf("Array started with size == %zu\n", size);
for (int i = 0; i < size; i++) {
if (i == size - 1) {
printf("%d\nArray ended\n", x[i]);
} else {
printf("%d, ", x[i]);
}
}
}
void print_int_array(int *x, size_t size) {
printf("Array started with size == %zu\n", size);
for (int i = 0; i < size; i++) {
if (i == size - 1) {
printf("%d\nArray ended\n", x[i]);
} else {
printf("%d, ", x[i]);
}
}
}
void create_fibonacci_numbers() {
int fin_numbers[FN] = {1, 1};
for (int i = 2; i < FN; i++) {
fin_numbers[i] = fin_numbers[i - 1] + fin_numbers[i - 2];
}
print_int_array(fin_numbers, FN);
}
int main() {
bool weekend[N] = {[0] = true, [N - 1] = true};
print_bool_array(weekend, N);
create_fibonacci_numbers();
}

View file

@ -1,38 +0,0 @@
/**
* @brief Itreation through array test
*/
#include <stdio.h>
void temps() {
int total_temp;
const int temperature_readings[24][30] = {
{25, 31, 19, 27, 22, 34, 28, 20, 33, 24, 29, 21, 26, 32, 23,
30, 35, 18, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47},
{41, 28, 34, 22, 36, 19, 31, 26, 43, 30, 24, 37, 20, 33, 27,
35, 23, 29, 32, 25, 38, 21, 40, 42, 44, 45, 46, 47, 48, 49},
{18, 33, 27, 39, 24, 43, 31, 35, 20, 26, 29, 22, 36, 28, 34,
21, 25, 30, 32, 37, 40, 41, 42, 43, 44, 45, 46, 47, 48, 19},
{35, 22, 29, 41, 26, 31, 20, 33, 27, 24, 36, 28, 34, 21, 25,
30, 32, 37, 40, 41, 42, 43, 44, 45, 46, 47, 48, 19, 23, 38},
{27, 34, 21, 25, 30, 32, 37, 40, 41, 42, 43, 44, 45, 46, 47,
48, 19, 23, 38, 35, 22, 29, 41, 26, 31, 20, 33, 24, 36, 28},
{40, 41, 42, 43, 44, 45, 46, 47, 48, 19, 23, 38, 35, 22, 29,
41, 26, 31, 20, 33, 27, 24, 36, 28, 34, 21, 25, 30, 32, 37},
{46, 47, 48, 19, 23, 38, 35, 22, 29, 41, 26, 31, 20, 33, 27,
24, 36, 28, 34, 21, 25, 30, 32, 37, 40, 41, 42, 43, 44, 45},
{19, 23, 38, 35, 22, 29, 41, 26, 31, 20, 33, 27, 24, 36, 28,
34, 21, 25, 30, 32, 37, 40, 41, 42, 43, 44, 45, 46, 47, 48},
{38, 35, 22, 29, 41, 26, 31, 20, 33, 27, 24, 36, 28, 34, 21,
25, 30, 32, 37, 40, 41, 42, 43, 44, 45, 46, 47, 48, 19, 23},
{22, 29, 41, 26, 31, 20, 33, 27, 24, 36, 28, 34, 21, 25, 30,
32, 37, 40, 41, 42, 43, 44, 45, 46, 47, 48, 19, 23, 38, 35}};
for (int i = 0; i < 24; i++) {
printf("Row: %d\n", i);
for (int j = 0; j < 30; j++) {
printf("\tCell %d,value: %d\n", j, temperature_readings[i][j]);
total_temp += temperature_readings[i][j];
}
}
float average_temp = (float)total_temp / (24 * 30);
printf("Average temp: %.2f", average_temp);
}
int main() { temps(); }

View file

@ -1,32 +0,0 @@
#include <stdbool.h>
#include <stdio.h>
int main() {
bool digit_seen[10] = {false};
int seen_digits[10];
int iterator = 0;
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
while (n > 0) {
digit = n % 10;
if (digit_seen[digit]) {
seen_digits[iterator] = digit;
iterator += 1;
}
digit_seen[digit] = true;
n /= 10;
}
if (iterator > 0) {
printf("Repeated digit(s): ");
for (int i = iterator - 1; i >= 0; i--) {
printf("%d ", seen_digits[i]);
}
printf("\n");
} else {
printf("No repeated digit\n");
}
}

View file

@ -1,24 +0,0 @@
#include <stdbool.h>
#include <stdio.h>
int main() {
int occurence_counter[2][10] = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
long n;
int digit;
printf("Enter a number: ");
scanf("%ld", &n);
while (n > 0) {
digit = n % 10;
occurence_counter[1][digit] += 1;
n /= 10;
}
printf("Digit:\t\t");
for (int i = 0; i < 10; i++) {
printf("%d ", occurence_counter[0][i]);
}
printf("\nOccurrences:\t");
for (int i = 0; i < 10; i++) {
printf("%d ", occurence_counter[1][i]);
}
}

View file

@ -1,45 +0,0 @@
#include <ctype.h>
#include <stdio.h>
#define MAX_STRING_SIZE 100
int main() {
char input[MAX_STRING_SIZE] = {};
char filtered[MAX_STRING_SIZE] = {};
int last_real_char = 0;
printf("Enter message: ");
fgets(input, MAX_STRING_SIZE, stdin);
for (int i = 0; i < MAX_STRING_SIZE - 1; i++) {
char current_char = toupper(input[i]);
if (current_char != 0) {
last_real_char = i;
}
switch (current_char) {
case 'A':
filtered[i] = '4';
break;
case 'B':
filtered[i] = '8';
break;
case 'E':
filtered[i] = '3';
break;
case 'I':
filtered[i] = '1';
break;
case 'O':
filtered[i] = '0';
break;
case 'S':
filtered[i] = '5';
break;
default:
filtered[i] = current_char;
break;
}
}
for (int i = last_real_char; i < last_real_char + 10; i++) {
filtered[i] = '!';
}
printf("Entered message: %s", filtered);
}

View file

@ -1,45 +0,0 @@
#include <stddef.h>
#include <stdio.h>
#define N 10
/**
* @brief Function for printing the array elements
*
* @param x - pointer to array
* @param size - size of an array
*/
void print_bool_array(int *x, size_t size) {
printf("Array started with size == %zu\n", size);
for (int i = 0; i < size; i++) {
if (i == size - 1) {
printf("%d\nArray ended\n", x[i]);
} else {
printf("%d, ", x[i]);
}
}
}
int main() {
/* Array initialization */
int a[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
print_bool_array(a, N);
/* Partial array initialization */
int b[N] = {1, 23, 4};
print_bool_array(b, N);
/* Initialization without size */
int c[] = {10000000, 3, 4};
/* In print beneath we are calculating size of an array by taking the whole
* memory of array and dividing it by size of an element in it
*/
printf("%lu : %lu\n", sizeof(c), sizeof(c[0]));
print_bool_array(c, sizeof(c) / sizeof(c[0]));
/* Designated initializers */
int d[N] = {[2] = 15, [9] = 10};
print_bool_array(d, N);
/* Designated initializers without fixed size */
int e[] = {[2] = 15, [9] = 10, [154] = 1};
print_bool_array(e, sizeof(e) / sizeof(e[0]));
}

View file

@ -1,22 +0,0 @@
#include <stdio.h>
typedef int Kekus;
int main() {
unsigned kek;
kek = -9;
printf("%du\n", kek);
char ch1 = 'a';
char ch2 = 'A';
char ch3 = '0';
char ch4 = ' ';
printf("%c : %d\n", ch1, ch1);
printf("%c : %d\n", ch2, ch2);
printf("%c : %d\n", ch3, ch3);
printf("%c : %d\n", ch4, ch4);
Kekus pips = 192;
printf("%d\n", pips);
}

View file

@ -1,59 +0,0 @@
#include <stdio.h>
void undefined_subexpression() {
int b, c;
int a = 5;
c = (b = a + 2) - (a = 1);
printf("%d", c);
}
void comparison_unexpected() {
int i, j, k;
i = 10;
j = 2;
k = 0;
// This is equivalent of (i < j) < k because it is < is left-associated
// operator
printf("\n%d", i < j < k);
}
void switch_playground() {
int grade = 1;
switch (grade) {
/* case 0: */
/* printf("Failint"); */
/* break; */
/* case 1: */
/* printf("Poor"); */
/* break; */
/* case 2: */
/* printf("Average"); */
/* break; */
/* case 3: */
/* printf("Good"); */
/* break; */
/* case 4: */
/* printf("Excelent"); */
/* break; */
/* default: */
/* printf("Illegal grade"); */
/* break; */
/* } */
case 0: case 1: case 2: case 3: case 4:
printf("Allowed grades");
break;
default:
printf("Illegal grade");
break;
}
}
int main() {
int i = 5;
float k = 1.1;
float j = 10 * i + k;
printf("%f\n", j);
undefined_subexpression();
comparison_unexpected();
printf("\n");
switch_playground();
}

View file

@ -1,7 +0,0 @@
#include <stdio.h>
int main(void) {
printf("Privet Sashka kak dela");
return 0;
}

View file

@ -1,14 +0,0 @@
# Шаги запуска программы
Preprocessing -> Compiling -> Linking
## Preprocessing
Первый шаг - команда попадает сюда. Тут препроцессор выполняет команды, которые начинаются с `#`. These commands are called **Directives**
## Compiling
After Preprocessing app goes to compiler where app is being translated into machine instructions (object code)
## Linking
Linker combines object code from step 2 with additional code needed for final executable. This code includes library functions
P.S.: *Сори за микс языков, лень было переключаться в процессе*
sdfaksdhfk

View file

@ -1,3 +0,0 @@
#include <stdio.h>
int main(void) { printf("hello, world\n"); }

View file

@ -1,13 +0,0 @@
#include <stdio.h>
int main(void) {
float float_var_1, float_var_2, float_var_3;
int int_var;
printf("%f\n", float_var_1);
printf("%f\n", float_var_2);
printf("%f\n", float_var_3);
printf("%d", int_var);
int _100_bottles;
int one____hundred_bottles;
int bottles_;
}

View file

@ -1,108 +0,0 @@
#include <math.h>
#include <stdio.h>
float calculate_volume(void) {
float radius;
printf("Hello from calculator\n");
printf("Please, enter the radius of circle in meters: ");
scanf("%f", &radius);
float division = 4.0 / 3.0;
float volume = division * M_PI * radius * radius * radius;
return volume;
}
float tax_calculator(void) {
float rubles, cents;
printf("Please, enter the rubles amount: ");
scanf("%f", &rubles);
printf("Please, enter the cents amount: ");
scanf("%f", &cents);
float result = (rubles + (cents / 100)) * 1.05;
return result;
}
void change_calculator(void) {
int rubles;
printf("Please, enter the rubles amount: ");
scanf("%d", &rubles);
/* In Russia, we have following bills:
* 5000 rubles
* 2000 rubles
* 1000 rubles
* 500 rubles
* 200 rubles
* 100 rubles
* 50 rubles
* 10 rubles
* 1 ruble - we actually does not have 1 ruble bill, but for the sake of
* project we have
*/
// Calculate for 5000
int _5k_bills = rubles / 5000;
// Remove this amount from total
rubles = rubles - _5k_bills * 5000;
// Calculate for 2000 for remeaning
int _2k_bills = rubles / 2000;
// Remove this amount from total
rubles = rubles - _2k_bills * 2000;
// Calculate for 1000 for remeaning
int _1k_bills = rubles / 1000;
// Remove this amount from total
rubles = rubles - _1k_bills * 1000;
// Calculate for 500 for remeaning
int _500_bills = rubles / 500;
// Remove this amount from total
rubles = rubles - _500_bills * 500;
// Calculate for 200 for remeaning
int _200_bills = rubles / 200;
// Remove this amount from total
rubles = rubles - _200_bills * 200;
// Calculate for 100 for remeaning
int _100_bills = rubles / 100;
// Remove this amount from total
rubles = rubles - _100_bills * 100;
// Calculate for 50 for remeaning
int _50_bills = rubles / 50;
// Remove this amount from total
rubles = rubles - _50_bills * 50;
// Calculate for 10 for remeaning
int _10_bills = rubles / 10;
// Remove this amount from total
rubles = rubles - _10_bills * 10;
// Print result
printf("5000 bills\t%d\n", _5k_bills);
printf("2000 bills\t%d\n", _2k_bills);
printf("1000 bills\t%d\n", _1k_bills);
printf("500 bills\t%d\n", _500_bills);
printf("200 bills\t%d\n", _200_bills);
printf("100 bills\t%d\n", _100_bills);
printf("50 bills\t%d\n", _50_bills);
printf("10 bills\t%d\n", _10_bills);
printf("1 bills\t\t%d\n", rubles);
}
void load_calculator(void) {
float loan, interest_rate, monthly_payment;
loan = 20000.00;
interest_rate = 6.0;
monthly_payment = 386.66;
float monthly_interest_rate = (interest_rate / 100) / 12;
loan = loan + (loan * monthly_interest_rate) - monthly_payment;
printf("LN\t%.2f\n", loan);
loan = loan + (loan * monthly_interest_rate) - monthly_payment;
printf("LN\t%.2f\n", loan);
loan = loan + (loan * monthly_interest_rate) - monthly_payment;
printf("LN\t%.2f\n", loan);
}
int main() {
/* float volume = calculate_volume(); */
/* printf("%f", volume); */
/* float tax = tax_calculator(); */
/* printf("%.2f", tax); */
/* change_calculator(); */
load_calculator();
}

View file

@ -1,15 +0,0 @@
#include <stdio.h>
void goto_check() {
int d, n;
for (d = 2; d < n; d++) {
if (n % d == 0) {
goto done;
}
}
done:
if (d < n)
printf("%d is divisable by %d\n", d, n);
else
printf("%d is prime", d);
}
int main() { goto_check(); }

View file

@ -1,38 +0,0 @@
#include <stdio.h>
#define ARRAY_SIZE 10
void print_array(int a[], int array_size) {
printf("[");
int *p;
for (p = a; p < a + array_size; p++) {
if (p == &a[array_size - 1]) {
printf("%d", *p);
} else {
printf("%d, ", *p);
}
}
printf("]\n");
}
int main() {
int a[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7, 80, 90, 100};
print_array(a, ARRAY_SIZE);
printf("*a:\t%d\n", *a);
int *ap1 = &a[1];
*ap1++ = 99;
printf("Executing *ap1++:\n");
print_array(a, ARRAY_SIZE);
printf("*ap1 after execution:\n");
printf("%d\n", *ap1);
int *ap2 = &a[2];
*(ap2)++ = 88;
printf("Executing *(ap2)++:\n");
print_array(a, ARRAY_SIZE);
printf("*ap2 after execution:\n");
printf("%d\n", *ap2);
int *ap3 = &a[3];
*++ap3 = 77;
printf("Executing *++ap3:\n");
print_array(a, ARRAY_SIZE);
printf("*ap3 after execution:\n");
printf("%d\n", *ap3);
}

View file

@ -1,22 +0,0 @@
#include <stdio.h>
/**
* @brief Variable swapping exercide
*/
void swap(int *p, int *q) {
printf("*p: %d; p = %p\n", *p, p);
printf("*q: %d; q = %p\n", *q, q);
int x = *p;
int y = *q;
*p = y;
*q = x;
}
int main() {
int a, b;
a = 4;
b = 5;
printf("a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("a = %d, b = %d", a, b);
}

View file

@ -1,35 +0,0 @@
#include <stdio.h>
/* Splitting seconds into hh:mm:ss */
void split_time(long total_sec, int *hr, int *min, int *sec) {
int f_h, f_m, f_s;
f_h = total_sec / 3600;
printf("hours: %d\n", f_h);
total_sec = total_sec - f_h * 3600;
f_m = total_sec / 60;
printf("minutes: %d\n", f_m);
total_sec = total_sec - f_m * 60;
printf("seconds: %ld\n", total_sec);
*hr = f_h;
*min = f_m;
*sec = total_sec;
}
void split_time_otimized(long total_sec, int *hr, int *min, int *sec) {
*hr = (int)(total_sec / 3600);
*min = (int)((total_sec % 3600) / 60);
*sec = (int)(total_sec % 60);
}
int main() {
long total_sec = 5123;
int hours, minutes, seconds;
hours = 0;
minutes = 0;
seconds = 0;
printf("BEFORE: %d:%d:%d\n", hours, minutes, seconds);
/* split_time(total_sec, &hours, &minutes, &seconds); */
split_time_otimized(total_sec, &hours, &minutes, &seconds);
printf("AFTER: %d:%d:%d\n", hours, minutes, seconds);
}

View file

@ -1,43 +0,0 @@
/* Finding two largest values in array */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_RANDOM_VALUE 1000
#define ARRAY_SIZE 10
void find_two_largest(int a[], int n, int *largest, int *second_largest) {
for (int i = 0; i < n; i++) {
if (a[i] > *largest) {
*second_largest = *largest;
*largest = a[i];
} else if (a[i] < *largest && a[i] > *second_largest) {
*second_largest = a[i];
}
}
}
int main() {
int random_numbers_array[ARRAY_SIZE];
int largest = 0;
int second_largest = 0;
// Generate random numbers
srand(time(NULL));
for (int i = 0; i < ARRAY_SIZE; i++) {
random_numbers_array[i] = rand() % MAX_RANDOM_VALUE + 1;
}
// Print array
printf("[");
for (int i = 0; i < ARRAY_SIZE; i++) {
if (i == ARRAY_SIZE - 1) {
printf("%d", random_numbers_array[i]);
} else {
printf("%d,", random_numbers_array[i]);
}
}
printf("]\n");
// Exercise
find_two_largest(random_numbers_array, ARRAY_SIZE, &largest, &second_largest);
printf("Largest: %d\nSecond largest: %d\n", largest, second_largest);
}

View file

@ -1,27 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_RANDOM_VALUE 1000
#define ARRAY_SIZE 10
int *find_largest(int a[], int n) {
int highest_number_index = 0;
for (int i = 0; i < ARRAY_SIZE; i++) {
if (a[i] > highest_number_index) {
highest_number_index = i;
}
}
return &a[highest_number_index];
}
int main() {
int random_numbers_array[ARRAY_SIZE];
int *highest_index;
srand(time(NULL));
for (int i = 0; i < ARRAY_SIZE; i++) {
random_numbers_array[i] = rand() % MAX_RANDOM_VALUE + 1;
}
highest_index = find_largest(random_numbers_array, ARRAY_SIZE);
printf("HI: %p\n", highest_index);
printf("VALUE: %d", *highest_index);
}

View file

@ -1,23 +0,0 @@
#include <stdio.h>
int main()
{
int x = 10;
int * pX = &x;
printf("int value: %d\n", x);
printf("int address: %p\n", pX);
*pX = 15;
printf("int value after modifing pointer: %d\n", x);
printf("int address: %p\n", pX);
x = 20;
printf("int value: %d\n", x);
printf("int value from pointer: %d\n", *pX);
printf("int address: %p\n", pX);
char *p = "Hello";
printf("Char value: %s\n", p);
printf("Char address: %p", &p);
char p_value = *p;
printf("Char p_value: %c\n", p_value);
return 0;
}

View file

@ -1,14 +0,0 @@
#include <stdio.h>
int main() {
char *p = "Hello";
printf("%p\n", p);
printf("%c", *p);
p++;
printf("\n\n%p\n", p);
printf("%c", *p);
char *pp = "World";
char ppa[] = "Ryan Gosling";
printf("\n%s\n", ppa);
puts(ppa);
puts(ppa);
}

View file

@ -1,18 +0,0 @@
#include <stdio.h>
int main() {
int a, *ap;
a = 123;
ap = &a;
int b = 10;
printf("a:\t%d\n", a);
printf("&a:\t%p\n", &a);
printf("ap:\t%p\n", ap);
printf("*ap:\t%d\n", *ap);
printf("&ap:\t%p\n", &ap);
printf("*&ap:\t%p\n", *&ap);
printf("**&ap:\t%d\n", **&ap);
printf("------\n");
printf("b:\t%d\n", b);
printf("&b:\t%p\n", &b);
printf("*&b:\t%d\n", *&b);
}

View file

@ -1,16 +0,0 @@
#include <stdio.h>
#define N 10
int main() {
int a[N], *p;
printf("Enter %d numbers: ", N);
for (p = a; p < a + N; p++) {
scanf("%d", p);
}
printf("In reverse order:");
for (p = a + N - 1; p >= a; p--) {
printf(" %d", *p);
}
printf("\n");
return 0;
}

View file

@ -1,16 +0,0 @@
#include <stdio.h>
void decompose(double, long *, double *);
int main() {
long mp;
double rm;
double x = 3.141234;
printf("%ld, %f\n", mp, rm);
decompose(x, &mp, &rm);
printf("%ld, %f\n", mp, rm);
}
void decompose(double x, long *int_part, double *frac_part) {
*int_part = (long)x;
*frac_part = x - *int_part;
}

View file

@ -1,66 +0,0 @@
# ellipsis operator
Ellipsis оператором в макросах называется: `...`
Что он делает (пример в `ellipsis.c`):
```c
#include <stdio.h>
#define TEST(condition, ...) \
((condition) ? printf("Passed test: %s\n", #condition) : printf(__VA_ARGS__))
int main() {
int voltage = 30;
int max_voltage = 20;
TEST(voltage <= max_voltage, "Voltage %d exceeds %d\n", voltage, max_voltage);
max_voltage = 40;
TEST(voltage <= max_voltage, "Voltage %d exceeds %d\n", voltage, max_voltage);
}
```
Тут у нас происходит следующее:
1. `...` объединяет в себе параметры, которые идут после обязательных. В нашем случае получается что
туда попадают аргументы, которые идут плсле `condition`.
2. `__VA_ARGS__` - идентификатор, который может появляеться только в случае использования `...` и представляет
из себя аргументы, которые относятся к `...`
3. Дальше внутри программы препроцессор раскроет конструкцию:
```c
TEST(voltage <= max_voltage, "Voltage %d exceeds %d\n", voltage, max_voltage);
```
в что-то подобное:
```c
((voltage <= max_voltage)?
printf("Passed test: %s\n", "voltage <= max_voltage"):
printf("Voltage %d exceeds %d\n", voltage, max_voltage));
```
Где последняя строка это как раз то, что представляет из себя `printf(__VA_ARGS__)`
# static
Зачем нужно ключевое слово `static`. Есть 3 варианта:
1. Статичные глобальные переменные
file1.c
```c
static int counter = 0;
```
Данная цель - сделать эту переменнюу приватную для файла `file1.c`, т.е. в других файлах данная
переменная доступна не будет
2. Статичные локальные переменные
```c
void count_calls()
{
static int count = 0;
count++;
printf("Called %d times\n", count);
}
```
Тут переменная `count` будет доступна между вызовами функции, т.е. каждый вызов функции будет происходить
добавление 1 к `count`
```
Called 1 times
Called 2 times
Called 3 times
```
3. Статичные функции
```c
static void helper()
{
...
}
```
Тут делает функцию доступной только в файле, где объявлен
# __func__

View file

@ -1,20 +0,0 @@
#include "stdio.h"
#include <stdio.h>
#define FREEZING_PT 32.0f
#define BEGIN {
#define END }
int main(void)
BEGIN
float farenheit, celsius;
printf("Enter Fahrenheit temperature: ");
scanf("%f", &farenheit);
#define SCALE_FACTOR (5.0f / 9.0f)
celsius = (farenheit - FREEZING_PT) * SCALE_FACTOR;
printf("Celcius equivalent is: %.1f\n", celsius);
return 0;
}

View file

@ -1,12 +0,0 @@
#include <stdio.h>
#define DEBUG 1
int main()
{
#if defined (DEBUG)
printf("DEBUG defined");
#else
printf("DEBUG not defined");
#endif
return 0;
}

View file

@ -1,15 +0,0 @@
#include <stdio.h>
#define MK_ID(n) kakulya_##n
#define GENERIC_MAX(type) \
type type##_max(type x, type y) { return x > y ? x : y; }
GENERIC_MAX(float);
/* The macro above will transorf into something like following:
* float float_max(float x, float y) { return x > y ? x : y; }
*/
int main(int argc, char *argv[]) {
int MK_ID(1); // This converts to `int kakulya_1`
printf("%d", kakulya_1);
}

View file

@ -1,11 +0,0 @@
#include <stdio.h>
#define TEST(condition, ...) \
((condition) ? printf("Passed test: %s\n", #condition) : printf(__VA_ARGS__))
int main() {
int voltage = 30;
int max_voltage = 20;
TEST(voltage <= max_voltage, "Voltage %d exceeds %d\n", voltage, max_voltage);
max_voltage = 40;
TEST(voltage <= max_voltage, "Voltage %d exceeds %d\n", voltage, max_voltage);
}

View file

@ -1,21 +0,0 @@
#include <stdio.h>
// #define DEBUG 1
int main() {
#ifdef DEBUG
printf("All good, DEBUG is initialized");
#else
#error Debug is not initiated!
#endif
return 0;
}
// #error identifier blocks code compilation if compiler reached it.
// For example code above will not compile if DEBUG is not initiated.
//
// error.c: In function main:
// error.c:8:2: error: #error Debug is not initiated!
// 8 | #error Debug is not initiated!
// | ^~~~~
// make: *** [Makefile:14: main] Error 1

View file

@ -1,13 +0,0 @@
#include <stdio.h>
// #define DEBUG 1
// #ifdef identifier is similar to #if defined(identifier)
//
// #ifndef is just opposite of #ifdef
int main() {
#ifdef DEBUG
printf("DEBUG defined!");
#else
printf("DEBUG NOT defined!");
#endif
return 0;
}

View file

@ -1,11 +0,0 @@
#include <stdio.h>
#define DEBUG 0
int main()
{
printf("Hello ");
#if DEBUG
printf("debug ");
#endif
printf("World!");
}

View file

@ -1,21 +0,0 @@
#include <stdio.h>
#define SIZE 256
int main(int argc, char *argv[])
{
int BUFFER_SIZE;
if (BUFFER_SIZE > SIZE)
puts("ERROR: SIZE exceeded");
}
/*
* Код выше трансформируется в следующее:
*
*
* int main(int argc, char *argv[])
* {
* int BUFFER_SIZE;
* if (BUFFER_SIZE > 256)
* puts("ERROR: SIZE exceeded");
* }
*/

View file

@ -1,11 +0,0 @@
#include <stdio.h>
#define PRINT_INT(n) printf(#n " = %d\n", n)
int main() {
int i = 10;
PRINT_INT(i);
}
/* This program with the help of `#` operator will conver #n to string literal
* of an argument, so the output of the program will be: i = 10
*/

View file

@ -1,13 +0,0 @@
#include <stdio.h>
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#define IS_EVEN(n) ((n) % 2 == 0)
#define IS_EVEN_STR(n) ((n) % 2 == 0 ? "yes" : "no")
int main(int argc, char *argv[]) {
int j, k;
j = 10;
k = 20;
printf("%d\n", MAX(j, k));
printf("%d is even: %d\n", j, IS_EVEN(j));
printf("%d is even? %s\n", j, IS_EVEN_STR(j));
}

View file

@ -1,10 +0,0 @@
#include <stdio.h>
#define PRINT_INT(n) printf(#n " AND " #n " = %d\n", n)
int main(void)
{
unsigned long int k = 10;
printf("sizeof k: %lu", k);
int x = sizeof(int);
printf("sizeof k: %d", x);
}

View file

@ -1,12 +0,0 @@
/*
* #pragma tokens
* Используется когда программы слишком большие и надо воспользоваться какими-то
* особыми фичами компилятора.
*/
#include <stdio.h>
#pragma data(heap_size = > 1000, stack_size = > 2000)
int main()
{
return 0;
}

View file

@ -1,8 +0,0 @@
#include <stdc-predef.h>
#include <stdio.h>
int main() {
// printf("%s", __STDC_IEC_559__);
// printf("%s", __STDC_IEC_559_COMPLEX__);
printf("%d\n", __STDC_VERSION__);
printf("%d", __STDC_HOSTED__);
};

View file

@ -1,10 +0,0 @@
#include <stdio.h>
#define SIZE 100
int main(int argc, char *argv[]) {
int i;
i = 101;
#undef SIZE
if (i > SIZE) {
printf("Yey!\n");
}
}

View file

@ -1,61 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NUMBER 100
/* External variable */
int secret_number;
// Prototypes
void initialize_number_generator(void);
void choose_new_secret_number(void);
void read_guess(void);
int main() {
char command = 'y';
printf("Guess the secret number between 1 and %d. \n\n", MAX_NUMBER);
initialize_number_generator();
do {
choose_new_secret_number();
printf("New number has been chosen.\n");
read_guess();
printf("Play again? (Y/N)\n");
while (getchar() != '\n')
; // Discard any leftover input
scanf("%c", &command);
printf("\n");
} while (command == 'y' || command == 'Y');
exit(0);
}
/**
* @brief Initializing random number generator based on current time
* time(NULL) returns current time in `time_t` format
*/
void initialize_number_generator(void) { srand((unsigned)time(NULL)); }
/**
* @brief Here we are using rand() function and getting the remaining value of
* deletion by MAX_NUMBER + 1 to get random value between 0 and 100
*/
void choose_new_secret_number(void) {
secret_number = rand() % MAX_NUMBER + 1;
};
void read_guess(void) {
int guess, num_guesses = 0;
for (;;) {
num_guesses++;
printf("Enter guess: ");
scanf("%d", &guess);
if (guess == secret_number) {
printf("You guessed the number after %d attempts!\n\n", num_guesses);
return;
} else if (guess < secret_number) {
printf("Missed! Secret value is lower than your value\n");
} else {
printf("Missed! Secret value is higher than your value\n");
}
}
};

View file

@ -1,18 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
/**
* @brief Function for demonstration static local variables
*/
void test_static() {
static int static_var;
static_var += 1;
printf("%d\n", static_var);
}
int main() {
test_static();
test_static();
test_static();
test_static();
exit(0);
}

View file

@ -1,2 +0,0 @@
# Точка останова
Creating longer macros - 328

View file

@ -1,26 +0,0 @@
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
// Reading CLI arguments
char **p;
// Iterating from 1 due to the app name at 0 index
for (p = &argv[1]; *p != NULL; p++) {
printf("%s\n", *p);
}
printf("-----\n");
// Another way
for (int n = 1; n < argc; n++) {
char *argument = argv[n];
// Option 1 (Idiom 1 of finding end of string)
/* printf("%c", *argument); */
/* while (*argument++) { */
/* printf("%c", *argument); */
/* } */
// Option 2 (Idiom 2 of finding end of string)
while (*argument) {
printf("%c", *argument);
argument++;
}
printf("\n");
}
}

View file

@ -1,6 +0,0 @@
int main() {
// Char array declaraion
char adate[] = "June 14";
// Char pointer declaraion
char *pdate = "June 14";
}

View file

@ -1,48 +0,0 @@
#include <stdio.h>
#include <string.h>
#define MAX_REMIND 50
#define MSG_LEN 60
int read_line(char str[], int n);
int main(void) {
char reminders[MAX_REMIND][MSG_LEN + 3];
char day_str[3], msg_str[MSG_LEN + 1];
int day, i, j, num_remind = 0;
for (;;) {
if (num_remind == MAX_REMIND) {
printf("-- No space left --\n");
break;
}
printf("Enter day and reminder: ");
scanf("%2d", &day);
if (day == 0)
break;
sprintf(day_str, "%2d", day);
read_line(msg_str, MSG_LEN);
for (i = 0; i < num_remind; i++)
if (strcmp(day_str, reminders[i]) < 0)
break;
for (j = num_remind; j > i; j--)
strcpy(reminders[j], reminders[j - 1]);
strcpy(reminders[i], day_str);
strcat(reminders[i], msg_str);
num_remind++;
}
printf("\nDay Reminder\n");
for (i = 0; i < num_remind; i++)
printf(" %s\n", reminders[i]);
return 0;
}
int read_line(char str[], int n) {
int ch, i = 0;
while ((ch = getchar()) != '\n') {
if (i < n) {
str[i++] = ch;
}
}
str[i] = '\0';
return i;
}

View file

@ -1,23 +0,0 @@
#include <ctype.h>
#include <stdio.h>
#define MAX_REMIND 50
#define MSG_LEN 60
char *capitalize(char cap_string[]);
int main() {
char string_to_capitalize[] = "some fuck1ng bullshit!";
char *cap;
cap = capitalize(string_to_capitalize);
printf("%s", cap);
}
char *capitalize(char cap_string[]) {
char *p;
char capitalized_string[MSG_LEN];
p = capitalized_string;
for (int i = 0; cap_string[i] != '\0'; i++) {
capitalized_string[i] = toupper(cap_string[i]);
}
return p;
}

View file

@ -1,26 +0,0 @@
#include <ctype.h>
#include <stdio.h>
#define MAX_REMIND 50
#define MSG_LEN 60
char *capitalize(char cap_string[]);
int main() {
char string_to_capitalize[] = "some fuck1ng bullshit!";
char *cap;
cap = capitalize(string_to_capitalize);
printf("%s", cap);
}
char *capitalize(char cap_string[]) {
char *p;
char capitalized_string[MSG_LEN];
int i = 0;
p = capitalized_string;
while (*cap_string) {
capitalized_string[i] = toupper(*cap_string);
i++;
cap_string++;
}
return p;
}

View file

@ -1,36 +0,0 @@
#include <stdio.h>
#define MAX_LEN 60
char *censor(char cens_string[]);
int main() {
char string_to_censor[MAX_LEN] = "Hello my dear foolish foles!";
char *cens;
cens = censor(string_to_censor);
printf("INPUT:\t %s\n", string_to_censor);
printf("OUTPUT:\t %s\n", cens);
}
char *censor(char cens_string[]) {
char to_cens[] = "foo";
char cens_char = 'x';
char censored[MAX_LEN + 1], *c, *start;
c = censored;
start = c;
int i = 0;
// Starting iteration on string to censor
while (*cens_string) {
// If we find 'f' char - we need to check current 'f' char and next 2 for
// equality with to_cens string
if (*cens_string == to_cens[0] && *(cens_string + 1) == to_cens[1] &&
*(cens_string + 2) == to_cens[2]) {
*c = cens_char;
*(c + 1) = cens_char;
*(c + 2) = cens_char;
cens_string += 3;
c += 3;
} else {
*c++ = *cens_string++;
}
}
return start;
}

View file

@ -1,15 +0,0 @@
#include <stdio.h>
int main(void) {
// String literal assigment
char *p;
/*Following statement does not copy string. It makes pointer p to point to first charachter of list of chars*/
p = "abc";
printf("%s\n\n", p);
// ---
// Subscripting
char ch;
ch = p[1];
printf("%c\n", ch);
}

View file

@ -1,5 +0,0 @@
#include <stdio.h>
int main() {
char *p = "Hello world!";
printf("%c", *p);
}

View file

@ -1,14 +0,0 @@
#include <stdio.h>
int main() {
char *p = "Hello";
printf("%p\n", p);
printf("%c", *p);
p++;
printf("\n\n%p\n", p);
printf("%c", *p);
char *pp = "World";
char ppa[] = "Ryan Gosling";
printf("\n%s\n", ppa);
puts(ppa);
puts(ppa);
}

View file

@ -1,19 +0,0 @@
#include <stdio.h>
int main() {
char ch0, ch1, ch2, ch3;
ch0 = "abc"[0];
ch1 = "abc"[1];
ch2 = "abc"[2];
ch3 = "abc"[3];
printf("%c\n", ch0);
printf("%p", &ch0);
printf("\n\n");
printf("%c\n", ch1);
printf("%p", &ch1);
printf("\n\n");
printf("%c\n", ch2);
printf("%p", &ch2);
printf("\n\n");
printf("%c\n", ch3);
printf("%p", &ch3);
}

View file

@ -0,0 +1,20 @@
/*
* Exercise 4-1. Write the function strindex(s,t) which returns the position of
* the rightmost occurrence of t in s, or -1 if there is none
*/
#include <stdio.h>
#include <string.h>
int strindex(char s[], char t) {
for (int i = 0; i < strlen(s); i++) {
if (s[i] == t) {
return i;
}
}
return -1;
}
int main() {
int index = strindex("Hello world", 'w');
printf("Index: %d\n", index);
}

View file

@ -1,31 +0,0 @@
#include <stdio.h>
#define LOWER 0
#define UPPER 300
#define STEP 20
int main() {
float fahr, celsius;
int lower, upper, step;
fahr = LOWER;
printf("Temperature conversion\n");
while (fahr <= UPPER) {
celsius = (5.0 / 9.0) * (fahr - 32.0);
printf("%3.0f\t%6.1f\n", fahr, celsius);
fahr = fahr + STEP;
}
printf("\nNow Celcius -> Fahr table\n");
lower = 0;
upper = 100;
step = 5;
fahr = 0.0;
celsius = lower;
while (celsius <= upper) {
fahr = (celsius * (9.0 / 5.0)) + 32;
printf("%3.0f\t%6.1f\n", celsius, fahr);
celsius = celsius + step;
}
return 0;
}

View file

@ -1,12 +0,0 @@
#include <stdio.h>
int main() {
int div_result;
printf("hello world\n");
printf("Test\tTab\n");
printf("Test backspace\b\b\b");
printf("Test\tc_word\a\n");
div_result = 6/5;
printf("Result: %d", div_result);
return 0;
}

View file

@ -1,40 +0,0 @@
# Links
- [Tutorial for ncurses](https://tldp.org/HOWTO/NCURSES-Programming-HOWTO/helloworld.html)
# Построчная буферизация
Построчная буферизация означает, что символы не отправляются программе сразу, а сначала накапливаются в буфере пока пользователь не нажмет `Enter`.
Визуальное описание выглядит примерно так:
*Режим cooked*
```
Пользователь печатает: h e l l o [backspace] [backspace] i
Что видит пользователь: helli
Буфер терминала: helli
↓ [Enter]
Программа получает: "helli\n" (только после Enter!)
```
*Режим cbreak*
```
Пользователь печатает: h
Программа получает: 'h' ← сразу!
Пользователь печатает: e
Программа получает: 'e' ← сразу!
Пользователь печатает: l
Программа получает: 'l' ← сразу!
```
# Режимы инициализации
## raw() vs cbreak()
У терминалов есть 3 режима работы:
1. Cooked mode (по умолчанию)
Это когда - ввод буферизиуется построчно, пользователь должен нажать Enter, работают сигналы по типу Ctrl-C, Ctrl-Z, работает backspace для редактирования строки.
2. Cbreak mode
Это когда:
- Ввод передается немедленно, без ожидания Enter;
- Сигналы работают;
- Нет буферизации по строкам;
- Каждый символ доступен сразу после нажатия.
3. Raw mode
Это когда:
- Ввод передается немедленно;
- Полный контроль над всеми клавишами;
- Не работают сигналы

View file

View file

@ -1,29 +0,0 @@
#include "modes.h"
#include <ncurses.h>
int main() {
/* Инициализация curses режима. Необходимо перед использованием приложения с
* этой библиотекой. Она инициализирует curses систему и выделяет память для
* текущего окна (stdscr в этой библиотеке)*/
initscr();
/*Функция вызова печати символов в stdscr на текущей x, y позиции. По
* умолчанию координаты = 0,0 => печать произойдет в левом верхнем углу*/
// printw("Hello world!");
/*Для того, чтобы символы выше напечатались на экране (на данный момент
* получена инструкция печати, но выполнение еще не инициализировано). Нужно
* вызывать функцию refresh, которая "Обновляет некоторые флаги и структуры
* данных и пишет данные в буфер, который относится к stdscr". Собственно эта
* функции дампит буфер на экран*/
// refresh();
// Ждем инпута от пользователя
// getch();
ncurses_modes();
// Завершаем curses режим
endwin();
return 0;
}

View file

@ -1,21 +0,0 @@
#include "modes.h"
#include <ncurses.h>
void ncurses_modes() {
int ch;
raw();
keypad(stdscr, TRUE);
noecho();
printw("Type char to see it in bold\n");
ch = getch();
if (ch == KEY_F(1))
printw("F1 key pressed");
else {
printw("The pressed key is ");
attron(A_BOLD);
printw("%c", ch);
attroff(A_BOLD);
}
refresh();
getch();
}

View file

@ -1,5 +0,0 @@
#ifndef MODES_H
#define MODES_H
void ncurses_modes();
#endif