1.51k likes | 2.12k Views
Programming in C++. Lecture Notes 1 – Getting Started. Andreas Savva. What is a Computer?. Is it a machine with a fantastic brain and incredible intelligence? Of course NOT.
E N D
Programming in C++ Lecture Notes 1 – Getting Started Andreas Savva
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.
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 <iostream> using namespace std; void main() { int a, b; cout << ”Enter two numbers”; cin >> a >> b; cout << a << ” + ” << b << ” = ” << a+b; }
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. • 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.
C++ compiler run execute What is a Compiler? • 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. #include <iostream> using namespace std; void main() { cout << ”Hello World”; } • 10110110 11010011 • 10110011 00010001 • 11001111 11110000 • 100 10010010 • 11010100 00010001 • . . .
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. History
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-stepsolution to a problem
Mathematical Example • Problem: What is the value ofx in the following equation? 5x – 10 = 30 • Algorithm (Solution): Step 1:5x = 30 + 10 Step 2:5x = 40 Step 3:x = 40/5 Step 4:x = 8
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. • Step7:Serve with vanilla ice-cream.
Algorithm Step 1:Move 3 squares and turn right. Step2:Move 1 square and turn left. Step3:Move 2 squares and turn left. Step4:Move 2 squares and turn right. etc. The Problem: How will the robot go to the file folder? In programming the steps are called statements.
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() { }
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
Which are valid Identifiers? 3men_and_a_baby MyTax My New Name Paper.Size 4_Me _4Me int Int Integer _ _ _ Tom&Jerry _Salary! A123456789 gghdjtjhgjfg Epsilon New-life
Input Output Input and OutputLibrary: iostream #include <iostream> using namespace std; int main() { int x,y; cin >> x >> y; cout << x + y; return 0; }
My name is George Output – The command “cout” cout << ”……………” where “<<” is the output operator. • i.e. • will display on the screen: cout << ”My name is George”;
Hello world A complete program #include <iostream> using namespace std; int main() { cout << ”Hello world”; return 0; } Output: • Note: • ”Hello world” is called a string – a set of characters
HelloMy name is George Another Example #include <iostream> using namespace std; int main() { cout << ”Hello” << ”My name is George”; return 0; } Output: • 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”; • cout << ”Hello” << ” My name is George”;
HelloMy name is George Is this different? #include <iostream> using namespace std; int main() { cout << ”Hello”; cout << ”My name is George”; return 0; } Output: • Note: • It does not change the line unless we ask it to.
Hello My name is George Changing the line • We can change the line using the special word “endl”. #include <iostream> using namespace std; int main() { cout << ”Hello” << endl; cout << ”My name is George”; return 0; } Output: Same output: cout << ”Hello” << endl << ”My name is George”;
I ama student of: C++ !+-%45 @ Structure of cout cout << p1 << p2 << … << pn ; where p1, p2, … pn are parameters. What is the output of the following statements? cout << ”I am” << ”a student”; cout << ” of:” << endl << endl << ”C”; cout << ”++” << endl << ”!+-%45 @”;
Error. Why? Correct: cout << ”He said: ”I love you””; cout << ”He said: \”I love you\””; He said: ”I love you” Special characters • ’\t’ tab • ’\r’ return • ’\’’ single quote • ’\\’ backslash • ’\n’ newline • ’\b’ backspace • ’\0’ null • ’\”’ double quote How can we display the following output?
Harry Potter is very-very FAMOUS Special Characters What is the output of the following statement? cout << ”Harry Potter\nis very-very\n\nFAMOUS”;
Errors • Three types of Errors: • Syntax Errors (Compile errors) • Logical errors • Run-time errors
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 <iostream> using namespace std; void main() { // The main program cout << ”Hello”; // Output return 0; }
Numbers What is the output of the following statements? Output Statement cout << ”5”; 5 cout << ”5 + 6”; 5 + 6 cout << 5; 5 cout << 5 + 6; 11 cout << 5 << ” + ” << 6 << ” = ” << 5 + 6; 5 + 6 = 11
Numbers Integers 5 123 -12 98765432 Reals 3.6 123.678 -0.000001 9876543.2 34.0 34.0
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(<DataType>) 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.
Choose the right data-type Space Shuttle Challenger, 28 Jan 1986
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”.
Reals • There are two ways to represent a real number: Fixed point formFloating point form 3.1 1.6e7 0.00001 45E-2 123.56 -123.1e3
Floating-point Reals xEy OR xey 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 = 4.576 × 102 = 457.6 i.e. • -3.478216E2 = -347.8216 • 1E-5 = 0.00001 • 7.2E9 = 7200000000.0
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.
Floating-point form Output • Otherwise a real number will be displayed in a floating-point form as: .e±_ i.e. 1.23456e-005
Formatted Output #include <iostream> #include <iomanip> 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) << 12.45878 << endl; return 0; } Output: 3 000780002 00078ppp2 12.46
Data TypesIndicates 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 ( 0 - 255 ) Bytes in Memory 2 or 4 2 4 4 8 1 1
Signed and Unsigned Integers • Default is signed signed intx; unsigned longy; • x can take values from -2bits-1 to 2bits-1-1 • y can take values from 0 to 2bits-1 Long Reals • Only with double not with float • long doublez;
Memory Declarations and Memory i.e. char Name[20]; int Counter; const double DISCOUNT_RATE= 0.5; Name Counter DISCOUNT_RATE 0.5
5,6 15 Constants const <DataType> <Identifier> = <value>; #include <iostream> using namespace std; int main() { constint x = 5; constint y = 7, z = 3; cout << x << ”,” << x + 1 << endl; cout << x + y + z; return 0; }
5+2=7 5-2=3 5*2=10 5/2=2 Why Using Constants? #include <iostream> using namespace std; int main(){ constint 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; }
User-defined constants Examples: constint threenines = 999; constint retirementage = 65; const double pi = 3.14159; const float Bloodheat = 37.0; const double tinynumber = 1E-20; const int Emergency = threenines; constlong Population = 100000;
22 Constants #define <identifier> <value> #include <iostream> using namespace std; int main() { #define MAX 10// no semicolon constint Dozen = 12; cout << MAX + Dozen; return 0; }
Variables At Run-time: • Constants cannot change their values. • Variables can change their values many times. <DataType> <Identifier>; • i.e. • double Salary; • int x, y; • char c;
Values to Variables • A variable can be assigned a value by • the assignment statement • initializing values • input values
The Assignment Statement i.e. Num = 6 – 5 * 3; Total = Number1 + Number2 – MAX_NUMS; i = 0; Num = Num + (4 – 6 * Num); int x = 5; <Variable> = <Expression>; In C++ you can assign a value at declaration
Variables Example #include <iostream> using namespace std; int main() { constint 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.
14 Initializing Values int num(12); i.e. int x (4); int y (x + 3 * 2); int total (x + y); cout << total; <Data Type> <Variable>( <Expression>);
Input – The command “cin” cin >> var1 >> var2 >> … >> varn where “>>” is the input operator. • i.e. • will read a value for variable x, • and a value for variable y. cin >> x >> y;
Input Example #include <iostream> using namespace std; void main() { int x,y; cin >> x >> y; cout << x << ” + ” << y << ” = ” << x + y; } 5 12 5 + 12 = 17 Input values in RED. Program holds.
A Better Program #include <iostream> using namespace std; void main() { int x,y; cout << ”Enter two Numbers: ”; cin >> x >> y; cout << x << ” + ” << y << ” = ” << x + y; } 5 12 Enter two numbers: 5 + 12 = 17 When we want input from the user we should display some output explaining what the input should be.