Variables and Data Types C IF ELSE IF

Variables and Data Types

C++ IF, ELSE, IF. . . ELSE STATEMENT

If statements in C++ The ability to control the flow of your program, letting it make decisions on what code to execute, is valuable to the programmer. The if statement allows you to control if a program enters a section of code or not based on whether a given condition is true or false. One of the important functions of the if statement is that it allows the program to select an action based upon the user's input. For example, by using an if statement to check a user entered password, your program can decide whether a user is allowed access to the program. Without a conditional statement such as the if statement, programs would run almost the exact same way every time. If statements allow the flow of the program to be changed, and so they allow algorithms and more interesting code. Basic If Statement Syntax The structure of an if statement is as follows: if (TRUE) Execute the next statement Here is a simple example that shows the syntax: if (5<10) cout<<"Five is now less than ten, that's a big surprise";

Flow Diagram Flowchart of if Statement

How if statement works?

Example 1: C++ if Statement // Program to print positive number entered by the user // If user enters negative number, it is skipped #include <iostream> using namespace std; int main() { int number; cout << "Enter an integer: "; cin >> number; // checks if the number is positive if ( number > 0) { cout << "You entered a positive integer: " << number << endl; } cout << "This statement is always executed. "; return 0; } Output 1 Output 2 Enter an integer: 5 You entered a positive number: 5 This statement is always executed. Enter a number: -5 This statement is always executed.

