Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming in C++ Lecture Notes 1 – Getting Started Andreas Savva.

Similar presentations


Presentation on theme: "Programming in C++ Lecture Notes 1 – Getting Started Andreas Savva."— Presentation transcript:

1 Programming in C++ Lecture Notes 1 – Getting Started Andreas Savva

2 2 What is a Computer? Is it a machine with a fantastic brain and incredible intelligence? Of course NOT. A computer has no reasoning power. It does exactly what we tell it to do - no more and no less. If we tell it to do something stupid, it does it. If we tell it to do sensible/clever things it does it as well. The important thing is that computers do what we ask them to do very - very quickly and without making mistakes.

3 3 What is a Computer Program? A computer program is a sequence of instructions. The computer does not obey these instructions while we write them. Instead, it stores them in a file and when we finish, we can ask the computer to execute them. The process of constructing (or writing) a program is called programming. #include using namespace std; void main() { int a, b; cout << ”Enter two numbers”; cin >> a >> b; cout << a << ” + ” << b << ” = ” << a+b; }

4 4 What is a Programming Language? Why can’t we “speak” to the computer in English or in Greek or even in Chinese? Because natural languages are prone to ambiguities. Since computers do exactly what we tell them to, we must be very precise what we tell them, otherwise they will not respond since they have no intelligence. Programming languages have been developed for the purpose of communicating with computers. we Programming languages are a sort of stylised English with a few special symbols. They are called high level languages, since they are designed at the level at which we want to think about things rather than at the level at which the machine operates.

5 5 A program written in a high level language is called the “source code”, and it does not make sense to a computer. The computer understands only one language – the “machine code”. Thus, the source-code must be translated into machine code. The translation process is called compilation and the program is called compiler. This compiled program can then be run/executed. So, on a computer you can use any programming language for which the computer has a compiler. What is a Compiler? #include using namespace std; void main() { cout << ”Hello World”; } C++ compiler run execute

6 6 History 1950s Assembly languages Late 1950s, early 1960s FORTRAN (FORmula TRANslator) COBOL (Common Business Oriented Language) Early 1970s Pascal was developed by Nicklaus Wirth of Switzerland – Academic language (good programming techniques) C was developed by Dennis Ritchie at AT&T Bell Labs – Language of choice by many professionals Early 1980s C++ was developed by Bjarne Stroustrup at AT&T Bell Labs – Successor of C, supports OOP.

7 7 What is an Algorithm An Algorithm is a detailed sequence of simple steps that are needed to solve a problem. It is a step-by-step solution to a problem

8 8 Mathematical Example Problem: What is the value of x in the following equation? 5x – 10 = 30 Algorithm (Solution): Step 1:5x = Step 2:5x = 40 Step 3:x = 40/5 Step 4:x = 8

9 9 Making a cake Step 1: Preheat oven to 200 degrees. Step 2: Mix the eggs with the sugar. Step 3: Add the butter, flour, and the rest of the ingredients. Step 4: Stir for 5 minutes. Step 5: Put the mixture into a baking pan and cook it in a 175 degrees for 40 minutes. Step 6: Keep it in the pan for 15 minutes to cool down. Step 7: Serve with vanilla ice-cream.

10 10 Algorithm Step 1: Step 1: Move 3 squares and turn right. Step2: Step 2: Move 1 square and turn left. Step3: Step 3: Move 2 squares and turn left. Step4: Step 4: Move 2 squares and turn right. etc. The Problem The Problem: How will the robot go to the file folder? In programming the steps are called statements.

11 11 Start Programming The simplest C++ program has the form: At least one space or end-of-line must appear between adjacent words (one or more characters) and numbers but none can occur between a symbol and a word, or a symbol and a symbol. Additional spaces and end-of-lines are ignored. void main() { }

12 12 Two Types of Words Reserved Words Identifiers 1 to 255 characters (if more it will be truncated to 255) must start with a letter or an underscore consist of letters, digits and underscores void main() { int x; x = 5; } C++ is a case-sensitive language Semicolons ( ; ) denote the end of statements

