Wednesday, March 4, 2020

CONSOLE I/O & TYPE-CASTING IN C++

1. Basic data types in C++:

Up till now we have handled only one data type, int, and also seen that during operations on ints, the decimal part is discarded and only the whole number part of the result is stored. This feature can be exploited to write useful code blocks. For example, remember that to get the least significant digit of a multi-digit number n, the following line of code exploited this feature:

digit = (n - (n/10)*10);

If n = 123, after the execution of this line, digit will receive 3.

However, in our daily lives, we need to handle other types of data like decimal numbers and words and sentences of English language as well. C++ provides the following built-in data types (by built-in it is meant that the compiler core intrinsically understands it):

S#
Type
Size
(Bytes)
Meant to store
Examples
1
int
4*
Integer values
3, 0, -3, 102334, -999
2
short
2
Integer values
Same as int but with a smaller range.
3
float
4
Floating point (decimal) values (single precision)
0, 1.0, 1.25, -0.025
4
char
1
ASCII encoded characters including alphabets, numeric, punctuation marks etc.
A, a, 6, ^, (, /
5
double
8
Floating point values like float (double precision)
Same as float but with a larger range and more precision
6
long double
16
Floating point values like float (quadruple precision)
Same as double but with a larger range and more precision
7
long
4
Integer values
Same as int
8
long long
8
Integer values
Same as long but with a larger range.
9
bool
1
true or false (boolean values)
false is stored as 0, true as 1 (any value other than 0 is treated as true)
size of int only depends on the compiler used – mostly 4 bytes. Others are specified.
Note that basic data types intshort, longlong long, bool and char are int-data types in that when used in most operations they invoke integer-maths and behave as int.
Each of the above data type can be declared, defined (or initialized), input or output just like int we have dealt with, until now. For example as in following sample code:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
     int var = 33;
     cout << "var = " <<var<< ", size = ";
cout<< sizeof(var) << " bytes." << endl;
cout << "var = ";
     cin >>var;
cout << "var = " <<var<< endl;  
     return 0;
}
Sample code to manipulate int


Note the sizeof operator, which reports the size in bytes of the operand variable or type.

Task # 1: Declaration, initialization, input and output
Open a new file in DevC++ and save it as lab04_1.cpp. Write the sample code given above and test how the int data type works.

Replace the keyword int on line 6 with each of the other 8 data types (one by one) and see how they behave.

For integer data types (shortintlonglong long) enter integer values (both positive and negative) and see if the same is printed on the output or not. Try to put in large values and see how they respond.

For floating point data types (float, double, long double) enter floating point values (both positive and negative), i.e., values that have a point in them, e.g. 437538.47386834. Try to put in large values. You may use scientific notation to enter large numbers like 2.52e+015.

For char note that you would need to replace the initialization value of 33 with one character in single quotes, e.g., 'A'.At run time, try to input other values and see what gets displayed.
For bool use either keyword true or false to initialize. Again, try to input other values and check the display.

Your task is to find as small a number as possible that cannot be represented by a data type. You may use the size of the variable to narrow down on the smallest number. Fill the table below:

S#
Data type
Smallest Input for which the output is printed differently
Output for the input in previous column
1
short
32768 

var = 32767, size = 2 bytes.
2
long
2147483648
2147483647   size = 4 bytes
3
long long
var = 9223372036854775808

var=9223372036854775807
size = 8 bytes
4
float
var = 3.40282e+039
var = 3.40282e+038
size = 4 bytes
5
double
var = 1.79769e+309
 Var = 1.79769e+308
size = 8 bytes
6
long double
var = 1.18973e+4933
var = 1.18973e+4932
size = 16 bytes
7
char
var = AA

var = A, size = 1 bytes
8
bool
var = 10
var = 1, size = 1 bytes

Task # 2:Boundaries/Limits
Rename current file as lab04_2.cpp.Modify the existing file to contain the following code and run it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()
{
     short x, y;
     x = -12;
     y = 90;

     cout << "x = " << x << ", y = " << y << endl;
    
     short z = x * y;
    
     x = z / x;
     y = z / x;
    
     cout << "x = " << x << ", y = " << y << endl;

     return 0;
}


Note how variables can also be declared right where they are needed or are assigned a value.

1.    Describe in a single sentence what the code does?

         The program changes the values that are assigned to x and y and changes x to value of y and y to value of x.

2.    Describe the logic used in the code in your own words. Avoid explaining each line. Lines 12 - 15 contains the logic used.


      By using variable short z=x *y  and x =y/z , y = z/x  we change the output of program and y vhanges to x’s value and x to y’s valuye




3.    Change the values -12 and 90 to -1200 and 9000 in lines 7 and 8 respectively. Run the code again. Does the code work as intended? Write the output of the code below.
The code does not  work as intended
x = -1200, y = 9000
x = -11, y = -1221


4.    Change the type short on lines 6 and 12 to long (or int). Re-run. Does the code work as intended?Write the output of the code below.
As the capacity of variable is increased from short to long so program works correctly.
x = -1200, y = 9000
x = 9000, y = -1200



