Basic Elements of Computer Program Week 2
Topic 2 - Outline Identifier Data types Arithmetic Operator Arithmetic Expression Assignment Statement IO Statement C++ Program Structure Programming Process Control Structure Topic 2 - Outline
What? Name assigned by user Identifier What? Name assigned by user Why? To represent programming entities such as variable, function or constant Rules? The 1st character must be an alphabet letter or an underscore ‘_’. Can only consists of letters, digits and underscore ‘_’. Cannot use C++ reserved words/keywords There must be no blank space character Identifiers are case sensitive
Reserved Word It has predefined meaning for the language. int char long float double default case for void break const else if private do goto switch while public class return continue
Variable Rules? What? Memory location in computer. Must begin with a letter or underscore (_), and may only contain only letters, underscore, or digits. Variable name cannot be a keyword. Variable name cannot consists of more than 31 characters. Variable What? Memory location in computer. Why? To store data/instructions How? Store a data at a time Variable value might be changed during program execution Must declare before used Must assign / initialize a value to variable before use it Rules?
Variable Declaration Syntax: data_type variable; Example: int x; int number1, number2, number3; Please take note of the coma to Separate the variable list & Semicolon to end the variable declaration
Variable: what happen when a variable is declared?? The compiler allocates a memory space for the variable. In the memory space, name, data type and value of the variable are stored. ex. Allocates a memory of 4 bytes with address 00000004. the information stored in the memory space are variable name (area), data type (float). float area;
Constant Values that are fixed and do not change throughout program execution Declaring a constant: Using const keyword
Constant Declaration Syntax: const data_type constant_name = value; const float PI = 3.14; Data type const keyword Constant_name value
Legal and Illegal Identifiers The following are legal identifiers in C++: first conversion payRate
Data Types Numeric Int Float Double Character Char
Numeric Data Type Integer Floating point Whole number – positive, zero or negative C++ keyword int, long int, long long int Floating point Numbers with decimal points float, double int area; float area;
int Data Type Examples: -6728 78 Positive integers do not have to have a + sign in front of them No commas are used within an integer Commas are used for separating items in a list
float, double Data Type Is a decimal number that contains the decimal point (.)or the exponent (e) or both. float data type can hold values up to six or seven significant digit accuracy. double data type can hold values up to 14 or 15 significant digit accuracy.
Character Data Type char Single character Example: char name; Store one character value C++ keyword char Example: char name;
char Data Type The smallest integral data type Used for characters: letters, digits, and special symbols Each character is enclosed in single quotes Some of the values belonging to char data type are: 'A', 'a', '0', '*', '+', '$', '&' A blank space is a character and is written ' ', with a space left between the single quotes
char[] Data Type Sequence of characters It stores sequence of zero or more characters Enclosed in double quotation marks Null: no characters is stored. Each character has relative position Position of first character is 0, the position of the second is 1, and so on Length: number of characters in a sequence C++ keyword char[] char name[5]; Note: the double quotes and Single quotes
Initialization A variable can be initialized to any value as long as the value’s data type matches the variable’s data type. Syntax: datatype variable [ = initialValue ]; Examples: int age = 0; float rate = 0.0; double sale = 0.0; char grade = ‘ ’; char company[20] =“ ”;
SUMMARY OF DATA TYPE Category Data types Keywords Bits Range Examples Numeric integer int 16 -32768 to 32767 45, 0, -10 long integer long 32 -4294967296 to 4294967295 -37876 floating point Float 6 digit precision 32.88, -89.5 double floating point double 64 12 digit precision 12.7866754 Character char 8 ‘c’, ‘v’ Sequence of character char[ ] “hello”, “sarah”
OPERATORS A Symbol that tells the compiler to perform specific mathematical or logical manipulations Types of operator: Arithmetic operators Assignment operators Relational operators Logical operators
Arithmetic Operator Addition + Subtraction - Division / Multiplication * Modulus %
Precedence & Associativity Precedence of operator Precedence rules: specify which operator is evaluated first when two operators with different precedence are adjacent in an expression. Associativity rules: specify which operator is evaluated first when two operators with the same precedence are adjacent in an expression. Highest Operators Associativity () Left to right * / % + - Lowest
Precedence & Associativity Example 1: Example 2: 4 + 2 * 3 3 * 4 / 2
Arithmetic Expression: Operands & Operator One of the input of an operator Example: 3 + 6 Operator Operand
Several rules that you need to follow to evaluate arithmetic expression: If one or more operand(s) in an arithmetic expression has/have data type double, the resulting expression is of data type double. If all operands in arithmetic expression are of type int, the resulting expression is of type int.
Arithmetic operators Require two operands Ex. +, -, *, /, % For the modulus (remainder) operator, all of its operands must be integer only. Be careful of the operands’ data types when using division operator. For example, Expressions Output 7 / 4 1 7.0 / 4 1.75 -1 / 4 -1 / 4.0 -0.25
Example 3 * 7 – 6 + 2 * 5 / 4 + 6 (3 * 7) – 6 + ( (2 * 5) / 4 ) + 6 = 21 – 6 + (10 / 4) + 6 (Evaluate *) = 21 – 6 + 2 + 6 (Evaluate /) = 15 + 2 + 6 (Evaluate -) = 17 + 6 (Evaluate first +) = 23 (Evaluate +)
Assignment statement Assigns a value to respective memory space allocated to a variable. May involve arithmetic expressions. Syntax: Examples variable = value/ variable; a = 3; x = 5.6; y = ‘z’; pi = 3.14; 5 = z; //invalid!!
Assignment statement Syntax: The expressions may contains variables, constant and arithmetic operators, Example: variable = expression; float radius, pi, area; radius = 3; pi = 3.14; area = pi * radius * radius;
Assignment statement A sequence of character: Using assignment statement: Using strcpy function: char a [20] = “sample string”; char a [20]; strcpy(a ,“sample string”);
Writing algebraic expression using C++ statement. Algebraic statement pow(a,b) ab sqrt(a - b) √ (a – b) abs(x - y) | x – y |
Arithmetic Expression Examples Algebraic Expression Arithmetic Expression 17– 12 + 74 23 – 7 5 23 – 7 / 5 12 + 1 + 76 4 (12 + 1 + 76) / 4 42 pow ( 4 , 2 ) ( a – b) sqrt (a – b ) x – y abs ( x – y )
Examples: -b ± √b2 – 4ac 2a Solution : Or -b + sqrt ((pow (b,2) – (4 * a * c))/(2 * a) Or -b - sqrt (b * b – 4 * a * c) / (2 * a)
IO Statement: Output statements Used to display information on screen. The header file iostream.h must be included in the preprocessor directives. Syntax: The symbol << is called insertion operator cout<<variable<<variable<<…<<variable;
Output statements Sample output: … year = 1999; cout << “my year of birth is”<<year; my year of birth is 1999
cout << (2003 – year); Output statements The operand after the symbol << can be a constant, variable or an expression. The following are escape sequence which can be used in a string literal in a cout statement. cout << (2003 – year); \n – new line \’ – single quote \t - tab \” - double quote \b - backspace \\ - backslash
IO Statement: Input statement Used to read in information from a keyboard. Syntax: The symbol >> is called an extraction operator. The operand after the symbol >> must be a variable. cin>>variable>>variable>>…>>variable;
Input statement: example … cout << “enter your age and matric number:”; cin>>age>>matric;
Input statement cin only takes input up to the first blank (ignores whitespace such as blanks, tabs). When reading a sequence of character (including whitespace), used: cin.getline(name, 20);
Example Using cin statement: Sample output cout<< “Enter your name:”; cin>>name; cout<< “Welcome, ”<<name<<“!”; Enter your name: Adam Ahmad Welcome, Adam!
Example Using cin.getline statement: Sample output cout<< “Enter your name:”; cin.getline(name,20); cout<< “Welcome, ”<<name<<“!”; Enter your name: Adam Ahmad Welcome, Adam Ahmad!
C++ Program Structure Components of the program Preprocessor directives Constant and type definition section Main program heading Begin block Main block Declaration section Statement section End block
Syntax #include <headerFileName> const <dataType><identifier> = <value> dataType <identifier> <functionType> <functionName> (formal parameter list) { cout << statement; cin >> variables; }
A C++ program is a collection of one or more subprograms, called functions A subprogram or a function is a collection of statements that, when activated (executed), accomplishes something Every C++ program has a function called main
Preprocessor directives Examples: #include <iostream.h> To declares the basic C++ streams (I/O) routines. #include <math.h> Declares prototypes for the math functions and math error handlers. #include <conio.h> Declares various functions used in calling the operating system console I/O routines.
Example of program Preprocessor Directives main function #include <iostream.h> #include <conio.h> #include <string> void main() { string name; int age; cout<< "Please enter your name:\n"; cin>>name; cout<< "Please enter your age:\n"; cin>>age; cout<<endl; cout<< "Your name is:"<<name<<endl; cout<< "Your age is:"<<age<<endl; getch(); } Preprocessor Directives main function
Programming process
Compilation process
Running a program
Control Structure: Sequential Control Structure The simplest of all the structures The program instruction has one starting point and one ending point. Each step is carried out in order of their position and is only done once.
Sequential Control Structure Flowchart Begin Fill a kettle with water Boil the water in the kettle Put tea leaves in the pot Pour boiling water into the pot End
Control Structure: Selection Control Structure The selection structure allows comparison of expression, and based on the comparison, to select certain course of action
Selection Control Structure Telephone rings? F T Continue reading Answer phone
Control Structure: Repetition control structure The repetition structure allow a sequence of instructions to be executed repeatedly until a certain condition is achieved.
Repetition control structure beg has items? false true Take item out
Control Structure: Modular Is a method of dividing a problem into separate tasks, each with a single purpose. Separate task with a single purpose = FUNCTION
Modular Company IT Accountancy Human resource