13 13 Which are valid Identifiers? 3men_and_a_baby MyTax My New Name Paper.Size 4_Me _4Me int Int Integer _ _ _ Tom&Jerry _Salary! A gghdjtjhgjfg Epsilon New-life                

14 14 Input and Output Input and Output Library: iostream #include using namespace std; int main() { int x,y; cin >> x >> y; cout << x + y; return 0; } InputOutput

15 15 Output – The command “cout” i.e. will display on the screen: cout << ”……………” My name is George where “<<” is the output operator. cout << ”My name is George”;

16 16 A complete program Note: ”Hello world” is called a string – a set of characters #include using namespace std; int main() { cout << ”Hello world”; return 0; } Output: Hello world

17 17 Another Example #include using namespace std; int main() { cout << ”Hello” << ”My name is George”; return 0; } Note: If you want to leave a space between the words Hello and My you must add it either after Hello or before My, i.e. cout << ”Hello ” << ”My name is George”; Output: HelloMy name is George

18 18 Is this different? #include using namespace std; int main() { cout << ”Hello”; cout << ”My name is George”; return 0; } Note: It does not change the line unless we ask it to. Output: HelloMy name is George

19 19 Changing the line We can change the line using the special word “endl”. #include using namespace std; int main() { cout << ”Hello” << endl; cout << ”My name is George”; return 0; } Output: Hello My name is George cout << ”Hello” << endl << ”My name is George”; Same output:

20 20 Structure of cout where p 1, p 2, … p n are parameters. What is the output of the following statements? cout << p 1 << p 2 << … << p n ; cout << ”I am” << ”a student”; cout << ” of:” << endl << endl << ”C”; cout << ”++” << endl << I ama student of: C++

21 21 Special characters ’\n’newline ’\b’backspace ’\0’null ’\”’double quote ’\t’tab ’\r’return ’\’’single quote ’\\’backslash How can we display the following output? He said: ”I love you” cout << ”He said: ”I love you””; Error. Why? cout << ”He said: \”I love you\””; Correct:

22 22 Special Characters What is the output of the following statement? cout << ”Harry Potter\nis very-very\n\nFAMOUS”; Harry Potter is very-very FAMOUS

23 23 Three types of Errors: Syntax Errors (Compile errors) Logical errors Run-time errors Errors

24 24 Comments, Remarks It is very useful to include comments in a program for the benefit of the human reader. Any sequence of characters enclosed between the symbols /* and */, or after the symbols // in the same line, is interpreted as a comment and has no effect upon the action of the program. A comment may appear at any point in your program at which a space would be legal. /* A program to display “Hello World” Programmer: A.Savva */ #include using namespace std; void main() { // The main program cout << ”Hello”; // Output return 0; }

25 25 Numbers What is the output of the following statements? cout << ”5”;5 Statement Output cout << ”5 + 6”; cout << 5;5 cout << 5 + 6; 11 cout << 5 << ” + ” << 6 << ” = ” << 5 + 6; = 11

26 26 Numbers Integers Reals

27 27 Integers Integers come in 3 sizes: short – at least 16 bits int long – at least 32 bits There is no requirement that long is strictly longer that short (but cannot be shorter). The expression sizeof( ) returns the size of the DataType expressed as a multiple number of the size of char. Thus the statement cout << sizeof(char); will always display 1. If the statement cout << sizeof(long); displays 4 it means that the size of long is 4 times the size of char.

28 28 Choose the right data-type Space Shuttle Challenger, 28 Jan 1986

29 29 Integers (Decimal, Octant, Hex) Octant (base 8) constants are specified by prefixing the number with a zero digit, and hexadecimal (base 16) constants can be specified by prefixing the number with “0x”. Codewill displayReason cout << 34;34 cout << 034;28 34 octant = 28 decimal cout << ; is octant, 10 is decimal cout << ; = 044 = 36 cout << 096;Error Digit 9 is illegal in octant numbers cout << 0x45;69 45 hexadecimal = 69 decimal cout << 0xA8F3;43251 A8F3 hexadecimal = decimal

