Lab #2.1. Compiler error messages, text literals in C++

  1. Create working directory (<WORK>), and copy both lab2.1.cpp and lab2.2.cpp into it.
  2. Open lab2.1.cpp, and compile and run it.
  3. See if everything works OK.
  4. remove semicolon (;) after endl.
  5. Compile and observe the error message. See, how error message is displayed “Compile log” window (press F2 to show/hide it).

  1. Put back the deleted semicolon, and compile and run again.

(Semicolon is put after almost each line in C++.)

7.     Change endl to uppercase ENDL.

8.     Compile and observe the error message.

C:\lab\lab02\lab2.1.cpp: In function 'int main()':

C:\lab\lab02\lab2.1.cpp:6:32: error: 'ENDL' was not declared in this scope

     cout << "Hello, world!" << ENDL;

                                ^

Process terminated with status 1 (0 minute(s), 0 second(s))

1 error(s), 0 warning(s) (0 minute(s), 0 second(s))

 

  1. Correct the error, compile and run.

(C++ ir case sensitive programming language.)

10.  Change text “Hello, World!” to uppercase “HELLO, WORLD!”

11.  Compile and run (should work correctly).

(Case sensitivity matters for identifiers, not text literals.)

12.  In text “HELLO, WORLD!”, put the word WORLD in double quotes, and put backslash(\) before comma:

cout << "HELLO\, "WORLD!"" << endl;

  1. Compile and get error message, like:

C:/Darbi/prg/lab1.1.cpp:6:13: warning: unknown escape sequence '\,'

C:/Darbi/prg/lab1.1.cpp: In function `int main()':

C:/Darbi/prg/lab1.1.cpp:6: parse error before `!' token

(Text literals in C++ are put in double quotes, however not all symbols can be put there directly. There are special symbols (like single quotes, double quotes, backslash) to be preceded by backslash. In addition, ‘\n’ denotes new line, but ‘\t’ – tab.)

  1. Add backslash ‘\’ before each of the 3 symbols added before, and also character sequence ‘\n’ after comma.

cout << "HELLO\\,\n \"WORLD!\"" << endl;

  1. Compile and run:

HELLO\,

 "WORLD!"

Observe the difference between text in the program and text, which is printed out (escape symbol ‘\’ is not printed).

 

 

Lab #2.2. Values of data types ‘int’ and ‘double’, mathematical division and integer division in C++

1.     Open lab2.2.cpp, and compile and run.

  1. Instead of
    cin >> x >> y;
    insert following two lines:

x = 12;

y = 7;

3.     Instead of
z = x + y;
insert
z = x / y;

4.     The text “sum” change to “result”.

The program now looks like this:

#include <iostream>

using namespace std;

 

int main ()

{

    int x, y, z;

    cout << "Input 2 integer values:" << endl;

    x = 12;

    y = 7;

    z = x / y;

    cout << "Result is " << z << endl;

    return 0;

}

5.     Compile and run and get 1.

(This was integer division: operator “/” denotes integer division if both operands are integers).

6.     Change line
int x, y, z;
to
float x, y, z;

This sets data types of variables x, y, z to floating point number.

7.     Compile and run and get 1.71429

If any of operands is floating point number (i.e., not an integer), then ‘/’ denotes mathematical division.

8.     Change line
float x, y, z;
to two lines

int x, y;

float z;

Operands x un y are again integers, and result is 1.

9.     Change
z = x / y;

to
z = x / 5;
(5 instead of y)

10.  Result is 2 – numbers without decimal points in the program text are recognized as integers, so integer division is performed.

11.  Change
z = x / 5;

to
z = x / 5.0;

12.  Result is 2.4 (number 5.0 contains decimal point, thus is recognized as floating point number – to be more precise, of data type ‘double’)

 

 

Lab #2.3. Formatted input in C++

13.  Open file lab2.3.cpp and compile.

  1. Run the program with numbers 1.23 and 4.56, with pressing ENTER between them.
  2. Run the program with the same input but putting space between numbers.

Output look a little bit strange (the second number is “required” after it is input):

