Печать, ввод, операторы, условия и циклы

Печать переменных

Как показано в примерах моей последней статьи, функция printf выводит строку в консоль.

Теперь у этого есть свое применение, но чтобы сделать эту функцию более модульной, давайте поговорим о спецификаторах формата.

Спецификаторы формата заменяют части строк переменными при их включении в аргументы printf.

Format Specifiers:
╔══════════════╦════════════════════╗
║   Specifier  ║       Type         ║ 
╠══════════════╬════════════════════╣
║ %f           ║ Floating point     ║ 
║ %c           ║ Character          ║ 
║ %d           ║ Decimal            ║ 
║ %s           ║ String             ║
╚══════════════╩════════════════════╝
int x = 20;
int y = 10;
printf("The value of x is %d", x);
//Output: The value of x is 20
x+=1;
printf("The value of x is %d,\nThe value of y is %d", x, y);
//Output: The value of x is 21
//The value of y is 10

Если вы пропустите переменные аргументы, строка выведет размер типа спецификатора.

Чтение входных данных

Чтобы прочитать ввод от пользователя, используйте функцию scanf. Эта функция является частью библиотеки stdio, поэтому вам нужно будет ее импортировать.

#include<stdio.h>
int main(){
   int x;
   float y;
   printf("Enter the integer: ");
   scanf("%d", &x); //(format specifier, reference to variable)
   // Sets x = to the users input without any need for conversion
   // the & is a reference to the variable x
   // this allows us to directly change the value of x from the 
   // scanf function
   printf("Enter the float: ");
   scanf("%f", &y);
}

Операторы

Арифметика

  • Однонаправленный — Один операнд/переменная
    — Приращение: ++
    — Уменьшение: «- -»
//Can be postfix ++x or prefix x++
//Prefix inc/dec the variable first and then returns x, so
int x =10;
int y = ++x;
// y = 11
//postfix returns the variable and then inc/dec variable
int x = 10;
int y = x++
// y = 10
  • Двунаправленный — принимает два операнда (x, y)
    – Суммирование: x + y
    – Вычитание: x - y
    – Умножение: x * y
    – Деление: x / y
    – Модуль, остаток: x % y

Побитовый

Используется для управления битами

В таблицах ниже показаны различные побитовые операторы.

где A и B являются битами, которые могут быть ложными (выкл, НИЗКИЙ, 0) или истинными (вкл, ВЫСОКИЙ, 1)

и результат является выходом оператора, заданного A и B

AND Table:
╔═══════╦══════╦════════════════════╗
║   A   ║   B  ║       Result       ║ 
╠═══════╬══════╬════════════════════╣
║   0   ║   0  ║         0          ║ 
║   0   ║   1  ║         0          ║ 
║   1   ║   0  ║         0          ║ 
║   1   ║   1  ║         1          ║
╚═══════╩══════╩════════════════════╝
OR Table:
╔═══════╦══════╦════════════════════╗
║   A   ║   B  ║       Result       ║ 
╠═══════╬══════╬════════════════════╣
║   0   ║   0  ║         0          ║ 
║   0   ║   1  ║         1          ║ 
║   1   ║   0  ║         1          ║ 
║   1   ║   1  ║         1          ║
╚═══════╩══════╩════════════════════╝
XOR Table:
╔═══════╦══════╦════════════════════╗
║   A   ║   B  ║       Result       ║ 
╠═══════╬══════╬════════════════════╣
║   0   ║   0  ║         0          ║ 
║   0   ║   1  ║         1          ║ 
║   1   ║   0  ║         1          ║ 
║   1   ║   1  ║         0          ║
╚═══════╩══════╩════════════════════╝
NOT Table:
╔═══════╦══════╗
║   A   ║   B  ║
╠═══════╬══════╣
║   0   ║   1  ║
║   1   ║   0  ║
╚═══════╩══════╝
int x = 0b1010 // binary variables
int y = 0b0101
int andOp = x & y; // 0
int orOp = x | y; // 1111 = 15
char notX = ~x; // 0101 = 5
char notY = ~y; // 1010 = 10
int xorOp = x ^ y; // 1111 = 15

Операторы смены

  • оператор сдвига влево ‹‹
  • оператор правой смены ››
  • эти операции будут сдвигать биты двоичного числа (рассмотрим в следующей статье) внутри его регистра влево или вправо на указанное число
int x = 0b00001010; // 10 decimal
x >> 1; // shift bits to the right once
Original 8 bit register
╔═══════════════════════════════════════════════╗
║  0  ║  0  ║  0  ║  0  ║  1  ║  0  ║  1  ║  0  ║
╚═══════════════════════════════════════════════╝
Right Shifted 8 bit register by 1
╔═══════════════════════════════════════════════╗
║  0  ║  0  ║  0  ║  0  ║  0  ║  1  ║  0  ║  1  ║
╚═══════════════════════════════════════════════╝
int y = 0b00001010; 
y << 1;
Left Shifted 8 bit register by 1
╔═══════════════════════════════════════════════╗
║  0  ║  0  ║  0  ║  1  ║  0  ║  1  ║  0  ║  0  ║
╚═══════════════════════════════════════════════╝
Will convert the value from binary back to integer

Назначение

int x = 20;
x += 3; // same as x = x + 3 or 23
x -= 5; // same as x = x - 5 or 18
x *= 2; // same as x = x * 2 or 36
x /= 4; // same as x = x / 4 or 9
x %= 4; // remainder of 9/4 or 1
int y = 0b00001010;
y &= 1; // 1010 & 1 = 0b00001011
y |= 15; // 1011 | 15 = 0b00001111
y ^= 2; // 1111 ^ 0010 = 0b00001101

Реляционные и логические

  • Любое число, не равное нулю, считается истинным
  • Ноль считается ложным
x == y //true if x is equal to y
x != y //true if x is no equal to y
x > y //true if x is greater than y
x < y //true if x is less than y
x >= y //true if x is greater or equal to y
x <=y //true if x is less than or equal to y
x && y //true if x and y are true
x || y //true if x or y are true
!x //true if x is false

Условное заявление

Выполнение операций при определенных условиях

В C есть два основных типа

  • Если блоки
int x = 20;
if(x >= 20){
  printf("X is greater than or equal to 20");
} else if (x < 20) {
  printf("X is less than 20");
} else {
  printf("X is undefined");
}
//only required part of a conditional is the if (condition)
//statement, the rest is optional
  • Операторы переключения
int x = 3
switch(x){
  case 1:
   printf("X equals 1");
   break;
  case 2:
   printf("X equals 2");
   break;
  case 3:
   printf("X equals 3");
   break;
  default:
   printf("X is a different number");
   break;
}
// the case values must be constant and only used once 
// (no variables)
// the default case is optional
// need to include break at end of case or the switch statement will
// run every case after the one that is met

Циклы

  • Для петель
for(int i = 0; i < 20; i++){
   printf("Hello: %d", i);
} 
// for(variable initializer; condition; incrementer/decrementer)
// {Statement}
// Code above will print out hello 20 times with the number 0-19 in
// place of %d
  • Пока циклы
int x = 10;
while (x != 100){
   printf("Not yet");
   x += 10;
}
printf("x is now at 100");
// Run until the condition is false
// while(condition){statements}
  • Циклы Do-while
char choice = 'y';
do {
  printf("Do you want to keep going: );
  scanf("%c", &choice);

}while(choice == 'y')
printf("Terminating");
//will loop once and then check the conditional 

Надеюсь, вам всем понравился второй раздел основ Embedded C.
Если вам понравился этот, вот Часть I и Часть III.