30 30 Reals There are two ways to represent a real number: Fixed point formFloating point form e E e3

31 31 Floating-point Reals where x is an integer or fixed point real and y is an integer. The letter "E" is interpreted as "times 10 to the power". So 4.576E2 = × 10 2 = i.e E2 = E-5 = E9 = xEy OR xey

32 32 Fixed-point form Output A real is displayed in a fixed-point form if : the integer part of the real has at most 7 digits. The number will be displayed in at most 7 character positions. the first non-zero digit is within the first 6 positions (including the decimal point). The output will have the leading zeros followed by 6 more digits starting from the first non-zero digit. Zeros at the end of the number will not appear in the output. Codewill display cout << ; cout << ; cout << ; cout << ; cout << e3; cout << ; cout << ;0.012 cout << e-2;0.012

33 33 Floating-point form Output Otherwise a real number will be displayed in a floating- point form as:. e ± _ i.e e Codewill display cout << ; e+009 cout << ; e-008 cout << ;1.2e-008 cout << ; e-008 cout << ;1.234e+013

34 34 Formatted Output Library: iomanip setw(n) Sets minimum field width on NEXT output. setfill(ch) Only useful with setw. If a value does not entirely fill a field, the character ch will be used to fill in the other characters. Default value is blank. Same effects as cout.fill(ch). Applies to ALL. setprecition(n) Sets the number of digits printed to the NEXT real number. Equivalent to cout.precision(n).

35 35 Formatted Output Output: ppp #include using namespace std; int main() { cout << setw(5) << 3 << endl; cout << setw(5) << setfill(’0’) << 78 << setw(4) << 2 << endl; cout << setw(5) << setfill(’0’) << 78 << setw(4) << setfill(’p’) << 2 << endl; cout << setprecition(4) << << endl; return 0; }

36 36 Data Types Data Types Indicates what type of information will be stored in the allocated memory space. Data type int short long float double bool char Values Whole Number Whole number in the range -32,768 to 32,767 Whole number in the range -2,147,483,648 to 2,147,483,647 Floating point number with 6 digits accuracy Floating point number with 14 digits accuracy true or false A single ASCII character ( ) Bytes in Memory 2 or

37 37 Signed and Unsigned Integers Default is signed signed int x; unsigned long y; x can take values from -2 bits-1 to 2 bits-1 -1 y can take values from 0 to 2 bits -1 Long Reals Only with double not with float long double z;

38 38 Declarations and Memory i.e. char Name[20]; int Counter; const double DISCOUNT_RATE = 0.5; Memory NameCounter DISCOUNT_RATE 0.5

39 39 Constants const = ; #include using namespace std; int main() { const int x = 5; const int y = 7, z = 3; cout << x << ”,” << x + 1 << endl; cout << x + y + z; return 0; } 5,6 15

40 40 Why Using Constants? #include using namespace std; int main(){ const int a = 5, b = 2; cout << a << ”+” << b << ”=” << a+b << endl; cout << a << ”-” << b << ”=” << a-b << endl; cout << a << ”*” << b << ”=” << a*b << endl; cout << a << ”/” << b << ”=” << a/b << endl; return 0; } 5+2=7 5-2=3 5*2=10 5/2=2

41 41 User-defined constants Examples: const int threenines = 999; const int retirementage = 65; const double pi = ; const float Bloodheat = 37.0; const double tinynumber = 1E-20; const int Emergency = threenines; const long Population = ;

42 42 Constants #define #include using namespace std; int main() { // no semicolon #define MAX 10 // no semicolon const int Dozen = 12; cout << MAX + Dozen; return 0; } 22

43 43 Variables At Run-time: Constants cannot change their values. Variables can change their values many times. ; i.e. double Salary; int x, y; char c;

44 44 Values to Variables A variable can be assigned a value by the assignment statement initializing values input values