5.    Change the values -1200 and 9000 to -120000 and 900000. Re-run. Does the code work as intended? Write the output of the code below.

The code does not work as intended
output
x = -120000, y = 900000
x = 5215, y = -120003





6.    Change data type in line 12 to long long. Re-run. Does the code work as intended?Write the output of the code below.
x = -120000, y = 900000
x = 5215, y = -120003

does not work as intended




7.    Change data type in line 6 to long long. Re-run. Does the code work as intended?Write the output of the code below.


The program works as intended
output
x = -120000, y = 900000
x = 900000, y = -120000



8.    Change the values to really large numbers like -1200000000 and 9000000000. Re-run. Does the code work as intended?Write the output of the code below.
    The code does not work as intended
Output:
       x = -1200000000, y = 9000000000
x = -6372286728, y = -1200000000


9.    Change data types in line 6 and 12 to float. Re-run. Does the code work as intended? Write the output of the code below.
Note how the output is represented in (-)sigeexp format, where - used for negative numbers, sig is significand, exp is exponent and e separates the significand and exponent, which is a compact way of representing large numbers.

The program/code works as intended
Output:
           x = -1.2e+009, y = 9e+009
            x = 9e+009, y = -1.2e+009



10.  Change the values to really large numbers like -120000000000000000 (16 zeros) and 900000000000000000 (17 zeros). Re-run. Does the code work as intended? Write the output of the code below.

The code works as intended.
 Output:
x = -1.2e+017, y = 9e+017
x = 9e+017, y = -1.2e+017




You see that by creating a bigger storage to store data/intermediate-results, we were able to make the program work as intended. However, at times, there is a better way to do it -- by changing the logic of the code!
In the programming world, there can be many (correct) ways of doing the same task, each being good in some way. For example:

11.  Change data types in line 6 and 12 to long and values to -120000 and 900000. We know the code wouldn't work as desired. Now change the * operator on line 12 to operator + and / operator to operator - on lines 14 and 15. Re-run. Does the code work correctly now? Write the output of the code below. Explain why it works.
The code works correctly as  firstly we used long and specified value not to be to big in the same way as  the previouys logic values are switched from x to y and y to x
Output:
           x = 120000, y = 900000
          x = 900000, y = 120000



12.  What do you learn from all these exercises in Task # 2? Write in your own words.
We    learn that with different data types we have different values if we specify a smaller data type and use larger value it does not work properly.



Task # 3:Understanding how cin works
Save a new file as lab04_3.cpp. Write minimalistic code to accomplish the following task.
Declare three variables i, d and c of types intdouble and char respectively, as below:

int i;
double d;
char c;

Read values into these variables using cin statements mentioned below (one statement at a time). The input values to be given on the black console window are specified. Give exactly these inputs and observe what is displayed for each variable. Output each variable usingcout to note what it stores using the following statement:

cout << "i = " << i << ", c = " << c << ", d = " << d << endl;

S#
Input Statement
Input entered
Value of i
Value of c
Value of d
1
cin >> i >> c >> d;
34
B
56.78
34
B
56.78
2
cin >> i >> c >> d;
34 B 56.78
34
B
56.78
3
cin >> i >> c >> d;
34B56.78
34
B
56.78
4
cin >> i >> c >> d;
56.78
56
.
78
5
cin >> i >> c >> d;
34B
56.78
34
B
56.78
6
cin >> i >> c >> d;
56.78B34
56
.
78
7
cin >> i >> c >> d;
56 78
56
7
8
8
cin >> i >> c >> d;
56     78
56
7
8

Note that the extraction operator >> skips blanks and use it as a marker to indicate end of a value. Such blanks are referred to as 'white space characters' and includes space, enter and tab.
Also note that the extraction operator matches data-type with input data. For example an int variable wouldn't receive floating point data, char will only receive one non-whitespace character,etc.

Task # 4:Formatting output with manipulators
Save the current file as lab04_4.cpp.
In this task we will learn how to format output on the console window using cout.
Consider three variables i, c and d of types intcharand doubleinitialized to 12345, 'B' and 12345.9876543210 respectively. cout these variables according to statements as shown below and record the output in the field below each statement.

Be careful that your code should only contain the specified set of cout statements to be able to note the effect of a manipulator, when used.

1
cout<< i << c << d;

12345B12346

2
cout<< i;
cout<< c;
cout<< d;
12345B12346

3
cout<< i << ", " << c << ", " << d<< endl;

12345, B, 12346

4
cout<< i<< endl;
cout<<c << endl;
cout<<d << endl;

12345
B
12346


5
cout << i << '\n' << c << '\n' << d << '\n';

12345
B
12346




6
cout << d << endl;
cout<<scientific;
cout << d << endl;


12346
1.234599e+004





7
cout<<scientific;
cout << d << endl;
cout << fixed;
cout << d << endl;

