Plan

  • The alphabet, vocabulary, syntax and semantics of a programming language
  • The shape of a simple C++ program, processing directives
  • Fundamental data types
  • Characters, reserved words
  • Variables, expressions, assignments
  • Operators
  • Boolean expressions
  • Constants
  • Integer type
  • Float type
  • Conversions

The alphabet of a programming language:

Character set

Any programming language has a certain alphabet at its core. In most cases, the set comprises of:

  • The English language characters( A-Z, usually both lower and upper cased, summing up to 52 characters)
  • Arab numbers( 0-9, 10 characters in total);
  • Special characters( , : = < > # $ % + – * / “ ‘ () etc.) whose base meaning differs from language to language.

Escape sequences / Special characters in C++

\b Backspace, \t Horizontal Tab, \v Vertical Tab, \n New line, \f New page – formfeed
 \r Beginning of line, \” Quotation marks, \’ Apostrophe, \\ Backslash, \? Question mark, \a Alarm

Character Sets Codification Standards

  • EBCDIC (Extended Binary Coded Decimal Interchange Code), an 8 bit code, introduce by IBM;
  • ASCII (American Standard Code for Information Interchange), introduced by ANSI (American National Standard Institute), is a 7 bit code and can support 128 characters( 95 displayable ones and 33 undisplayable, also known as control characters). Later on, the ASCII set was extended to an 8 bit codification, thus making available up to 256 characters for general use.

The first 28 characters are from the ASCII standard set, the next 128 are displayable character codes for national European characters (French, Spanish, Romanian etc.), some of the greek alphabet letters, some common mathematical notations, special table drawing characters etc.

The order of the alphabetical characters is based on uniquely assigned numerical codes .

Key Words / Reserved words

Based on the characters that make up the common language alphabet, we identify words that encompass the whole vocabulary and the speech lexicon and with whose help, other expressions and instructions specific to the language are created. These are divided in two categories:

  1. key words – they have an explicit meaning in a certain context  (I.E. in some programming languages, words that delegate instructions can be used as variable names, leaving out any restrictions: These situations are generally avoided as  they can hide errors in the program’s logic and make it harder to grasp to a new reader);
  2. reserved words – these words cannot be used other than their main intended purpose ( i.e. in C++). The advantages of using this category of words are as follows:
  • The software becomes easier to understand;
  • The compilation speed is greatly increased ( lexical, syntactical and semantical analysis is simplified in regards to the search of particular symbols within character tables);
  • Errors are easier to identify;
  • On the other hand, within the scope of the language, both reserved words and user defined words will be used to refer to different elements (variables, files, procedure names, function names etc.)

The syntax of a programming language

Even in the case of programming languages, word sequences constructed by following a certain set of rules can lead up to sentences called instructions. The syntax of a programming language refers to the rule set through which the compiler decides if a certain instruction is correctly written or not. This syntax can be described in numerous ways, one of which being the BNF notation (Backus-Naur Form).

BNF Notation

The BNF was first used to describe the ALGOL language( within the ALGOL60 report back in 1963) and bears the name of its two authors. In BNF, metasymbols, terminal symbols and non-terminal symbols are used.

Metasymbols are <, >, ½ si ::= and are part of the language description mechanism. The ½ symbol signifies an alternative whereas  ::=  refers to an entity being “defined as such”.

Terminal symbols are words that show up where production requires them to do so (I.E. for, while, do, +, ; etc.).

Non-terminal symbols are found between < and > signs, sdepicting language creations by themselves (I.E. <variable>, <identifier>, <instruction if> etc.).

Example: in C++, the syntax of an identifier is described in BNF as follows:

<identifier>::=<letter>|<identifier><digit>|<identifier><letter>|

where

<letter>::=a|b|...|z|A|B|...|Z|_

<digit>::=0|1|2|...|9
The symbol _ is considered <letter> in this context.

Based on these rules, the identifier can also be defined in three other possible ways: An identifier, be it a <letter>, an <identifier> followed by a <digit> or a <literal> (recursive definition). The meaning of a definition is as follows: an identifier can contain a single letter or a letter followed by any number of letters and/or digits. According to this definition, these next identifiers are considered to be adequate: a, t1, sec12a1.

The description of the conditional instruction syntax (if-else) from C++ in BNF notation is as follows:

<instruction if>::= if (<condition>)
                        <instruction1>
                     else
                        <instruction2>

Semantics of a programming language

The semantics of an instruction represents the meaning it has, as in what will the computer do when it encounters it.

And so, for the if-else instruction presented above, the <condition> will be evaluated and if it is found to be true ( at the time of the evaluation) then the following instruction will be executed once <instruction1>, respectively <Instruction2> if the value is false.

Your first program in C++, using Code::Blocks

Setting up Code::Blocks and writing your first program:

Example of a simple program in C++

/*
 * first program in C++
 */
#include <iostream>
int main ()
{
  std::cout << "First test 1, 2, 3. ";
  std::cout << "it's working.. \n";
  return 0;
}

OR

/*
* first program in C++
*/
#include <iostream>
using namespace std;
int main ()
{
  cout << "First test 1, 2, 3. ";
  cout << "it's working.. \n";
  char c;
  cout << "To exit, press any key!!\n";
  cin >> c;
  return 0;
}

The outuput will be

First test 1, 2, 3. it's working..

The sape of a simple program in C++

/*annotation; it does not interfere the program */
//preprocess directives
#include <libraries> (Input/output, math, strings, …)
#define 
//variable declarations
user types;
Variables;
Functions;
....
// defining user functions ..........

//main function
int main()
{
..........
return 0;
}  //this is where the program ends

Preprocess directives

Preprocess directive #include

Syntax:

#include <libraries> (Input/output, math, strings, …)

Exemple:

#include <iostream>
#include <math.h>
#include <stdlib.h>
#include “my_library.h”
#include “t1.h”

Preprocess directive #define

Syntax:

#define symbol

#define symbol value

Examples:

#define infinite 1000
#define pi 3.1415926
#define then
#define si &&
#define daca if
#define altfel else
#define max(x,y) x > y ? x : y #define min(x,y) x < y ? x : y
#include <stdio.h>
void main()
{
   float a,b,c;
   printf("Give the lenghts of the sides:\n");
   scanf("%f %f %f",&a,&b,&c);
   daca ((a>=0) si (b>=0) si (c>=0) si  (a<b+c) si (b<a+c) si (c<a+b))
        printf("%4.2f, %4.2f  si %4.2f forms a triangle.", a,b,c);
   altfel
        printf("It does not form a triangle.");
}

Data

Constants and variables. Expressions

Within a program, data can be declared as being either constants or variables.

A constant is a data type whose value cannot be modified during the program execution, so essentially it remains constant.

A variable is a data type whose value can is modifiable through different means during the program execution, so it can vary but this is not mandatory. Thus, it can be declared as being a variable within a program, leading to it receiving a value and the said value to remain associated to its respective variable until the program execution will have stopped.

Obviously, when a data type is declared as being constant, a value will be assigned along it, and when a variable will be declared, it is without saying, that for it to be used later on, it will have to receive a value.

Most programming languages assign an initial value to variables, at the same time with their declaration. Thus, string arrays are initialized with the empty string, and numbers are considered to be 0.

Not only constants, but also variables have a certain structure, be it simpler or more complex and a certain nature, give through the association of its possible values. Through variables, a large spectrum of operations can be accomplished, according to their nature and their structure. Therefore, we can state that data can have a certain type.

Certain lexical conventions exist in terms of declaring both constants and variables:

      • ALL_CAPS for constants
      • lowerToUpper for variables with highly suggestive names;

Expressions

Most programming languages define expression following a set of syntactic rules, which, in general go like this:

  1. Any constant is an expression;
  2. Any variable is an expression;
  3. If E is an expression, then (E), -E, +E, F(E) sare also expressions, where F is the name of an applicable function in regards to E;
  4. If E1 and E2 are expressions then so are E1+E2, E1-E2, E1*E2, E1/E2 .

So now, based on the previously mentioned rules we can construct highly complex expressions starting from constants and variables.  Thus, we consider the entity (3+A)*(5/(-B+C)) and we check if it’s an expression or not. Let’s assume that A,B and C are integer variables. Seeing as 3 is a constant, according to the first rule, it is an expression. A, being a variable, is also an expression according to rule 2. Now, if we apply rule 4, 3+A is an expression and (3+A) is also an expression due to rule 3. Following the multiplication (*) sign we have: 5 as an expression due to it being a constant, B,C then –B and –B+C are also expressions. Eventually, according to rule 3 again, (-B+C) is also an expression, thus leading to (5/(B+C)) being an expression and validating the whole statement as being an expression.

Data are characterized by:

  • Type
  • Name
  • Value
  • Access Level
  • Lifetime
  • Operators
  • Function calls

Variables in C++

Variables declaration

    type variable;

    type var1, var2,, varn;

    type variable = constant_expression;

Global and local variables

Global variables: their declaration is made at the beginning of the program, outside any function

Local variables: their declaration is made inside the body of a function, at the beginning.

Exemplification

char c;
signed char sc;

int a, b;
a = b = 5;

int i;
int sum = 0;
long j;

float x1,,x2, x3;
float pi = 3.14;
double y;

int square(int y)
{  
      int x;  x=y*y; 
      return x; 
}
Variable x is characterized by:
  • Type = int
  • Name = x
  • Value = 4
  • Access level: square function
  • Lifetime = during one function call

Variable assignation

variable = expression;

OR

Lvalues (left-side) = Rvalues (right-side)

  • Lvalues are variables
  • Rvalues are expressions

Example

In this assignation

distance = rate * time;

we have: Lvalue: „distance” and Rvalue: „rate * time”

Counterexample for Lvalue: 5+5, “str”, const int i

When assigning, two other problems are raise, but we will talk about them later:

  • Compatibility
  • Conversions

Variable types and their visibility

Data types

Data types means a set of values, together with the operations that can be executed with them.  At declaration, each variable will be associated with a certain type. A constant type can be implicitly defined from the constant value, or it can be explicitly specified, similarly to variables. Thus, if K constant has the numeric value 7, we can say that it is an integer, or a float, not a logical type or a string array.

However, there are languages that have some conventions, for example, any number different from zero is considered to be True, as a Boolean variable, whereas zero has the value False.

Some programming languages allow declaration of variables without specifying their type, thus considering having a general type. So, when the variable will be used, it will be assigned the most adequate type, in that situation. If a variable X is declared, and at some point the value 3 is assigned to it, its type would be considered numeric. Subsequently, if X will be assigned the value “abc”, that means a string array, then, X will be a string array.

Expressions are formed based on constants and variables. Of course, when forming expressions, operators will be used, also those functions, allowed by the value types they operate on. Small expressions can lead to large expressions, that are growing in complexity.

Type domain (object collection) – the set of values for which a certain memory representation was used

Type operations = operations which can be executed using values of that data type

Data types categories:

  • Standard data types
  • Low-level structured data types – operations are executed at component level
  • High-level data types – operations are implemented by user algorithms

Standard data types in C++

  • Character types:  char types , signed char, unsigned char
  • Integer types: character types,signed integers, unsigned integers, enum types
  • Float types: integer and float types
  • Arithmetic types: float and integer types
  • Basic types: character, unsigned and signed integers, float
  • Void types: represents a void set

(32 bit)

Equivalent data types

signed short int ≡ short
unsigned short int ≡ unsigned short
signed int ≡ int
unsigned int ≡ unsigned
signed long int ≡ long
unsigned long int ≡ unsigned long

Derived data types

Those are built from objects, incomplete types and functions

  • array type of T (elements of type T)
  • structure type
  • union type
  • function type, derived from the returned type T , parameters number and types (function that returns T)
  • pointer type, derived from a referenced type (function type, object type, incomplete type). Pointers type values are referenced to an entity of the type referenced. (pointer to T)
  • scalar type: arithmetic and pointer types
  • aggregate types: tablouri şi structuri
  • Un tablou de dimensiune necunoscută, o structură sau uniune cu conţinut necunoscut sunt tipuri incomplete

Integer types

Integer constants

  • Octals: preffix 0 (zero), for example: 032 = 26   și    077 = 63
  • Hexadecimals: preffix 0x or0X, for example: 0x32 = 50 și 0x3F = 63
  • „long” integers: have the suffix l or L, for example: 2147483647L și 0xaf9Fl = 44959
  • „unsigned” integers have the suffix u or U, for example: 345u și 0xffffu = 65535
  • Characters with apostrophe: ‘A’, ‘+’, ‘n’
  • Decimal characters: 65, 42
  • Octal characters: ’\101’, ‘\52’
  • Hexadecimal characters: ‘\x41’, ‘\x2A’
  • Special characters – escape sequences

Operations and functions for integer types

Operations for integer types: + – * / % == != < <= > >= ++ —

Functions:

  • from float types
  • from library: tolower, toupper, isalpha, isalnum, iscntrl, isdigit, isxdigit, islower, isupper, isgraph, isprint, ispunct, isspace

Operators

Operators ++ and —

They are applied only to an expression that represents a memory object (L-value):

Other examples:

++5 –(k+1) ++i++ have no sense
(++i)++ has sense

Float type (real)

float

  • Simple precision real numbers
  • sizeof(float) = 4
  • 10^-37<=abs(f)<=10^38
  • 6 significant digits

double

  • Double precision real numbers
  • sizeof(double) = 8
  • 10^-307<=abs(f)<=10^308
  • 15 significant digits

long double

  • „Extra” double precision real numbers
  • sizeof(long double) = 12
  • 10^-4931<=abs(f)<=10^4932
  • 18 significant digits

Limits are found in <float.h>

Operations: + – * / == != < <= > >=

Real constants

  • Real numbers are implicitly double:
     125.435 1.12E2 123E-2 .45e+6 13. .56
     1.12E2 = 1.12 x 102 = 112
     123E-2 = 1.12 x 10-2 = 1.23
     .45e+6 = 0.45 x 106 =450000
     13. = 13.00 şi .56 = 0.56
  • To be float it must have suffix f or F
     .56f 23e4f 45.54E-1F
     23e4f = 23 x 104 = 230000.00
  • To be long double it must have suffix l or L
     123.456e78L

Functions (in library math.h):

sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, exp, log, log10, pow, sqrt, ceil, floor, fabs, ldexp, frexp, modf, fmod.

Booleene data (logical)

Bool type

  • Value domain: {false, true}
  • false = 0
  • true = 1, but also any non-null integer
  • Operations: ! && || == !=
  • Possible declarations:
     bool x = 7; // x becomes “true”
     int y = true; // y becomes 1

Logical expressions

relational_expression ::= expr < expr | expr > expr | expr <= expr | expr >= expr | expr == expr | expr != expr expresie_logica ::= ! expr | expr || expr | expr && expr

The value of relational expressions

Logical negation

! 0 = 1, ! any_nr_different_from_0 = 0

Logical disjunction. The value of logical expressions ||

Logical conjunction. The value of logical expressions &&

Examples

A condition of this type a ≤ x ≤ b is written in C++ as follows:

(x >= a) && (x <= b) (a <= x) && (x <= b)

A condition of this type a > x or x > b is written in C++ as follows:

(x < a) || (x > b) !(x >= a && x <= b)

De Morgan’s laws

  • ! (A && B) is equivalent with !A || ! B
  • ! (A || B) is equivalent with ! A && ! B

Void type

  • Conversion of an expression in void type means that its value is ignored
  • Used for pointer type; no type control is made to a pointer of type void
  • Used for functions with no returned value or for functions without parameters
  • It is an incomplete type which cannot be assigned a value

Structures. Using typedef 

Typedef is a mechanism with which a type is associated to an identifier:

typedef char big_letter;
typedef short age;
typedef int vector[20];
typedef char string[30];
typedef float matrix[10][10];
typedef struct { double re, im; } complex;

That identifier can be used to declare variables:

big_letter u, v=‘a’;
age v1, v2;
vector x; string s;
matrix a;
complex z;

or functions

complex sum(complex z1, complex z2) { 
  complex z; 
  z.re=z1.re+z2.re; z.im=z1.im+z2.im; 
  return z;
}

Conditional operator ? :

Syntax

exp1 ? exp2 : exp3

Semantics 

  • exp1 is evaluated
  • If exp1 has a true value (non-null), then the value of the expression is the value of exp2; exp3 is not evaluated
  • If exp1 has a false value (null), then the value of the expression is the value of exp3; exp2 is not evaluated

Operator ?: is associative

Examples

x >= 0 ? x : y
x > y ? x : y
x > y ? x > z ? x : z : y > z ? y : z
game=(response==’1’)?SimpleGame();DoubleGame();
#include <iostream>
using namespace std;
void main(){
   int a=1, b=2, c=3;
   int x, y, z;
   x = a?b:c?a:b;
   y = (a?b:c)?a:b; /* left association */
   z = a?b:(c?a:b); /* right association */
   cout<< "x=" << x << "\ny=" << y << "/nz="<< z;
}
/* x=2 y=1 z=2 */

Comma operator ,

Syntax

comma_expression ::= expression, expression

Semantics

  • The first expression is evaluated, then the second one.
  • Valoarea şi tipul întregii expresii este valoarea şi tipul operandului drept.
  • The value and type of the whole expression is the value and type of the right operand.

Example

a = 1, b = 2;
i = 1, j = 2, ++k + 1;
k != 1, ++x * 2.0 + 1;
for(sum = 0, i = 1; i <= n; sum += i, ++i);

Operator sizeof()

sizeof() is a single operator that allows finding out the number of bytes an object can be represented on (a type or an expression)

Examples:

sizeof(int), sizeof(double);
sizeof(b*b-4*a*c), sizeof(i);
sizeof(char)<=sizeof(short)<=sizeof(int)<=sizeof(long)
sizeof(signed)=sizeof(unsigned) = sizeof(int)
sizeof(float)<=sizeof(double)<=sizeof(long double)

Use:

#include <iostream>
using namespace std;
void main(){
  int x = 1; double y = 9; long z = 0;
  cout << "Operator sizeof()\n\n\n";
  cout << "sizeof(char) = " << sizeof(char) << endl;
  cout << "sizeof(int) = " << sizeof(int) << endl;
  cout << "sizeof(short) = " << sizeof(short) << endl;
  cout << "sizeof(long) = " << sizeof(long) << endl;
  cout << "sizeof(float) = " <<sizeof(float) << endl;
  cout << "sizeof(double) = " << sizeof(double) << endl;
  cout << "sizeof(long double) = " << sizeof(long double) << endl;
  cout << "sizeof(x +y + z) = " << sizeof(x+y+z) << endl;
}

The result of execution in Visual C++:

Operator sizeof()

sizeof(char) = 1
sizeof(int) = 4
sizeof(short) = 2
sizeof(long) = 4
sizeof(float) = 4
sizeof(double) = 8
sizeof(long double) = 8
sizeof(x + y + z) = 8

Table with operators priority and associativity

Rules for implicit conversion

In the absence of an unsigned, the objects are converted to the „highest” type in the list (descending):

long double, double, float, long int, int

Rules for unsigned operands are depending on implementation.

Conversion to unsigned is made only when needed(I.E. the value from unsigned does not „fit” in the other operand)

The rule “integer promotion” : Operations are made at least in int, so char and short are „promoted” to int.

To an assignation (v = exp) the type of the right term is converted in the right term’s type (which is the result’s type).

WARNING! Things that can happen:

  • Loss of precision (double ->float ->long int)
  • Loss of significant bits (long ->int)
  • Indeterminations

Examples of implicit conversions

#include <iostream>
using namespace std;
int main(void){
   char c1 = -126, c2;          /* c1 = 10000010    */
   unsigned char c3, c4 = 255;  /* c4 = 111111111   */
   short s1, s2 = -32767; /* s2=10000000 00000001   */
   short s3 = -1, s4;     /* s3 = 11111111 11111111 */
   s1 = c1;
   cout << "c1=" << (int)c1 << " s1=" << s1 << endl;
   c2 = s2;
   cout << "c2=" << (int)c2 << " s2=" << s2 << endl;
   c3 = s3;
   cout << "c3=" << (int)c3 << " s3=" << s3 << endl;
   s4 = c4;
   cout << "c4=" << (int)c4 << " s4=" << s4 << endl;
   return 0;
}

Example (execution result)

 

 

Forcing type – cast

  • Explicit conversion to nametype type can be made as follows::

(nametype) expresie

Example:

(long)(‘A’ + 1.0)
(int)(b*b-4*a*c)
(double)(x+y)/z
(float)x*y/z
x / (float)2

cast example

#include <iostream>
using namespace std;
int main(void){
   int i, j; double x, y, z, t;
   i = 5/2; x = 5/2;
   y = (double)(5/2);  j = (double)5/2;
   z = (double)5/2;   t = 5./2;
   cout << i << ", " << x << ", ";
   cout << y << ", " << j << ", ";
   cout << z << ", " << t << ", " << endl;
   return 0;
}
/* 2, 2, 2, 2, 2.5, 2.5 */

Files in library relative to types

<limits.h>

  • for integer types
  • min/max integer: INT_MIN, INT_MAX
  • Number of bits per character CHAR_BIT
  • Etc.

<float.h>

  • for float types:
  • Maximum exponent
  • Decimal precision, etc.

<stdlib.h>

  • has conversion functions:
  • Character array in int: atoi(const char*)
  • Character array in int float: atof(const char*)
  • Knowledge assessment test

Revision

Student discussion

Knowledge assesment test

Formular Google Forms

Plan

  • Input-output
  • Instructions
  • Functions

Input / output

General formula
cin >> var;   /* reads var from cin */

  • Arithmetic types, character arrays can be retrieved
cout << expr;   /* writes expr to cout */
  • Arithmetic types, character arrays, pointers of any type except char can be transferred.
  • Multiple operations of the following type are posibile:
cin >> var1 >> var2 ... >> varN; 

cout << var1 << var2 ... << varN;

Input/ output: example- characters

Input/ output: example– ASCII codes

On the blackboard there are some explanations regarding ASCII codes and sorting character arrays in different programs.

Special codes: 7 (BELL), 10 LF (Line Feed), 13 CR (Carriage Return), 27 ESC (Escape), 32 Space, 33 !, …., 48 ‘0’, …, 65 ‘A’, 66 ‘B’,… , 97 ‘a’, 98 ‘b’,… .

Statements

Expression statement

Syntax:

Semantics:

  • The expression is evaluated.
  • If an expression is in the form of an assignment statement, variable=expression, then the variables gets the value of the right statement, the old value being lost.
  • If an expression is in the form variable op = expression, this is equivalent to variable=variable op expression, where op is an operator from the {+, -, *, /, %} set.
  • If an expression is in the form variable++ or ++variable, this is equivalent to variable=variable+1.
  • If an expression is in the form variable– or –variable, then this is equivalent with variable=variable-1.

Example:

a = b;
a + b + c;
;
cout << a;
sizeof(int);

Block statememt

Syntax:

  • Groups instructions/declarations in an executable unit.
  • A composed instruction is itself an instruction: where an instruction may appear, is it correct to have a composed instruction.

Semantics:

  • Every instruction/declaration is executed one time, from up to down and from left to right.
  • There is no return to any of the instructions/declarations from before.

Examples:

{
  int a=3, b=10, c=7;
  a += b += c;
  cout << a << ", " << b <<  ", " << c; // ?, ?, ?
}

if (x > y){
   int temp;
   temp = x; x = y; y = temp;
   cout << x << y;
}

{
   int a, b, c;
   {
      b = 2; c = 3; a = b += c;
   }
   cout << "a= " << a <<endl;
} // ?

Conditional statements: if and if-else

Syntax:

if_statement ::=  if (<boolean_expression>)
               {<statement1>;}

if_else_statement ::=  if (<boolean_expression>)
                     {<statement1>;}
                    else
                     {<statement2>;}

boolean_expression is build using:

  • Arithmetic expressions
  • Comparators:  ==, !=, <, <=, >, >=
  • Logical connectors: &&, ||, !

Semantics:

  • The boolean_expression is evaluated (one single time).
  • If this is true, then statement1 , is executed.
  • If this is false, then, if else branch is present, statement2 is executed.

Examples:

if(length== width) 
  squareArea= length*width;

if (a % 2) if (b % 2) p = 1; else p = 2; // with whom is grouped „else”?

if(a%2) { if(b%2) p = 1;} else p = 2;

if (firstNumber< secondNumber) 
  minimum = firstNumber;
else
  minimum = secondNumber;

int first, second, third, fourth, maximum;
if(first>second)
   if(third>fourth)
      if(first>third) maximum = first;
      else maximum = third;
   else
      if(first>fourth) maximum = first;
      else maximum = fourth;
else
   if(third>fourth)
      if(second>third) maximum = second;
      else maximum = third;
   else
      if(second>fourth) maximul = second;
      else maximum = fourth;

“Dangling else” problem

Rule:

The rule is: else is attached to the closest if.

int a=1, b=2; // b=3 if (a == 1) if (b == 2) // b=2 cout << „*****\n”; else cout << „ooooo\n”;

  • Do not let the code trick you!
  • Be careful to the differences between equality and assignment operators.
if ( condition-1 ) {
      instructions-1;
  }
else if ( condition-2 ) {
      instructions-2;
  ...
  }
else if ( condition-n ) {
      instructions-n;
  }
else {
      instructions-for-the-rest-of-possibilities;  
  }

Example:

int main(void){
    float operand1, operand2, rezultat;
    char operator;
    cout << "Expression:(number operator number – FARA SPATII)\n";
    cin >> operand1 >> operator >> operand2;
    if(operator == '+')
          result= operand1+operand2;
    else if(operator == '-')
          result= operand1-operand2;
    else if(operator == '*')
          result= operand1*operand2;
    else if(operator == '/')
          result= operand1/operand2;
    else{
         cout << "Error in writing the expression!";
         return 1;
    }
    cout << "The result is: " << result<< "\n";
    return 0;
}

Switch statement

Syntax:

switch (expression)
{
  case constant1:
     instruction group 1;
     [break;] (break is optional)
  case constant2:
     instruction group 2;
     [break;]
  .
  .
  .
  [default:
     implicit group of instructions] (default is optional)
}

Semantics:

  • expression is evaluated.
  • If it has the value constant1, then the group of instructions 1  is executed, eventually the group of instructions 2, etc., until the first break.
  • If it has the value costant2, then the group of instructions2 is executed etc., until the first break.
  • In case the expression is not equal with contant1, nor constant2, and the implicit group of instructions is present, then that is the thing that gets executed.

Example:

  • The value of expression, which is of type int, is compared with the constants.
  • In case of equality, the required instruction and the ones that follow are executed. There is the posibility of exiting with the break instruction.
  • If the value determined is different from all of the specified constants, the default instruction is executed, which appears only a single time, not necessarily at the end. If default is missing, switch is exited.
  • The constant’s values must be different; their order is not important.
  • The braces that group the case sets are mandatory. After each case, more instructions can appear without them being grouped in braces.
int i;
cin >> i;

switch(i){
  case 1: cout << " 1";
  case 2: cout << " 2";
  case 3: cout << " 3"; // break;// ???
  case 4: cout << " 4";
  default: cout << " blabla! ";
//3

char eval;
cin >> eval;
switch (eval) {
  case 'A':
  case 'a': 
  cout << "Excellent: you got an \"A\"!\n";     
  break;
  case 'B':
  case 'b':     
  cout << "Good: you got a \"B\"!\n";     
  break;
  }

While statement

Syntax:

Semantics:

  • The expression (expresia)  is evaluated (condition).
  • If it is null/not true, we go to the next_instruction (instructiunea_urmatoare).
  • If it is true, the instruction is executed and the cycle is retaken, testing again de value of expression (!=0) etc.
  • So, while expression  is true, the instruction is executed.
int n, i=1, factorial=1;
cin>>n;
while (i++ < n)
      factorial *= i;
cout<<factorial;

do-while statement

Syntax:

Semantics:

  • instruction (instructiune) is executed.
  • condition (conditie) is evaluated: if its value is nonzero, the control is transferred back to the beginning of do..while instruction; if the value is null, next_instruction(instructiunea_urmatoare) is executed.

Thus, instruction (instructiune)  is executed one or more time(s).

Example

unsigned long n;
  do {
    cout << "Enter number (0 to end): ";
    cin >> n;
    cout << "You entered: " << n << "\n";
  } while (n != 0);
  return 0;

 

Example – calculator

int main(void){
    float operand1, operand2, rezultat;
    char operator, raspuns;
    int ERROR;
    cout << "Calculator pentru expresii de forma \n operand1 operator operand2\n";
    cout << "Folositi operatorii + - * / \n";     
do{
       ERROR = 0;
       cout << "Dati expresia: ";
       cin >> operand1 >> operator >> operand2;
       switch(op){
         case '+': rezultat = operand1+operand2; break;
         case '-': rezultat = operand1-operand2; break;
         case '*': rezultat = operand1*operand2; break;
         case '/': if(y != 0) rezultat = operand1/operand2;
                   else {cout << "Impartire prin zero!\n"; ERROR = 1;}
                   break;
         default : {cout << "Operator necunoscut!\n"; ERROR = 1;}
       }
       if(!ERROR)
          cout << operand1 << " " << operator << " " << operand2 << " = " << rezultat;
       cin.sync();
       do{cout << "\n Continuati (d/n)?"; raspuns = getchar();
       } while (raspuns != 'd' && raspuns != 'n');
  } while (raspuns != 'n');
  cout << "La revedere!\n";
  return 0;
}

for instruction

Syntax:

One, two or all three expressions can be missing, but the two separators (;) are mandatory.

Semantics

  • If instructiune does not contain continue and expr-cond is present, then for is equivalent to: expr-init;
while(expr-cond){
   instructiune;
   expr-in/decrementare;
}
next_instruction (instructiunea_urmatoare)
  • If continue exists, then this transfers the control to expr-in/decremenatare.
  • expr-init is evaluated–  in general, this is used for initializing the iteration.
  • expr-cond is evaluated- in general this is a logical expression which is used for iteration control. If its value is nonzero (true), the loop’s body do is executed (instructiune), expr-in/decrementare is evaluated and the control is passed to the beginning of the do loop, without evaluating expr-init.
  • In general expr-in/decrementare makes the transition to the next iteration: modifies a variable that is a part of the expr-cond.
  • The process continues until the value of expr-cond  is null (false). The control is transferred to the next instruction (the one after for)

Examples:

i = 1;
suma = 0;
for(;i <= N;++i) suma += i;

i = 1;
suma = 0;
for(;i <= N;) suma += i++;

i = 1;
suma = 0;
for(;;) suma += i++; // Bucla infinita

Sequence break instructions

  • break;
    • refers to the closest loop or switch instruction.
    • it produces the exit from loop or switch and transfers the control to the next instruction.
  • continue;
    • refers to the closest loop (for, while, do..while).
    • interrupts the current iteration execution and transfers the control to the next iteration.
  • goto;
    • Allows a jump to another program section, identified by the beginning point.Permite saltul la o anumită secțiune din program, identificată prin punctul de începere.
  • return expr;   or return;

Examples:

int n;
  for (n=10; n>0; n--)
  {
    cout << n << ", ";
    if (n==3)
    {
      cout << "countdown aborted!";
      break;
    }
  }
for (int n=10; n>0; n--) {
    if (n==5) continue;
    cout << n << ", ";
  }
  cout << "FIRE!\n";
int n=10;
  loop:
  cout << n << ", ";
  n--;
  if (n>0) goto loop;
  cout << "FIRE!\n";
  return 0;

int i, suma=0;
for(i = 1; i<=N; i++){
   if(i%3 != 0) continue;
   suma+=i;
   }
cout << “suma = ” << suma; /* suma multiplilor de 3 până la N */

Iteration instructions – recommandation

  • For the control expression of the iteration, relational operators are recommended instead of th equality ones.
int main(){
   int contor = 0;
   double suma = 0.0, x;
   for(x = 0.0; x != 9.9; x += 0.1){
       suma += x; 
       ++contor;
   }
   cout << "suma = " << suma << ", contor= " << contor << "\n";
   return 0;
}

  • Folositi x < 9.9 in loc de x != 9.9