45 45 The Assignment Statement i.e. Num = 6 – 5 * 3; Total = Number1 + Number2 – MAX_NUMS; i = 0; Num = Num + (4 – 6 * Num); int int x = 5; = = ; In C++ you can assign a value at declaration

46 46 Variables Example #include using namespace std; int main() { const int MAX = 100; int x, y = MAX - 1; x = y + 1; cout << x << y; int total = x + y; cout << total; x = y = total = 0; cout << x; return 0; } In C++ you can declare variables anywhere = can be used many times in a statement.

47 47 Initializing Values int num(12); i.e. int x (4); int y (x + 3 * 2); int total (x + y); cout << total; ( ); ( ); 14

48 48 Input – The command “cin” i.e. will read a value for variable x, and a value for variable y. cin >> var 1 >> var 2 >> … >> var n where “>>” is the input operator. cin >> x >> y;

49 49 Input Example #include using namespace std; void main() { int x,y; cin >> x >> y; cout << x << ” + ” << y << ” = ” << x + y; } = 17 Input values in RED. Program holds.

50 50 A Better Program #include using namespace std; void main() { int x,y; cout << ”Enter two Numbers: ”; cin >> x >> y; cout << x << ” + ” << y << ” = ” << x + y; } Enter two numbers: = When we want input from the user we should display some output explaining what the input should be.

51 51 Arithmetic Operations +Addition – Subtraction *Multiplication /Division * 2 =11 (5 + 3) * 2 =16

52 52 Order of Operations 1.Brackets 2.Multiplication ( * ) and Division ( / ) 3.Addition ( + ) and Subtraction ( – ) 4.Assignment Statement ( = )

53 53 Expressions Write the following mathematical expressions in C++: P = (n*(n-1)*(n-2)+2)/(3*(n-3)); x = (-b+sqrt(b*b – 4*a*c))/(2*a);

54 54 Calculations – Left-to-right / 2 – 6 * 3 = ( 2 - ( ) * ) * 2 = 12 / 2 * 3 = 12 / ( 2 * 3 ) = ( ( ) * ( ( ) / ( 7 – 4 ) * 2 ) ) / 6 =

55 55 Post-increment x++; // Increases x by 1, i.e. x = x + 1; Post-decrement x--; // Decreases x by 1, i.e. x = x - 1; Pre-increment ++x; // Increases x by 1, i.e. x = x + 1; Pre-decrement --x; // Decreases x by 1, i.e. x = x - 1; ++Increase the value of a variable by one. - -Decrease the value of a variable by one. Increment - Decrement Operators

56 56 Increment - Decrement Operators The difference is when they are used inside expressions. Pre-operators: will increase/decrease the variable and then evaluate the expression. Post-operators: will evaluate the expression and then increase/decrease the variable. int x, a = 5; x = a++; int x, a = 5; x = ++a; x = 5, a = 6 x = 6, a = 6 int x, a = 5; x = a--; int x, a = 5; x = --a; x = 5, a = 4 x = 4, a = 4

57 57 Order of Operations 1.Brackets ++var - - var +exp -exp 2.Prefix operators ( ++var, - - var, +exp, -exp ) ( / ) 3.Multiplication ( * ) and Division ( / ) +– ) 4.Addition ( + ) and Subtraction ( – ) = 5.Assignment Statement ( = ) var++var- - ) 6.Postfix operators ( var++, var- - )

58 58 Increment - Decrement Operators int x, a = 5, b = 10; x = a b; int x, a = 5, b = 10; x = a++ + b++; x = 14, a = 6, b = 9 x = 15, a = 6, b = 11 int x, a = 5, b = 10; x = ++a + ++b; x = 17, a = 6, b = 11

59 59 More Examples int x, a = 5; x = a a; x = 0, a = 5 int x, a = 5; x = a a + ++a; x = 15, a = 6 int x, a = 5; x = a++ + (--a + ++a); x = 15, a = 6 int x, a = 2; x = (++a + ++a) + ++a; x = 13, a = 5 int x, a = 2; x = ++a + (++a + ++a); x = 15, a = 5