Else An if statement can be followed by an optional else statement, which executes when the boolean expression is false. Syntax The syntax of an if. . . else statement in C++ is − if(boolean_expression) { // statement(s) will execute if the boolean expression is true } else { // statement(s) will execute if the boolean expression is false } If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed.

Example #include <iostream> using namespace std; int main () { // local variable declaration: int a = 100; // check the boolean condition if( a < 20 ) { // if condition is true then print the following cout << "a is less than 20; " << endl; } else { // if condition is false then print the following cout << "a is not less than 20; " << endl; } cout << "value of a is : " << a << endl; return 0; } When the above code is compiled and executed, it produces the following result − a is not less than 20; value of a is : 100

How if. . . else statement works? Flowchart of if. . . else

Example 2: C++ if. . . else Statement // Program to check whether an integer is positive or negative // This program considers 0 as positive number #include <iostream> using namespace std; int main() { int number; cout << "Enter an integer: "; cin >> number; if ( number >= 0) { cout << "You entered a positive integer: " << number << endl; } else { cout << "You entered a negative integer: " << number << endl; } cout << "This line is always printed. "; return 0; } Output Enter an integer: -4 You entered a negative integer: -4. This line is always printed.

Else If if. . . else Statement An if statement can be followed by an optional else if. . . elsestatement, which is very usefull to test various conditions usingle if. . . else if statement. When using if , else statements there are few points to keep in mind. • An if can have zero or one else's and it must come after any else if's. • An if can have zero to many else if's and they must come before the else. • Once an else if succeeds, none of he remaining else if's or else's will be tested.

Syntax The syntax of an if. . . else statement in C++ is − if(boolean_expression 1) { // Executes when the boolean expression 1 is true } else if( boolean_expression 2) { // Executes when the boolean expression 2 is true } else if( boolean_expression 3) { // Executes when the boolean expression 3 is true } else { // executes when the none of the above condition is true. }

Let's look at a simple program for you to try out on your own. #include <iostream> using namespace std; int main() // Most important part of the program! { int age; // Need a variable. . . cout<<"Please input your age: "; // Asks for age cin>> age; // The input is put in age cin. ignore(); // Throw away enter if ( age < 100 ) { // If the age is less than 100 cout<<"You are pretty young!n"; // Just to show you it works. . . } else if ( age == 100 ) { // I use else just to show an example cout<<"You are oldn"; // Just to show you it works. . . } else { cout<<"You are really oldn"; // Executed if no other statement is } cin. get(); }

Example When the above code is compiled and executed, it produces the following result − #include <iostream> using namespace std; int main () { // local variable declaration: int a = 100; // check the boolean condition if( a == 10 ) { // if condition is true then print the following cout << "Value of a is 10" << endl; } else if( a == 20 ) { // if else if condition is true cout << "Value of a is 20" << endl; } else if( a == 30 ) { // if else if condition is true cout << "Value of a is 30" << endl; } else { // if none of the conditions is true cout << "Value of a is not matching" << endl; } cout << "Exact value of a is : " << a << endl; return 0; } Value of a is not matching Exact value of a is : 100

Conditional/Ternary Operator ? : A ternary operator operates on 3 operands which can be used instead of a if. . . else statement. Consider this code: if ( a < b ) { a = b; } else { a = -b; } You can replace the above code with: a = (a < b) ? b : -b; The ternary operator is more readable than a if. . . else statement for short conditions.

Conditional ternary operator ( ? ) // conditional operator #include <iostream> using namespace std; int main () { int a, b, c; a=2; b=7; c = (a>b) ? a : b; cout << c << 'n'; } 7

Example: Check Vowel or a Consonant Manually #include <iostream> using namespace std; int main() { char c; int is. Lowercase. Vowel, is. Uppercase. Vowel; cout << "Enter an alphabet: "; cin >> c; // evaluates to 1 (true) if c is a lowercase vowel is. Lowercase. Vowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); // evaluates to 1 (true) if c is an uppercase vowel is. Uppercase. Vowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'); // evaluates to 1 (true) if either is. Lowercase. Vowel or is. Uppercase. Vowel is true if (is. Lowercase. Vowel || is. Uppercase. Vowel) cout << c << " is a vowel. "; else cout << c << " is a consonant. "; return 0; } Output Enter an alphabet: u u is a vowel.

Objectives of this session • Keywords • Identifiers • Basic Data Types • bool & wchar_t • Pointer • Built-in Data Types • User-defined Data Types • Derived Data Types • Symbolic Constants • Dynamic Initialization of Variables • Reference Variables

Variables and Data Types Tokens The smallest individual units in a program are known as tokens. o Keywords o Identifiers o Constants o Strings o Operators

Keywords

Identifiers A valid identifier is a sequence of one or more letters, digits or underscore characters (_). Neither spaces nor punctuation marks or symbols can be part of an identifier. Only letters, digits and single underscore characters are valid. In addition, variable identifiers always have to begin with a letter. They can also begin with an underline character (_ ).

Identifiers continue… The name of a variable: • Starts with an underscore “_” or a letter, lowercase or uppercase, such as a letter from a to z or from A to Z. Examples are Name, gender, _Students, p. Rice. • Can include letters, underscore, or digits. Examples are: keyboard, Master, Junction, Player 1, total_grade, _Score. Side 1. • Cannot include special characters such as !, %, ], or $. • Cannot include an empty space. • Cannot be any of the reserved words. • Should not be longer than 32 characters (although allowed).

Basic Data Types C++ Data Types User-defined Type Built-in Type Derived Type structure union class enumeration array function pointer reference Integral Type int Void char Floating Type float double

Basic Data Types continue… ANSI C++ added two more data types • bool • wchar_t ANSI is a member of ISO, ANSI C++ is simply the same thing as the ISO C++ standard, ANSI means "American National Standards Institute" there are many language before C. there and not register by ANSI, but Dennis Ritchis does not done mistake he register and he provid and show the property of that language therefore that C language has got ASNI keys this property was done to the C++ also. .

Data Type - bool A variable with bool type can hold a Boolean value true or false. Declaration: bool b 1; // declare b 1 as bool type b 1 = true; // assign true value to b 1 bool b 2 = false; // declare and initialize The default numeric value of true is 1 and false is 0. Syntax: bool b 1 = true; // declaring a boolean variable with true value

It is also possible to convert implicitly the data type integers or floating point values to bool type. For example, the statementsbool x = 0; // false bool y = 100; // true bool z = 15. 75; // true

#include<iostream> // CPP program to illustrate bool data type in C++ using namespace std; int main() { int x 1 = 10, x 2 = 20, m = 2; Output: bool b 1, b 2; b 1 = x 1 == x 2; // false b 1 is = 0 b 2 = x 1 < x 2; // true b 2 is = 1 cout << "b 1 is = " << b 1 << "n"; Yes cout << "b 2 is = " << b 2 << "n"; 9 bool b 3 = true; if (b 3) cout << "Yes" << "n"; else cout << "No" << "n"; int x 3 = false + 5 * m - b 3; cout << x 3; return 0; }

Data Type – wchar_t The character type wchar_t has been defined to hold 16 -bit wide characters. wide_character uses two bytes of memory. wide_character literal in C++ begin with the letter L L‘xy’ // wide_character literal

Built-in Data Types int, char, float, double are known as basic or fundamental data types. Signed, unsigned, long, short modifier for integer and character basic data types. Long modifier for double.

Built-in Data Types continue… Type void was introduced in ANSI C. Two normal use of void: o To specify the return type of a function when it is not returning any value. o To indicate an empty argument list to a function. § eg: - void function-name ( void )

C++ Pointers In this lecture, you'll learn everything about pointers. You'll learn how values are stored in the computer and how to access them using pointers. Pointers are powerful features of C++ that differentiates it from other programming languages like Java and Python. Pointers are used in C++ program to access the memory and manipulate the address.

Address in C++ To understand pointers, you should first know how data is stored on the computer. Each variable you create in your program is assigned a location in the computer's memory. The value the variable stores is actually stored in the location assigned. To know where the data is stored, C++ has an & operator. The & (reference) operator gives you the address occupied by a variable. If var is a variable then, &var gives the address of that variable.

Example 1: Address in C++ #include <iostream> using namespace std; int main() { int var 1 = 3; int var 2 = 24; int var 3 = 17; cout << &var 1 << endl; cout << &var 2 << endl; cout << &var 3 << endl; } Output 0 x 7 fff 5 fbff 8 ac 0 x 7 fff 5 fbff 8 a 8 0 x 7 fff 5 fbff 8 a 4 Note: You may not get the same result on your system. The 0 x in the beginning represents the address is in hexadecimal form. Notice that first address differs from second by 4 -bytes and second address differs from third by 4 -bytes. This is because the size of integer (variable of type int) is 4 bytes in 64 -bit system.

Pointers Variables C++ gives you the power to manipulate the data in the computer's memory directly. You can assign and deassign any space in the memory as you wish. This is done using Pointer variables. Pointers variables are variables that points to a specific address in the memory pointed by another variable. How to declare a pointer? int *p; OR, int* p; The statement above defines a pointer variable p. It holds the memory address The asterisk is a dereference operator which means pointer to. Here, pointer p is a pointer to int, i. e. , it is pointing to an integer value in the memory address.

Asterisk (*) ampersand sign (&)

Address-of operator (&) The address of a variable can be obtained by preceding the name of a variable with an ampersand sign (&), known as address-of operator. For example: foo = &myvar; This would assign the address of variable myvar to foo; by preceding the name of the variable myvar with the addressof operator (&), we are no longer assigning the content of the variable itself to foo, but its address. The actual address of a variable in memory cannot be known before runtime, but let's assume, in order to help clarify some concepts, that myvar is placed during runtime in the memory address 1776. In this case, consider the following code fragment: myvar = 25; foo = &myvar; bar = myvar;

Address-of operator (&) The values contained in each variable after the execution of this are shown in the following diagram:

Address-of operator (&) First, we have assigned the value 25 to myvar (a variable whose address in memory we assumed to be 1776). The second statement assigns foo the address of myvar, which we have assumed to be 1776. Finally, the third statement, assigns the value contained in myvar to bar. This is a standard assignment operation, as already done many times in earlier chapters. The main difference between the second and third statements is the appearance of the address-of operator (&). The variable that stores the address of another variable (like foo in the previous example) is what in C++ is called a pointer. Pointers are a very powerful feature of the language that has many uses in lower level programming. A bit later, we will see how to declare and use pointers.

Dereference operator (*) As just seen, a variable which stores the address of another variable is called a pointer. Pointers are said to "point to" the variable whose address they store. An interesting property of pointers is that they can be used to access the variable they point to directly. This is done by preceding the pointer name with the dereference operator (*). The operator itself can be read as "value pointed to by". Therefore, following with the values of the previous example, the following statement: baz = *foo; This could be read as: "baz equal to value pointed to by foo", and the statement would actually assign the value 25 to baz, since foo is 1776, and the value pointed to by 1776 (following the example above) would be 25.

Dereference operator (*) It is important to clearly differentiate that foo refers to the value 1776, while *foo (with an asterisk * preceding the identifier) refers to the value stored at address 1776, which in this case is 25. Notice the difference of including or not including the dereference operator (I have added an explanatory comment of how each of these two expressions could be read):

Dereference operator (*) baz = foo; // baz equal to foo (1776) baz = *foo; // baz equal to value pointed to by foo (25) he reference and dereference operators are thus complementary: & is the address-of operator, and can be read simply as "address of" * is the dereference operator, and can be read as "value pointed to by" Thus, they have sort of opposite meanings: An address obtained with & can be dereferenced with *. Earlier, we performed the following two assignment operations: myvar = 25; foo = &myvar;

Dereference operator (*) Right after these two statements, all of the following expressions would give true as result: myvar == 25 &myvar == 1776 foo == 1776 *foo == 25 The first expression is quite clear, considering that the assignment operation performed on myvar was myvar=25. The second one uses the address-of operator (&), which returns the address of myvar, which we assumed it to have a value of 1776. The third one is somewhat obvious, since the second expression was true and the assignment operation performed on foo was foo=&myvar. The fourth expression uses the dereference operator (*) that can be read as "value pointed to by", and the value pointed to by foo is indeed 25. So, after all that, you may also infer that for as long as the address pointed to by foo remains unchanged, the following expression will also be true: *foo == myvar

Declaring pointers Due to the ability of a pointer to directly refer to the value that it points to, a pointer has different properties when it points to a char than when it points to an int or a float. Once dereferenced, the type needs to be known. And for that, the declaration of a pointer needs to include the data type the pointer is going to point to. The declaration of pointers follows this syntax: type * name; where type is the data type pointed to by the pointer. This type is not the type of the pointer itself, but the type of the data the pointer points to. For example: int * number; char * character; double * decimals;

Declaring pointers These are three declarations of pointers. Each one is intended to point to a different data type, but, in fact, all of them are pointers and all of them are likely going to occupy the same amount of space in memory (the size in memory of a pointer depends on the platform where the program runs). Nevertheless, the data to which they point to do not occupy the same amount of space nor are of the same type: the first one points to an int, the second one to a char, and the last one to a double. Therefore, although these three example variables are all of them pointers, they actually have different types: int*, char*, and double* respectively, depending on the type they point to. Note that the asterisk (*) used when declaring a pointer only means that it is a pointer (it is part of its type compound specifier), and should not be confused with the dereference operator seen a bit earlier, but which is also written with an asterisk (*). They are simply two different things represented with the same sign.

Let's see an example on pointers: // my first pointer #include <iostream> using namespace std; int main () { int firstvalue, secondvalue; int * mypointer; mypointer = &firstvalue; *mypointer = 10; mypointer = &secondvalue; *mypointer = 20; cout << "firstvalue is " << firstvalue << 'n'; cout << "secondvalue is " << secondvalue << 'n'; return 0; } firstvalue is 10 secondvalue is 20

Declaring pointers Notice that even though neither firstvalue nor secondvalue are directly set any value in the program, both end up with a value set indirectly through the use of mypointer. This is how it happens: First, mypointer is assigned the address of firstvalue using the address-of operator (&). Then, the value pointed to by mypointer is assigned a value of 10. Because, at this moment, mypointer is pointing to the memory location of firstvalue, this in fact modifies the value of firstvalue. In order to demonstrate that a pointer may point to different variables during its lifetime in a program, the example repeats the process with secondvalue and that same pointer, mypointer.

Here is an example a little bit more elaborated: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // more pointers #include <iostream> using namespace std; int main () { int firstvalue = 5, secondvalue = 15; int * p 1, * p 2; p 1 = &firstvalue; // p 1 = address of firstvalue p 2 = &secondvalue; // p 2 = address of secondvalue *p 1 = 10; // value pointed to by p 1 = 10 *p 2 = *p 1; // value pointed to by p 2 = value pointed to by p 1 = p 2; // p 1 = p 2 (value of pointer is copied) *p 1 = 20; // value pointed to by p 1 = 20 cout << "firstvalue is " << firstvalue << 'n'; cout << "secondvalue is " << secondvalue << 'n'; return 0; } firstvalue is 10 secondvalue is 20

Declaring pointers Each assignment operation includes a comment on how each line could be read: i. e. , replacing ampersands (&) by "address of", and asterisks (*) by "value pointed to by". Notice that there are expressions with pointers p 1 and p 2, both with and without the dereference operator (*). The meaning of an expression using the dereference operator (*) is very different from one that does not. When this operator precedes the pointer name, the expression refers to the value being pointed, while when a pointer name appears without this operator, it refers to the value of the pointer itself (i. e. , the address of what the pointer is pointing to). Another thing that may call your attention is the line: int * p 1, * p 2;

Declaring pointers This declares the two pointers used in the previous example. But notice that there is an asterisk (*) for each pointer, in order for both to have type int* (pointer to int). This is required due to the precedence rules. Note that if, instead, the code was: int * p 1, p 2; p 1 would indeed be of type int*, but p 2 would be of type int. Spaces do not matter at all for this purpose. But anyway, simply remembering to put one asterisk per pointer is enough for most pointer users interested in declaring multiple pointers per statement. Or even better: use a different statement for each variable.

Built-in Data Types continue… Type void can also used for declaring generic pointer. A generic pointer can be assigned a pointer value of any basic data type, but it may not be de-referenced. void *gp; // gp becomes generic pointer int *ip; // int pointer gp = ip; // assign int pointer to void pointer Assigning any pointer type to a void pointer is allowed in C & C++.

Built-in Data Types continue… void *gp; // gp becomes generic pointer int *ip; // int pointer ip = gp; // assign void pointer to int pointer This is allowed in C. But in C++ we need to use a cast operator to assign a void pointer to other type pointers. ip = ( int * ) gp; // assign void pointer to int pointer // using cast operator *ip = *gp; is illegal

Sizes of Fundamental Types Type Size bool, char, unsigned char, __int 8 1 byte __int 16, short, unsigned short, wchar_t, __wchar_t 2 bytes float, __int 32, int, unsigned int, long, unsigned long 4 bytes double, __int 64, long double, long 8 bytes

Below table summarizes the modified size and range of built-in datatypes when combined with the type modifiers: DATA TYPE SIZE (IN BYTES) RANGE short int 2 -32, 768 to 32, 767 unsigned short int 2 0 to 65, 535 unsigned int 4 0 to 4, 294, 967, 295 int 4 -2, 147, 483, 648 to 2, 147, 483, 647 long int 8 -2, 147, 483, 648 to 2, 147, 483, 647 unsigned long int 4 0 to 4, 294, 967, 295 long int 8 -(2^63) to (2^63)-1 unsigned long int 8 0 to 18, 446, 744, 073, 709, 551, 615 signed char 1 -128 to 127 unsigned char 1 0 to 255 float 4 double 8 long double 12 wchar_t 2 or 4 1 wide character

int *p 1, *p 2, i; // p 1 and p 2 are int pointers. i is an int* p 1, p 2, i; // p 1 is a int pointer, p 2 and i are int * p 1, * p 2, i; // p 1 and p 2 are int pointers, i is an int

We can display the size of all the data types by using the sizeof() function and passing the keyword of the datatype as argument to this function as shown below: // C++ program to sizes of data types #include<iostream> using namespace std; int main() { cout << "Size of char : " << sizeof(char) << " byte" << endl; cout << "Size of int : " << sizeof(int) << " bytes" << endl; cout << "Size of short int : " << sizeof(short int) << " bytes" << endl; cout << "Size of long int : " << sizeof(long int) << " bytes" << endl; cout << "Size of signed long int : " << sizeof(signed long int) << " bytes" << endl; cout << "Size of unsigned long int : " << sizeof(unsigned long int) << " bytes" << endl; cout << "Size of float : " << sizeof(float) << " bytes" <<endl; cout << "Size of double : " << sizeof(double) << " bytes" << endl; cout << "Size of wchar_t : " << sizeof(wchar_t) << " bytes" <<endl; return 0; }

Output: Size Size Size of of of char : 1 byte int : 4 bytes short int : 2 bytes long int : 8 bytes signed long int : 8 bytes unsigned long int : 8 bytes float : 4 bytes double : 8 bytes wchar_t : 4 bytes


Pointers and dynamic objects/ Slide 59 Pointers *A pointer is a variable used to store the address of a memory cell. * We can use the pointer to reference this memory cell Memory address: 1020 … … integer 1024 100 1032 … 1024 … pointer

Pointers and dynamic objects/ Slide 60 Pointer Variable * Declaration of Pointer variables type* pointer_name; //or type *pointer_name; where type is the type of data pointed to (e. g. int, char, double) Examples: int *n; Rational. Number *r; int **p; // pointer to pointer

Pointers and dynamic objects/ Slide 61 Pointer to Pointer What is the output? The output is: 58 58 58

Example 2: C++ Pointers C++ Program to demonstrate the working of pointer. #include <iostream> using namespace std; int main() { int *pc, c; c = 5; cout << "Address of c (&c): " << &c << endl; cout << "Value of c (c): " << c << endl; pc = &c; // Pointer pc holds the memory address of variable c cout << "Address that pointer pc holds (pc): "<< pc << endl; cout << "Content of the address pointer pc holds (*pc): " << *pc << endl; c = 11; // The content inside memory address &c is changed from 5 to 11. cout << "Address pointer pc holds (pc): " << pc << endl; cout << "Content of the address pointer pc holds (*pc): " << *pc << endl; *pc = 2; cout << "Address of c (&c): " << &c << endl; cout << "Value of c (c): " << c << endl; return 0; }

Output Address of c (&c): 0 x 7 fff 5 fbff 80 c Value of c (c): 5 Address that pointer pc holds (pc): 0 x 7 fff 5 fbff 80 c Content of the address pointer pc holds (*pc): 5 Address pointer pc holds (pc): 0 x 7 fff 5 fbff 80 c Content of the address pointer pc holds (*pc): 11 Address of c (&c): 0 x 7 fff 5 fbff 80 c Value of c (c): 2

Explanation of program When c = 5; the value 5 is stored in the address of variable c - 0 x 7 fff 5 fbff 8 c. When pc = &c; the pointer pc holds the address of c - 0 x 7 fff 5 fbff 8 c, and the expression (dereference operator) *pc outputs the value stored in that address, 5. When c = 11; since the address pointer pc holds is the same as c - 0 x 7 fff 5 fbff 8 c, change in the value of c is also reflected when the expression *pc is executed, which now outputs 11. When *pc = 2; it changes the content of the address stored by pc - 0 x 7 fff 5 fbff 8 c. This is changed from 11 to 2. So, when we print the value of c, the value is 2 as well.

&c Common mistakes when working with pointers Suppose, you want pointer pc to point to the address of c. Then, int c, *pc; pc=c; /* *pc=&c; /* *pc=c; /* Wrong! pc is address whereas, c is not an address. */ Wrong! *pc is the value pointed by address whereas, &c is an address. */ Correct! pc is an address and, &c is also an address. */ Correct! *pc is the value pointed by address and, c is also a value. */ In both cases, pointer pc is not pointing to the address of c.

Data Types I/O • Strings and string I/O • Integers and integer I/O • Types and objects • Type safety

Input and output // read first name: #include<iostream> using namespace std; int main() { cout << "Please enter your first name (followed " << "by 'enter'): n"; string first_name; cin >> first_name; cout << "Hello, " << first_name << 'n'; } // note how several values can be output by a single statement // a statement that introduces a variable is called a declaration // a variable holds a value of a specified type // the final return 0; is optional in main() // but you may need to include it to pacify your compiler 67

Input and type • We read into a variable • Here, first_name • A variable has a type • Here, string • The type of a variable determines what operations we can do on it • Here, cin>>first_name; reads characters until a whitespace character is seen (“a word”) • White space: space, tab, newline, … 68

String input // read first and second name: Run int main() { cout << "please enter your first and second namesn"; string first; string second; cin >> first >> second; // read two strings string name = first + ' ' + second; // concatenate strings // separated by a space cout << "Hello, "<< name << 'n'; } // I left out the #include "std_lib_facilities. h" to save space and // reduce distraction // Don’t forget it in real code // Similarly, I left out the Windows-specific keep_window_open(); 69

Integers // read name and age: Run int main() { cout << "please enter your first name and agen"; string first_name; // string variable int age; // integer variable cin >> first_name >> age; // read cout << "Hello, " << first_name << " age " << age << 'n'; } 70

Integers and Strings • • Integers and floating-point numbers cin >> reads a word cout << writes + concatenates += s adds the string s at end ++ is an error - is an error • … • • cin >> reads a number cout << writes + adds += n increments by the int n ++ increments by 1 - subtracts … The type of a variable determines which operations are valid and what their meanings are for that type (that's called “overloading” or “operator overloading”) 71

A simple computation int main() // inch to cm conversion { const double cm_per_inch = 2. 54; // number of centimeters per inch int length = 1; // length in inches while (length != 0) { // length == 0 is used to exit the program // a compound statement (a block) cout << "Please enter a length in inches: "; cin >> length; cout << length << "in. = " << cm_per_inch*length << "cm. n"; } } • A while-statement repeatedly executes until its condition becomes false 75

Types and literals • Built-in types • Boolean type • bool • Character types • char • Integer types • int • and short and long • Floating-point types • double • and float • Standard-library types • string • complex<Scalar> • Boolean literals • true false • Character literals • 'a', 'x', '4', 'n', '$' • Integer literals • 0, 1, 123, -6, 034, 0 xa 3 • Floating point literals • 1. 2, 13. 345, . 3, -0. 54, 1. 2 e 3, . 3 F • String literals "asdf", "Howdy, all y'all!" • Complex literals • complex<double>(12. 3, 99) • complex<float>(1. 3 F) If (and only if) you need more details, see the book programming in C++! 76

Types • C++ provides a set of types • E. g. bool, char, int, double • Called “built-in types” • C++ programmers can define new types • Called “user-defined types” • We'll get to that eventually • The C++ standard library provides a set of types • E. g. string, vector, complex • Technically, these are user-defined types • they are built using only facilities available to every user 77

Declaration and initialization int a = 7; a: 7 int b = 9; b: 9 char c = 'a'; c: double x = 1. 2; 'a' x: 1. 2 string s 1 = "Hello, world"; s 1: 12 string s 2 = "1. 2"; s 2: 3 | | "Hello, world" "1. 2" 78

Objects • An object is some memory that can hold a value of a given type • A variable is a named object • A declaration names an object int a = 7; char c = 'x'; complex<double> z(1. 0, 2. 0); string s = "qwerty"; s: 6 a: c: z: 7 'x' 1. 0 2. 0 "qwerty" 79

Assignment and increment a: // changing the value of a variable int a = 7; // a variable of type int called a 7 // initialized to the integer value 7 a = 9; // assignment: now change a's value to 9 a = a+a; // assignment: now double a's value a += 2; // increment a's value by 2 ++a; // increment a's value (by 1) 9 18 20 21 82

A type-safety violation (“implicit narrowing”) // Beware: C++ does not prevent you from trying to put a large value // into a small variable (though a compiler may warn) Run int main() { a int a = 20000; char c = a; int b = c; if (a != b) // != means “not equal” cout << "oops!: " << a << "!=" << b << 'n'; else cout << "Wow! We have large charactersn"; } • Try it to see what value b gets on your machine 20000 c: ? ? ? 83

A type-safety violation (Uninitialized variables) // Beware: C++ does not prevent you from trying to use a variable // before you have initialized it (though a compiler typically warns) int main() { int x; char c; double d; // x gets a “random” initial value // c gets a “random” initial value // d gets a “random” initial value // – not every bit pattern is a valid floating-point value double dd = d; // potential error: some implementations // can’t copy invalid floating-point values cout << " x: " << x << " c: " << c << " d: " << d << 'n'; } • Always initialize your variables – beware: “debug mode” may initialize (valid exception to this rule: input variable) 84

A technical detail • In memory, everything is just bits; type is what gives meaning to the bits (bits/binary) 01100001 is the int 97 is the char 'a' (bits/binary) 01000001 is the int 65 is the char 'A' (bits/binary) 00110000 is the int 48 is the char '0' char c = 'a'; cout << c; // print the value of character c, which is a int i = c; cout << i; // print the integer value of the character c, which is 97 • This is just as in “the real world”: • What does “ 42” mean? • You don’t know until you know the unit used • Meters? Feet? Degrees Celsius? $s? a street number? Height in inches? … 85

About Efficiency • For now, don’t worry about “efficiency” • Concentrate on correctness and simplicity of code • C++ is derived from C, which is a systems programming language • C++’s built-in types map directly to computer main memory • a char is stored in a byte • An int is stored in a word • A double fits in a floating-point register • C++’s built-in operations map directly to machine instructions • An integer + is implemented by an integer add operation • An integer = is implemented by a simple copy operation • C++ provides direct access to most of the facilities provided by modern hardware • C++ help users build safer, more elegant, and efficient new types and operations using built-in types and operations. • E. g. , string • Eventually, we’ll show some of how that’s done 86

Another simple computation // inch to cm and cm to inch conversion: #include <iostream> using namespace std; int main() { const double cm_per_inch = 2. 54; int val; char unit; while (cin >> val >> unit) { // keep reading if (unit == 'i') // 'i' for inch cout << val << "in == " << val*cm_per_inch << "cmn"; else if (unit == 'c') // 'c' for cm cout << val << "cm == " << val/cm_per_inch << "inn"; else return 0; // terminate on a “bad unit”, e. g. 'q' } } 88

User-Defined Data Types continue… Enumerated Data Type: Enumerated data type provides a way for attaching names to numbers. enum keyword automatically enumerates a list of words by assigning them values 0, 1, 2, and so on. enum shape {circle, square, triangle}; enum colour {red, blue, green, yellow}; enum position {off, on};

User-Defined Data Types continue… Enumerated Data Type: enum colour {red, blue, green, yellow}; In C++ the tag names can be used to declare new variables. colour background; In C++ each enumerated data type retains its own separate type. C++ does not permit an int value to be automatically converted to an enum value.

User-Defined Data Types Enumerated Data Type: colour background = blue; // allowed colour background = 3; // error in C++ colour background = (colour) 3; // OK int c = red; // valid continue…

User-Defined Data Types continue… Enumerated Data Type: By default, the enumerators are assigned integer values starting with 0. We can override the default value by explicitly assigning integer values to the enumerators. enum colour {red, blue=4, green =8}; enum colour {red=5, blue, green};

User-Defined Data Types continue… Enumerated Data Type: C++ also permits the creation of anonymous enum (i. e. , enum with out tag name). enum {off, on}; here off 0 and on 1 int switch_1 = off; int switch_2 = on;

Example: Enumeration Type #include <iostream> using namespace std; enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; int main() { week today; today = Wednesday; cout << "Day " << today+1; return 0; } Output Day 4

//Enum example //An enum example in C++ #include <iostream> using namespace std; int main() { enum Days{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; Days The. Day; int j; cout<<"Please enter the day of the week (0 to 6)"; cin>>j; The. Day = Days(j); if(The. Day == Sunday || The. Day == Saturday) cout<<"Hurray it is the weekend"<<endl; else cout<<" Lectures still at work"<<endl; return 0; }

Derived Data Types Arrays The application of arrays in C++ is similar to that in C. Functions top-down - structured programming ; to reduce length of the program ; reusability ; function over-loading.

Derived Data Types Pointers As already explained to you. Pointers can be declared and initialized as in C. int * ip; // int pointer ip = &x; // address of x assigned to ip *ip = 10; // 10 assigned to x through indirection continue…

Derived Data Types continue… Pointers C++ adds the concept of constant pointer and pointer to a constant. char * const ptr 1 = “GOODS”; // constant pointer int const * ptr 2 = &m; // pointer to a constant

Symbolic Constants Two ways of creating symbolic constant in C++. Using the qualifier const Defining a set of integer constants using enum keyword. Any value declared as const can not be modified by the program in any way. In C++, we can use const in a constant expression. const int size = 10; char name[size]; // This is illegal in C.

Symbolic Constants continue… const allows us to create typed constants. #define - to create constants that have no type information. The named constants are just like variables except that their values can not be changed. C++ requires a const to be initialized. A const in C++ defaults, it is local to the file where it is declared. To make it global the qualifier extern is used.

Symbolic Constants extern const int total = 100; enum { X, Y, Z }; This is equivalent to const int X = 0; const int Y = 1; const int Z = 2; continue…

Reference Variables A reference variable provides an alias for a previously defined variable. For eg. , if we make the variable sum a reference to the variable total, then sum and total can be used interchangeably to represent that variable. data-type & reference-name = variable-name float total = 100; float &sum = total;

Reference Variables continue… A reference variable must be initialized at the time of declaration. This establishes the correspondence between the reference and the data object which it names. int x ; int *p = &x ; int & m = *p ;

Reference Variables void f ( int & x ) { x = x + 10; } int main ( ) { int m = 10; f (m); } When the function call f(m) is executed, int & x = m; continue…

Pointer to Pointer (Multiple Indirection) #include <iostream> using namespace std; int main () { int var; int *ptr; int **pptr; var = 3000; // take the address of var ptr = &var; // take the address of ptr using address of operator & pptr = &ptr; // take the value using pptr cout << "Value of var : " << var << endl; cout << "Value available at *ptr : " << *ptr << endl; cout << "Value available at **pptr : " << **pptr << endl; return 0; } Value of var : 3000 Value available at *ptr : 3000 Value available at **pptr : 3000

C++ new operator If you allocate memory using new, then it will remain allocated until the program exits unless you explicitly deallocate with delete. Below program contains only one function so memory will be deallocated after program exits, but we have used delete as it is a good programming practice to deallocate memory which isn't required further in the program. delete operator in c++ After using the dynamically allocated memory we have to delete the memory because it is not deleted by the compiler automatically. So if we forget to delete the memory than we will get memory leak issues in the program.

Difference between ptr and &ptr int main() { int *ptr; ptr=new int; *ptr=10; cout<<ptr<<endl; cout<<&ptr<<endl; delete ptr; cout<<*ptr<<endl; } What's the difference between the first two statements. Both give an address. Since the new operator reserves a memory in the heap, which statement gives the address of the dynamically reserved memory in the heap, ptr or &ptr. Now if we do: delete ptr; This will free the memory dynamically reserved in the heap earlier but &ptr still points to that memory location. Why ? ? int main() { int *ptr; ptr=new int; *ptr=10; cout<<ptr<<endl; cout<<&ptr<<endl; cout<<*ptr<<endl; } Because that is what delete does: it de-allocates whatever ptr points to. You can re-use ptr to point to something else, or set it to nullptr, but you have to be explicit about it. Bear in mind that many pointers can point to the same dynamically allocated memory address, so setting one of them to nullptr does not guarantee safety

The end
- Slides: 101