1.234599e+004
12345.987654




Note that the manipulator keywords do not output anything but instruct the insertion operator << to behave in the specified way. Understand the role of each manipulator by observing the output with and without the use of the manipulator.

To use some of the manipulators used below (setprecision, setw, , you need to include 'iomanip' in your code.

In the code segment below, consider four variables of type double named d1, d2, d3 and d4 initialized to 34.45, 15, 12345.876543210, and 6543210.45 respectively.

8
cout << d1 << ", " << d2 << ", " << d3 << ", " << d4 << endl;

34.45, 15, 12345.9, 6.54321e+006

9
cout <<showpoint;
cout << d1 << ", " << d2 << ", " << d3 << ", " << d4 << endl;

34.4500, 15.0000, 12345.9, 6.54321e+006


10
cout <<showpoint;
cout << d1 << ", " << d2 << ", " << d3 << ", " << d4 << endl;
cout <<noshowpoint;
cout << d1 << ", " << d2 << ", " << d3 << ", " << d4 << endl;

34.4500, 15.0000, 12345.9, 6.54321e+006
34.45, 15, 12345.9, 6.54321e+006



11
cout<<scientific;
cout << d1 << ", " << d2 << ", " << d3 << ", " << d4 << endl;

3.445000e+001, 1.500000e+001, 1.234588e+004, 6.543210e+006



12
cout<<fixed;
cout << d1 << ", " << d2 << ", " << d3 << ", " << d4 << endl;

34.450000, 15.000000, 12345.876543, 6543210.450000



13
cout <<setprecision(2);
cout << d1 << ", " << d2 << ", " << d3 << ", " << d4 << endl;

34, 15, 1.2e+004, 6.5e+006



14
cout <<fixed<< setprecision(2);
cout << d1 << ", " << d2 << ", " << d3 << ", " << d4 << endl;


34.45, 15.00, 12345.88, 6543210.45



15
cout <<scientific<< setprecision(2);
cout << d1 << ", " << d2 << ", " << d3 << ", " << d4 << endl;


3.45e+001, 1.50e+001, 1.23e+004, 6.54e+006



16
cout << fixed << setprecision(2);
cout <<setw(12)<< d1 << endl;
cout << setw(12) << d2 << endl;
cout << setw(12) << d3 << endl;
cout << setw(12) << d4 << endl;

       34.45
       15.00
    12345.88
  6543210.45




17
cout << fixed << setprecision(2)<<left;
cout << setw(12) << d1 << endl;
cout << setw(12) << d2 << endl;
cout << setw(12) << d3 << endl;
cout << setw(12) << d4 << endl;


34.45
15.00
12345.88
6543210.45








18
cout << fixed << setprecision(2) <<right;
cout << 1 << setw(20) <<setfill('.')<< d1 << endl;
cout << 2 << setw(20) << setfill('.') << d2 << endl;
cout << 3 << setw(20) << setfill('.') << d3 << endl;
cout << 4 << setw(20) << setfill('.') << d4 << endl;




1...............34.45
2...............15.00
3............12345.88
4..........6543210.45





Task # 5: Implicit and explicit type-casting
Save the current file as lab04_5.cpp.
Sometimes it is required to change the type of a value, for example, from an int to a double and vice versa, char to int and vice versa etc. When required this is done through explicit type casting to avoid warning/error messages.
The following code type-casts the value held by a double variable d to an int value and stores it into an int variable i.

double d = 34.45;
int i = static_cast<int>(d);

If you do not write the keywords static_cast<int> the output would still be the same since an implicit cast will be done but a warning will be generated at compile time for you to note if this is intended behaviour or not. To suppress such warnings it is recommended to do explicit type casting.Learn by noting the effect of casting in the following chunks of code.

Note you are not supposed to write all the following code in one go. Write each code chunk one at a time, observe the output, then modify it according to the next chunk and so on.

Code chunk
Note the output
double d = 34.45;    
int i = static_cast<int>(d);
cout << i<< endl;
      34
int i = 33;
double d = static_cast<double>(i)/2.0;
cout << d<< endl;
  16.5
char c = 'A';
int i = static_cast<int>(c);
cout << i<< endl;
 65
int i = 70;
char c = static_cast<char>(i);
cout << c<< endl;
   F
      
int i = 15;
cout << i/2 <<", " <<i/2.0 << endl;
cout << i/static_cast<float>(2) << endl;
7, 7.5
7.5
double d = 15.75;
cout << d/2 <<", " <<d/2.0 << endl;
cout << static_cast<int>(d)/2 << endl;
7.875, 7.875
7
int i1 = 73;
int i2 = i1 + 11, i3 = i1 - 6;
cout <<static_cast<char>(i1) << static_cast<char>(i2) <<static_cast<char>(i3) << endl;
  
     ITC



No comments:

Post a Comment

Functions & BASIC FILE I/O

A.    Files : For storage of data for later use, files are used. Files are stored on the Hard Disk Drive (HDD). There are two types of f...