60 60 Avoid complex statements int x, a = 2; x = (++a + ++a) + ++a; x = 13, a = 5 int x, a = 2; x = ++a + (++a + ++a); x = 15, a = 5 int x, a = 2; x = (++a + 1) + ++a; x = 9, a = 4 Not as expected int x, a = 2; x = ++a + (1 + ++a); x = 9, a = 4

61 61 More Examples (Be careful) int x, a = 5; x = a++-++a; x = 0, a = 7 int x, a = 5; x = a+++--a; x = 8, a = 5 int x, a = 5; x = a+++++a; Error int x, a = 5; x = a+++ ++a; x = 12, a = 7 int x, a = 5; x = a++---a; Error int x, a = 5; x = a++- --a; x = 0, a = 5

62 62 Mathematical Functions Library: cmath abs(x) = |x| sin(x) cos(x) tan(x) asin(x) = sin -1 x acos(x) = cos -1 x atan(x) = tan -1 x exp(x) = e x log(x) = log e x sqrt(x) =

63 63 More Functions int(x) – Returns the integer portion x pow(x,y) – Returns x y The Round function int(x + 0.5) – Rounds +ve x to the nearest integer int(x – 0.5) – Rounds –ve x to the nearest integer The Power function: a b = e b log a exp(b * log(a)) – Returns a b

64 64 Integer Division ( / ) & Remainder ( % ) = 5 2 – 3 = -1 2 * 3 = / 3.0 = / 3.0 = / 3 = / 3 = 0 20 / 8 = 2 20 % 8 = 4

65 65 Exersises 16 / 4 = 17 / 4 = 18 / 4 = 19 / 4 = 20 / 4 = 21 / 4 = 22 / 4 = 23 / 4 = 24 / 4 = % 4 = 17 % 4 = 18 % 4 = 19 % 4 = 20 % 4 = 21 % 4 = 22 % 4 = 23 % 4 = 24 % 4 = / 6 = -23 / 6 = 23 / -6 = -23 / -6 = 23 % 6 = -23 % 6 = 23 % -6 = -23 % -6 =

66 66 More Exercises 27 / 6 = 27 % 6 = 5 / 21 = 5 % 21 = 4 / 0 = 4 % 0 = Error 63 / 10 = 63 % 10 = 3 / 10 = 3 % 10 =

67 67 Order of Operations 1.Brackets 2.Prefix operators ( ++var, --var, -exp, +exp ) 3.Multiplication ( * ) and Division ( / ) and Remainder ( % ) 4.Addition ( + ) and Subtraction ( – ) 5.Assignment Statement ( = ) 6.Postfix operators ( var++, var-- )

68 68 Exercises 35 / 8 % 3 = 35 / (8 % 3) = 12 % (7 / 3) = 12 % 7 / 3 = (12 % 7) / 3 = % 7 = / 7 = * 8 % 5 = 4 * ( 8 % 5) = 33 % 5 * 2 = 8 % 5 * 4 = 8 % (5 * 4) = * (12 – 4 * 11 % 6 * 4 / 3) = 23

69 69 Swap Variable Values What is the output of the following statements? Will the values of a and b be swapped? int a = 5, b = 8; a = b; b = a; cout << a << ”, ” << b; We must use a Temporary Variable: int a = 5, b = 8, temp; temp = a; a = b; b = temp; cout << a << ”, ” << b;

70 70 The Assignment Statement += ; = + ; –= ; = – ; *= ; = * ; /= ; = / ; %= ; = % ; ?= ; where ? is a binary operator (i.e. +, -, *, /, %, etc.) Expression same as

71 71 Examples x = 5; x = 6 – 4 * 3; x += 5; // same as x = x + 5; x –= 5; // same as x = x – 5; x *= 5; // same as x = x * 5; x /= 5; // same as x = x / 5; x += * 2; // same as x = x + (5 + 3 * 2); X –= 5 – 3; // same as x = x – (5 – 3);