Input numeric value #1

1.23 4.56

Output: 1.23

Input numeric value #2

Output: 4.56

This happens because the input is not carried out directly from console to the variable, the process is roughly speaking – two-step. At the first step all the input information goes to a memory buffer, and this occurs until ENTER is reached. At the second step, operator >> reads information from the buffer and tries to translate information for the variable specified. A buffer is part of so called input stream (the name of included library <iostream> stands for input/output stream).

16.  Let’s compromise the program by inputting letter instead of number: a <ENTER>

Input numeric value #1

a

Output: 0

Input numeric value #2

Output: 0

or (it depends on the compiler)

Input numeric value #1

a

Output: 987

Input numeric value #2

Output: 987

What happens? If we enter a text which cannot be interpreted as number: (a) the first operator >> failed, and the value of the variable d either remained 987 or was set to 0 (depending on the compiler); (b) The second operator was ignored. This happened because after a fail, the input object had been blocked, and thus before unblocking it all the input commands are ignored.

17.  Let’s adapt our program to this situation. Before the second input command
cin >> d;
the following code block:

    if (!cin.good())

    {

        cin.clear();

        cin.ignore (256, '\n');

    };

18.  Run it with: a <ENTER> 1.23 <ENTER>.

Input numeric value #1

a

Output: 0

Input numeric value #2

1.23

Output: 1.23

The added code means that if there was something bad with the input (exclamation mark (!) means NOT), then we unlock the cin object using clear, and empty it using ignore. I we had not emptied it, it would have tried to read a number (for the second input operator) from the same position in buffer.

19.  Run program with: abc567 <ENTER> 1.23 <ENTER>.

Input numeric value #1

abc567

Output: 0

Input numeric value #2

1.23

Output: 1.23

20.  In the line

        cin.ignore (256, '\n');

change 256 to 1, and get:

        cin.ignore (1, '\n');

21.  Run program with: a12345 <ENTER>.

Input numeric value #1

a12345

Output: 0

Input numeric value #2

Output: 12345

Observe that ignore ignored just one character thus getting to 1.

A simplified scheme of two-step input machanism.

 

 

 

Lab #2.4. Formatted output C++

In this section, some capabilities of formatted output are discussed.

1.     Open file lab2.4.cpp and compile.

  1. Run the program.

The program prints out the number 123.46589, rounded to 6 significant digits (default for C++): 123.466.

  1. Change the number in the program to 1.2346589 (move decimal point two positions left).
  2. Compile and run.

The program prints it as 1.23466 (again we have 6 significant digits).

5.     Before line
cout << d << endl;
insert line:
cout.precision (3);

Precision (here: number of significant digits) is set to 3.

6.     Compile and run.

The program prints it as 1.23 (i.e., rounded to 3 significant digits).

7.     We may want to fix scale (decimal digits after decimal point) instead of significant digits, if so – insert following line before printing:
cout.setf (ios::fixed);

Now we have the main function as displayed here:

int main()

{

    double d = 1.2346589;

    cout.precision (3);

    cout.setf (ios::fixed);

    cout << d << endl;

    return 0;

}

8.     Compile, run and get result: 1.235 (scale: 3).

9.     Change line
cout << d << endl;
to

cout << d << "#" << endl;

10.  Compile, run and get result:  1.235#

11.  After line
cout << d << "#" << endl;
insert a similar line:

cout << d << "@" << endl;

12.  Compile, run and get result: 

1.235#

1.235@

13.  Before line
cout << d << "@" << endl;
insert:

cout.unsetf (ios::fixed);

Now we have the main function as displayed here:

int main()

{

    double d = 1.2346589;

    cout.precision (3);

    cout.setf (ios::fixed);

    cout << d << "#" << endl;

    cout.unsetf (ios::fixed);

    cout << d << "@" << endl;

    return 0;

}

14.  Compile and run.

The second number was printed with 3 significant digits (not scale 3):

1.235#

1.23@

15.  Insert the following line before first printing line:

cout.width (7);

16.  Compile, run and get result (observe first number printed indented):

  1.235#

