Lab06 s1 24 25
Lab06 s1 24 25
1. Obiective:
- Ințelegerea noțiunilor de expresie, operanzi și operatori
- Trecerea în revistă a principalilor operatori şi reținerea celor mai importanți
- Ințelegerea modului în care se face evaluarea expresiilor
- Scrierea și rularea de programe simple care folosesc operatori
1’. Objectives:
- Understanding the concept of expression, operand and operator
- Reviewing the main operators and remembering the most important ones
- Understanding the expression evaluation
- Writing and running some simple applications that use operators
2. Breviar teoretic
Operatorii sunt simboluri ce specifică operaţiile de efectuat asupra operanzilor. În urma aplicării unui
operator se obţine un rezultat.
Operatori paranteză
parantezele rotunde, ( )
paranteze pătrate, [ ]
Operator condiţional
E1 ? E2 : E3, unde E1, E2, E3 sunt expresii.
Operator virgulă
leagă două expresii în una singură astfel: E1, E2
C++ defineşte cuvintele cheie and, or, not, xor, and_eq, or_eq, not_eq, xor_eq, etc.
ca alternativa pentru &&, ||, !, ^, &=, |=, != and ^=, numite, “digraphs”, care pot fi
folosite în C++.
( https://en.cppreference.com/w/cpp/language/operator_alternative)
În limbajul C e necesar a include <iso646.h>
O expresie poate folosi operatori din clase diferite, la evaluarea ei ţinându-se cont de:
• precedenţă (prioritate): dă ordinea de efectuare a operaţiilor;
• asociativitate: indică ordinea de efectuare a operaţiilor care au aceeaşi precedenţă; poate fi
stânga->dreapta (S->D) sau dreapta->stânga (D->S);
• regula conversiilor implicite: asigură stabilirea unui tip comun pentru ambii operanzi, la
fiecare operaţie care solicită acest lucru şi în care tipurile diferă; regula de bază: se promovează tipul
cu domeniu de valori mai mic către tipul cu domeniul de valori mai mare;
2. Theoretical breviary
Operators are symbols that specify the operations to be performed on operands. Following the
application of an operator, a result is obtained.
Assignment operators
simple assignment, which is denoted by the character = and has the form: v=(expression)
where v is a simple variable, reference to an array or structure element. It is associated from
right to left: vn=…=v1=v=expression; assigning first v=expression, the results are associated to
v1, then v2, etc. until vn.
compound assignment, in which a distinct operator is associated with the assignment
operator (operator=), where the operator can be binary arithmetic or binary bitwise, so it
can be one of the following operators: /, %, *, -, +, <<, >>, &, ^, | .
The syntax: var operator= expression;
is equivalent to: var = var operator (expression);
Remark: Early C versions allowed postfix compound assignment. When the compiler would accept
both =- and -=, some compilers added a warning message for the old operator, something like:
“Operator =- is deprecated. Use -=”, others ignore the compound postfix operator.
Increment and decrement (unary) operators. These are ++ and --, can be postfixed (after the
operand), respectively prefixed (before the operand).
Parenthesis operators
round parenthesis, ( )
square parenthesis, [ ]
Conditional operator
E1 ? E2 : E3, where E1, E2, E3 are expressions
Comma operator
links two expressions into a single one, like this: E1,E2
C++ defines the keywords and, or, not, xor, and_eq, or_eq, not_eq, xor_eq, etc. as
an alternative for &&, ||, !, ^, &=, |=, != and ^=, named, “digraphs” which can be used in
C++.
( https://en.cppreference.com/w/cpp/language/operator_alternative)
In C language is necessary to include <iso646.h>
An expression may use operators from different classes, being evaluated considering:
• the precedence (priority): reflects the order of performing operations;
• associativity: indicates the order in which operations having the same precedence are
performed; can be left->right or right->left;
• Implicit conversions rule: ensures that a common type is established for both operands, each
time the situation imposes it; Basic rule: the type with the smaller value range is promoted to the
type with the larger value range;
The order of evaluation given by precedence and associativity can be modified by grouping the
operations with round parentheses.
3. Exemple / Examples
Ex. 1
/* conditional operator */
#include <iostream>
using namespace std;
int main ( ){
double n1, n2, n3;
cout << "Enter 3 real numbers: ";
cin >> n1 >> n2 >> n3;
cout << (n1 <= n2 && n2 <= n3 ? "Are ordered" : "Are not ordered") << '\n';
return 0;
}//end main
Ex. 2
/* logical and relational operators
The program checks if the character entered is an uppercase or lowercase letter
*/
#include <iostream>
using namespace std;
int main( ){
char ch;
cout << "Enter a character: ";
cin >> ch;
cout << (isAlpha(ch) != 0 ? "Is a letter" : "Is not a letter") << '\n';
//cout << (isAlpha(ch) ? "Is a letter" : "Is not a letter") << '\n';
return 0;
}//end main
int main( ){
unsigned char x = '\011';
unsigned char y = '\027';
cout << "x = " << oct << short(x) << '\n';
cout << "y = " << oct << short(y) << '\n';
cout << "~x = " << oct << (short)(~x) << '\n';
cout << "x & y = " << oct << (short)(x & y) << '\n';
cout << "x | y = " << oct << (short)(x | y) << '\n';
cout << "x ^ y = " << oct << (short)(x ^ y) << '\n';
cout << "x << 2 = " << oct << (short)(x << 2) << '\n';
cout << "x >> 2 = " << oct << (short)(x >> 2) << '\n';
return 0;
}//end main
int main() {
unsigned char x = '\011';
unsigned char y = '\027';
printf("x = %o \n" , short(x));
printf("y = %o \n", short(y));
printf("~x = %o \n", short(~x));
return 0;
}//end main
Ex. 4
/* logical operators in literal representation */
#include <iostream>
#include <bitset>// display bitwise representation from STL
using namespace std;
int main( ) {
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << "a = " << bitset<8> (a) << "," << " b = " << bitset<8>(b) << ", ! a = " <<
bitset<8>(!a) << "," << " not b = " << bitset<8>(not b) << endl;
// The logical and bit result is 00000001
cout << "a & b = " << bitset<8>(a & b) << hex << " Hex value bitand: 0X" << (a
bitand b) << ", a && b = " << bitset<8>(a && b) << ", a and b = " << bitset<8>(a
and b) << endl;
// The logical or bit result is 00001101
cout << "a | b = " << dec << bitset<8>(a | b) << hex << " Hex value bitor: 0X" <<
(a bitor b) << ", a || b = " << bitset<8>(a || b) << ", a or b = " << bitset<8>(a
or b) << endl;
// The logical xor bit result is 00001100
cout << "a ^ b = " << dec << bitset<8>(a ^ b) << ", a xor b = " << bitset<8>(a xor
b) << hex << " Hex value: 0X" << (a xor b) << endl;
// The logical complement bit result is 11111010
cout << "~(a=" << a << ") = " << dec << bitset<8>(~a) << hex << " Hex value compl:
0X" << (compl a) << endl;
// The result is 00010010 for left shift
cout << "b << 1" << " = " << dec << bitset<8>(b << 1) << hex << " Hex value: 0X" <<
(b << 1) << endl;
// The result is 00000100 for right shift
cout << "b >> 1 " << "= " << dec << bitset<8>(b >> 1) << hex << " Hex value: 0X" <<
(b >> 1) << endl;
}//end_main
Ex. 5
/* compound assignment operators
program that reads an integer from the console and performs with it:
multiplication, division modulo, bitwise XOR, bitwise AND
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main( ){
int x;
printf("Enter the value of int x: ");
scanf("%d", &x);
x ^= 0x0f;
printf("\n%x", x);
x %= 2;
printf("\n%d", x);
x &= 0x01;
printf("\n%x\n", x);
x *= 4;
printf("\n%d", x);
return 0;
}//end main
Ex. 6
/* Program that reads an integer and applies the postfixed increment operator and
the prefixed increment operator, displaying the result each time
*/
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
int main( ){
int x;
printf("Enter the value of x: ");
scanf("%d", &x);
printf("\n%d", x++);
printf("\n%d", x);
printf("\n%d", --x);
printf("\n%d\n", x);
//increment/decrement
int a = 3;
cout << "\n a initialized = " << a << '\n';//3
int rez = a++ + ++a * a++;
cout << "\n a processed = " << a << " rez= " << rez <<'\n'; //6, 20 or 28 or
//33- depending on the compiler
return 0;
}//end main
Ex. 7
/* sizeof and casting operators
Program that displays the size (in bytes) for some data types and constants
*/
#include <iostream>
using namespace std;
int main( ){
cout << "Size of char = " << sizeof(char) << " bytes\n";
cout << " Size of char* = " << sizeof(char*) << " bytes\n";
cout << " Size of short = " << sizeof(short) << " bytes\n";
cout << " Size of int = " << sizeof(int) << " bytes\n";
cout << " Size of long = " << sizeof(long) << " bytes\n";
cout << " Size of float = " << sizeof(float) << " bytes\n";
cout << " Size of double = " << sizeof(double) << " bytes\n";
cout << " Size of 1.55 (double) = " << sizeof(1.55) << " bytes\n";
cout << " Size of 1.55 (float) = " << sizeof((float)1.55) << " bytes\n";
cout << " Size of 1.55L = " << sizeof(1.55L) << " bytes\n"; //8 or 16
cout << " Size of SALUT = " << sizeof("SALUT") << " bytes\n";
return 0;
}//end main
4. Lucru individual:
1. Să se scrie un program care afişează valoarea polinomului de gradul 3 pentru o anumită
valoare a variabilei reale x. Citiți coeficienții polinomului și valoarea x.
2. Să se scrie un program care citeşte lungimile laturilor unui triunghi (folosind variabile întregi).
Validează că aceste 3 valori să fie laturi de triunghi şi afişează în acest caz laturile și aria
triunghiului ca valoare reală într-un câmp de lățime 10, aliniat la stânga cu o precizie de 2
zecimale, altfel afişează cele 3 valori și un mesaj adecvat.
3. Să se scrie un program care afişează valorile biţilor unei variabile de tip unsigned char aplicând
succesiv operatorul de deplasare dreapta şi operatorul %.
4. Să se scrie un program care monitorizează un canal de 16/32/64 biţi. Pentru aceasta citiţi de
la tastatură o valoare întreagă fără semn x, care va fi afişată în zecimal, binar, octal şi
hexazecimal. Folosiţi o funcţie pentru conversia numerelor din baza 10 în baza 2 sau facilitatea
bitset din C++. Implementaţi o funcţie numită getsets() care primeşte trei valori ca parametri:
x: valoarea citită de la tastatură
p: poziţia unui bit din cei 16/32 sau 64 de biţi (numărând de la dreapta şi pornind de la 0)
n: numărul de biţi care vor fi extraşi din valoarea citită.
Funcţia returnează, aliniaţi spre dreapta, acei n biţi ai valorii x, pornind de la poziţia p, unde
p<8*sizeof(x) şi p>n. Afişaţi rezultatul în binar, octal şi hexazecimal.
5. Să se scrie un program care citeşte de la intrarea standard un număr întreg şi afişează numărul
de zerouri semnificative din reprezentarea sa binară.
6. Se citește de la intrarea standard o valoare întreagă. Să se afișeze în format zecimal valoarea
fiecărui octet al întregului citit.
7. Se citesc de la tastatură 2 numere reale. Să se realizeze operațiile de adunare, scădere,
înmulțire și împărțire cu valorile date. Să se afișeze rezultatele obținute, apoi să se rotunjească
valorile obținute la valori întregi, folosind operatorul cast și fără a folosi funcții specifice. Să se
afișeze apoi valoarea minimă dintre numerele citite folosind operatorul condițional.
8. Citiți de la tastatură mai multe caractere reprezentând litere mici. Să se transforme
caracterele citite în litere mari în 2 moduri: printr-o operație aritmetică, respectiv folosind o
operație logică și o mască adecvată.
9. Citiți de la tastatură 2 numere întregi. Dacă sunt egale, determinați aria cercului cu raza egală
cu valoarea citită. Folosiți M_PI pentru calculul ariei din <cmath>. Dacă sunt diferite calculați
aria dreptunghiului cu laturile egale cu valorile date. Afișați aria calculată aliniată la stânga cu
două zecimale precizie și valorile introduse într-un câmp de 10 poziții, specificând forma
geometrică pentru care s-a făcut calculul.