72 72 Examples int a = 3, b = 5; a += b; a = 8, b = 5 int a = 3, b = 5; a -= b; a = -2, b = 5 int a = 3, b = 5; a *= b – (b / 2); a = 9, b = 5 int a = 3, b = 5; a += b++; a = 8, b = 6 int a, b = 5, c = 3; a = b -= c; a = 2, b = 2, c = 3 int a=3, b=5, c=4; a += b -= --c * 2; a = 2, b = -1, c = 3

73 73 The Data-Type “char” In C++ the type char is described as being an integer.Examples char ch; ch = 66; cout << ch; char ch; ch = ’A’; cout << ch; char ch; ch = ’?’; cout << ch; int x; x = ’3’; cout << x; Output: A Output: ? Output: B Output: 51

74 74 ASCII code 32SP51370F89Y108l 33!52471G90Z109m 34"53572H91[110n 35#54673I92\111o 36$55774J93]112p 37%56875K94^113q 38&57976L95_114r 39'58:77M96`115s 40(59;78N97a116t 41)60<79O98b117u 42*61=80P99c118v 43+62>81Q100d119w 44,63?82R101e120x 46.65A84T103g122z 47/66B85U104h123{ 48067C86V105i124| 49168D87W106j125} 50269E88X107k126~

75 75 Examples int c; c = ’3’ + 1; cout << c; char c; c = ’d’; cout << c; char c; c = ’d’; cout << int(c); char c; c = ’3’ + ’1’; cout << c; Output: d Output: 100 Output: 52 Output: d int c; c = ’d’; cout << c; Output: 100 char c; c = ’+’ - 1; cout << (int)c; Output: 42 char c; c = ’3’ + 1; cout << c; Output: 4

76 76 Type Cast double x = 4; x += 2 / 3; cout << x; Output: 4 double x = 4; x += 2.0 / 3; cout << x; Output: double x = 4; x += (double)2 / (double)3; cout << x; Output: double x = 4; x += 2 / 3.0; cout << x; Output: double x = 4; x += 2.0 / 3.0; cout << x; Output: double x = 4; x += (double)2 / 3; cout << x; Output:

77 77 Real constants are Double Warning but not an error: truncation from 'const double' to 'float‘ No Warning Also No Warning float x = 4.2; x += 2.7; float x = 4.2; x += 1; double x = 4.2; x += 2.7; float x = 4.2; x += (float)2.7; float x = 4; x += 1;

78 78 Converting to Integer Error: int x = 5.2; Correct: int x = (int) 5.2;

79 79 Comparison of C and C++ #include void main() { int x,y; printf(”Enter two Numbers: ”); scanf(”%d %d”, &x, &y); printf(”%d + %d = %d”, x, y, x + y); } #include using namespace std; void main() { int x,y; cout << ”Enter two Numbers: ”; cin >> x >> y; cout << x << ” + ” << y << ” = ” << x + y; } C C++

80 80 Anatomy of a C/C++ program A program in C/C++ may consist of one or more files: Program source code files ( myprog.c, myprog.cpp ) Contain blocks of code, data declarations, etc. One of the files has a function called main(), where the program will start executing. Header files ( header.h ) Contain definitions that are common to many source files. Source files usually #include header files (equivalent to replacing their content at that location). Libraries (names may vary) Contain precompiled modules used in many programs They are essential because C and C++ do not have complex capabilities built-in (e.g. input/output).

81 81 Compiling a Program Pre-process include header files translate constants etc Compile into object modules Link modules combine object files and libraries produce executable program PREPRO- CESSOR C/C++ source program(s) Header files Object files LINKER COMPILER Executable Library files abc 010 abc 010

82 82 Include Files #include ”MaxMin.c” int main() { cout << max(3,8); return 0; } #include using namespace std; int max(int a, int b) { if (a > b) return a; else return b; } MaxMin.cMyprog.cpp


Download ppt "Programming in C++ Lecture Notes 1 – Getting Started Andreas Savva."

Similar presentations


Ads by Google