1.23@

 (1) The first number is placed in area of 7 characters, right aligned (default for numbers) and the rest of positions (in the left) are left blank (filled with spaces), (2) The command width (unlike commands precision or fixed or scientific) has effect on the next printing command (i.e., << value) only.

17.  Before the second printing line, insert:

cout.width (8);

18.  After the declaration line of the variable d, insert:

cout.fill ('-');

Now we have the main function as displayed here:

int main()

{

    double d = 1.2346589;

    cout.fill ('-');

    cout.precision (3);

    cout.setf (ios::fixed);

    cout.width (7);

    cout << d << "#" << endl;

    cout.unsetf (ios::fixed);

    cout.width (8);

    cout << d << "@" << endl;

    return 0;

}

19.  Kompilçt un darbinât programmu, iegűstot rezultâtu

--1.235#

----1.23@

With the command fill we changed the filling symbol to ‘-’ (from the default filling symbol – space (‘ ’)).

20.  Before the first printing line, insert:

cout.setf (ios::left);

21.  Compile, run and get result:

1.235--#

1.23----@

  1. Open file lab2.5.cpp, compile and run.

Observe the result – so called manipulators can be used as alternative to formatting commands, in that case the library <iomanip> should be included.

 

 

Lab #2.5. Arithmetic

Create a C++ program using arithmetic operations (+ ,- ,* , /, %). String processing operations not allowed.

 

Task #1. Given natural number N, greater than or equal to 100. Use arithmetic operations to get last 3rd digit. Example: N=123456; Output=4.

 

Task #2. Given two whole numbers M and N. Without applying integer division operation (int / int) and remainder operation (%), calculate (1) result of integer division, (2) remainder of integer division. It is recommended to use additional mathematical functions floor(∙) and ceil(∙), found in libraries <cmath> or <math.h>.

 

 

Lab #2.6. Simple programs in C++

Simple program for calculating squares (io.cpp):

// Computing square simple

#include<iostream>

using namespace std;

int main()

{

    double valnum;

    cout << "Input number: ";

    cin >> valnum;

    cout << "Number " << valnum << " squared is " << valnum*valnum << endl;

}

 

Simple program for calculating squares with input error checking (ioplus.cpp):

// Computing square with input control

#include<iostream>

using namespace std;

int main()

{

    double valnum;

    cout << "Input number: ";

    cin >> valnum;

    if (cin.good())

    cout << "Number " << valnum << " squared is " << valnum*valnum << endl;

    else

        cout << "Input error -- number required." << endl;

}

 

Simple program for calculating squares with repeated execution (iorepeat.cpp):

// Computing square with repeating

#include<iostream>

using namespace std;

int main()

{

    int ok;

    do

    {

        double valnum;

        cout << "Input number: ";

        cin >> valnum;

               cout << "Number " << valnum << " squared is " << valnum*valnum << endl;

        cout << " Continue (1) or close (0)?" << endl;

        cin >> ok;

    } while (ok == 1);

}

 

Simple program for calculating squares with repeated execution and input error checking (iorepeatplus.cpp):

// Computing square with repeating and input control

#include<iostream>

using namespace std;

int main()

{

    int ok;

    do

    {

        double valnum;

        cout << "Input number: ";

        cin >> valnum;

        if (cin.good())

                     cout << "Number " << valnum << " squared is " << valnum*valnum << endl;

        else

        {

            cin.clear();

            cin.ignore(256,'\n');

            cout << "Input error -- number required." << endl;

        }

        cout << " Continue (1) or close (0)?" << endl;

        cin >> ok;

    } while (ok == 1);

}

 

 

Lab #2.7. Simple programs in JavaScript (to illustrate input/output differences with C++)

Simple program for calculating squares (ioprompt1.html), using alert for output:

<!-- Computing square -->

<script>

   var valnum = Number(prompt("Input number",""));

   var outputtext = "Number " + valnum + " squared is " + (valnum ** 2);

   alert(outputtext);

</script>

 

Simple program for calculating squares (ioprompt2.html), using console.log for output:

<!-- Computing squsre -->

<script>

   var valnum = Number(prompt("Input number",""));

   var outputtext = "Number " + valnum + " squared is " + (valnum ** 2);

   console.log(outputtext);

</script>

 

Simple program for calculating squares (iohtml.html), using html features for input/output:

<!-- Computing square -->

<html>

   <p id="text1"><b>Computing square</b></p>

   <p id="text2">Input number: </p>

   <input type="number" id="idinput" value="0"/>

   <p></p>

   <button onclick="main()">Compute square</button>

   <p id="idoutput"></p>

   <script>

         function main() {

               var valtxt = document.getElementById("idinput").value;

               var valnum = Number(valtxt);

               var outputtext = "Number " + valnum + " squared is " + (valnum ** 2);

            document.getElementById("idoutput").innerHTML = outputtext;

         }

   </script>

</html>

 

Lab #2.8. Formatted input Python

23.  Open file lab2.3.py.

d = float(input("Input numeric value: "))

print("Output:",d)

  1. Run program and input 1.23, program prints:

Output: 1.23

In Python, console input is performed with function input, and input data are in text form, the value from text should be explicitly converted to the needed type (here float). Instead of specifying a concrete type, function eval can be used:

d = eval(input("Input numeric value: "))

print("Output:",d)

25.  Let’s return to float.

d = float(input("Input numeric value: "))

print("Output:",d)

26.  Run program, inputing non-float data, e.g., abc:

Input numeric value: abc

27.  Program crashes:

Traceback (most recent call last):

  File "D:\darbi\Dropbox\acad\courses\prog\proglab\lab02\py\lab2.3.py", line 1,

in <module>

    d = float(input("Input numeric value: "))

ValueError: could not convert string to float: 'abc'

Observe the error type here: ValueError.

28.  Let’s create a smarter program (additionally, d is initialized by 789) (lab2.3a.py):

d = 789

try:

    d = float(input("Input numeric value: "))

except ValueError:

    print("Value error!")

print("Output:",d)

Error processing is performed by the try-except block.

29.  Using one operationinputalso several values can be input (The following program takes several values and prints their squares) (lab2.3b.py):

text = input("Input several integer values: ")

mylist = text.split()

print(mylist)

for m in mylist:

    i = int(m)

    print(i,i*i)

Function split splits the text (text) into list of values (mylist).

30.  Program in action:

Input several integer values: 2 8 11

['2', '8', '11']

2 4

8 64

11 121

In the printout, we can see that mylist is a list of text values (in quotes).

 

 

Lab#2.9. Formatted output in Python

31.  Open file lab2.4.py.

  1. Run the program.

Program prints 123.46589, all digits after decimal point printed.

  1. To restrict amount of digits after decimal point, we use function format (formatting consists of the formatting text (template) and the list of values to formaty, 0 denotes the value #0, in our case, the only one):

d = 123.46589

print("{0:.3f}".format(d))

  1. The program prints the number (3 digits after decimal point):

123.466

These 3 digits are specified by formatting information „.3f”.

35.  If we remove „f”:

d = 123.46589

print("{0:.3}".format(d))

36.  then number 3 denotes amount of significant digits (not after decimal point):

1.23e+02

It means 1.23*102.

We can format several values of different types in one line (lab2.4a.py):

a = 456

b = 123.46589

c = "Hallo"

print("{0:d}=={1:.4f}\n{2:s}".format(a,b,c))

37.  and this prints:

456==123.4659

Hallo

38.  Starting from Python v.3.6, instead of functionformatspecifically marked format string (f“...”) can be used (lab2.4b.py):

a = 456

b = 123.46589

c = "Hallo"

print(f"{a:d}=={b:.4f}\n{c:s}")

39.  Typically there is no need to format integers and strings (lab2.4c.py):

a = 456

b = 123.46589

c = "Hallo"

print(f"{a}=={b:.4f}\n{c}")

{} – units to format:

0,1,2 – unit numbers

d – integer

f – floating point number

s – character string (text)

Everything between formatted units is printed as is.